1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 3 * Copyright (c) 2016 Facebook 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io 5 */ 6 #include <uapi/linux/btf.h> 7 #include <linux/bpf-cgroup.h> 8 #include <linux/kernel.h> 9 #include <linux/types.h> 10 #include <linux/slab.h> 11 #include <linux/bpf.h> 12 #include <linux/btf.h> 13 #include <linux/bpf_verifier.h> 14 #include <linux/filter.h> 15 #include <net/netlink.h> 16 #include <linux/file.h> 17 #include <linux/vmalloc.h> 18 #include <linux/stringify.h> 19 #include <linux/bsearch.h> 20 #include <linux/sort.h> 21 #include <linux/perf_event.h> 22 #include <linux/ctype.h> 23 #include <linux/error-injection.h> 24 #include <linux/bpf_lsm.h> 25 #include <linux/btf_ids.h> 26 #include <linux/poison.h> 27 #include <linux/module.h> 28 #include <linux/cpumask.h> 29 #include <linux/bpf_mem_alloc.h> 30 #include <net/xdp.h> 31 #include <linux/trace_events.h> 32 #include <linux/kallsyms.h> 33 34 #include "disasm.h" 35 36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 38 [_id] = & _name ## _verifier_ops, 39 #define BPF_MAP_TYPE(_id, _ops) 40 #define BPF_LINK_TYPE(_id, _name) 41 #include <linux/bpf_types.h> 42 #undef BPF_PROG_TYPE 43 #undef BPF_MAP_TYPE 44 #undef BPF_LINK_TYPE 45 }; 46 47 struct bpf_mem_alloc bpf_global_percpu_ma; 48 static bool bpf_global_percpu_ma_set; 49 50 /* bpf_check() is a static code analyzer that walks eBPF program 51 * instruction by instruction and updates register/stack state. 52 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 53 * 54 * The first pass is depth-first-search to check that the program is a DAG. 55 * It rejects the following programs: 56 * - larger than BPF_MAXINSNS insns 57 * - if loop is present (detected via back-edge) 58 * - unreachable insns exist (shouldn't be a forest. program = one function) 59 * - out of bounds or malformed jumps 60 * The second pass is all possible path descent from the 1st insn. 61 * Since it's analyzing all paths through the program, the length of the 62 * analysis is limited to 64k insn, which may be hit even if total number of 63 * insn is less then 4K, but there are too many branches that change stack/regs. 64 * Number of 'branches to be analyzed' is limited to 1k 65 * 66 * On entry to each instruction, each register has a type, and the instruction 67 * changes the types of the registers depending on instruction semantics. 68 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 69 * copied to R1. 70 * 71 * All registers are 64-bit. 72 * R0 - return register 73 * R1-R5 argument passing registers 74 * R6-R9 callee saved registers 75 * R10 - frame pointer read-only 76 * 77 * At the start of BPF program the register R1 contains a pointer to bpf_context 78 * and has type PTR_TO_CTX. 79 * 80 * Verifier tracks arithmetic operations on pointers in case: 81 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 82 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 83 * 1st insn copies R10 (which has FRAME_PTR) type into R1 84 * and 2nd arithmetic instruction is pattern matched to recognize 85 * that it wants to construct a pointer to some element within stack. 86 * So after 2nd insn, the register R1 has type PTR_TO_STACK 87 * (and -20 constant is saved for further stack bounds checking). 88 * Meaning that this reg is a pointer to stack plus known immediate constant. 89 * 90 * Most of the time the registers have SCALAR_VALUE type, which 91 * means the register has some value, but it's not a valid pointer. 92 * (like pointer plus pointer becomes SCALAR_VALUE type) 93 * 94 * When verifier sees load or store instructions the type of base register 95 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 96 * four pointer types recognized by check_mem_access() function. 97 * 98 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 99 * and the range of [ptr, ptr + map's value_size) is accessible. 100 * 101 * registers used to pass values to function calls are checked against 102 * function argument constraints. 103 * 104 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 105 * It means that the register type passed to this function must be 106 * PTR_TO_STACK and it will be used inside the function as 107 * 'pointer to map element key' 108 * 109 * For example the argument constraints for bpf_map_lookup_elem(): 110 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 111 * .arg1_type = ARG_CONST_MAP_PTR, 112 * .arg2_type = ARG_PTR_TO_MAP_KEY, 113 * 114 * ret_type says that this function returns 'pointer to map elem value or null' 115 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 116 * 2nd argument should be a pointer to stack, which will be used inside 117 * the helper function as a pointer to map element key. 118 * 119 * On the kernel side the helper function looks like: 120 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 121 * { 122 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 123 * void *key = (void *) (unsigned long) r2; 124 * void *value; 125 * 126 * here kernel can access 'key' and 'map' pointers safely, knowing that 127 * [key, key + map->key_size) bytes are valid and were initialized on 128 * the stack of eBPF program. 129 * } 130 * 131 * Corresponding eBPF program may look like: 132 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 133 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 134 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 135 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 136 * here verifier looks at prototype of map_lookup_elem() and sees: 137 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 138 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 139 * 140 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 141 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 142 * and were initialized prior to this call. 143 * If it's ok, then verifier allows this BPF_CALL insn and looks at 144 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 145 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 146 * returns either pointer to map value or NULL. 147 * 148 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 149 * insn, the register holding that pointer in the true branch changes state to 150 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 151 * branch. See check_cond_jmp_op(). 152 * 153 * After the call R0 is set to return type of the function and registers R1-R5 154 * are set to NOT_INIT to indicate that they are no longer readable. 155 * 156 * The following reference types represent a potential reference to a kernel 157 * resource which, after first being allocated, must be checked and freed by 158 * the BPF program: 159 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 160 * 161 * When the verifier sees a helper call return a reference type, it allocates a 162 * pointer id for the reference and stores it in the current function state. 163 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 164 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 165 * passes through a NULL-check conditional. For the branch wherein the state is 166 * changed to CONST_IMM, the verifier releases the reference. 167 * 168 * For each helper function that allocates a reference, such as 169 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 170 * bpf_sk_release(). When a reference type passes into the release function, 171 * the verifier also releases the reference. If any unchecked or unreleased 172 * reference remains at the end of the program, the verifier rejects it. 173 */ 174 175 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 176 struct bpf_verifier_stack_elem { 177 /* verifier state is 'st' 178 * before processing instruction 'insn_idx' 179 * and after processing instruction 'prev_insn_idx' 180 */ 181 struct bpf_verifier_state st; 182 int insn_idx; 183 int prev_insn_idx; 184 struct bpf_verifier_stack_elem *next; 185 /* length of verifier log at the time this state was pushed on stack */ 186 u32 log_pos; 187 }; 188 189 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 190 #define BPF_COMPLEXITY_LIMIT_STATES 64 191 192 #define BPF_MAP_KEY_POISON (1ULL << 63) 193 #define BPF_MAP_KEY_SEEN (1ULL << 62) 194 195 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 196 197 #define BPF_PRIV_STACK_MIN_SIZE 64 198 199 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx); 200 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id); 201 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 202 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 203 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 204 static int ref_set_non_owning(struct bpf_verifier_env *env, 205 struct bpf_reg_state *reg); 206 static void specialize_kfunc(struct bpf_verifier_env *env, 207 u32 func_id, u16 offset, unsigned long *addr); 208 static bool is_trusted_reg(const struct bpf_reg_state *reg); 209 210 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 211 { 212 return aux->map_ptr_state.poison; 213 } 214 215 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 216 { 217 return aux->map_ptr_state.unpriv; 218 } 219 220 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 221 struct bpf_map *map, 222 bool unpriv, bool poison) 223 { 224 unpriv |= bpf_map_ptr_unpriv(aux); 225 aux->map_ptr_state.unpriv = unpriv; 226 aux->map_ptr_state.poison = poison; 227 aux->map_ptr_state.map_ptr = map; 228 } 229 230 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 231 { 232 return aux->map_key_state & BPF_MAP_KEY_POISON; 233 } 234 235 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 236 { 237 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 238 } 239 240 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 241 { 242 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 243 } 244 245 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 246 { 247 bool poisoned = bpf_map_key_poisoned(aux); 248 249 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 250 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 251 } 252 253 static bool bpf_helper_call(const struct bpf_insn *insn) 254 { 255 return insn->code == (BPF_JMP | BPF_CALL) && 256 insn->src_reg == 0; 257 } 258 259 static bool bpf_pseudo_call(const struct bpf_insn *insn) 260 { 261 return insn->code == (BPF_JMP | BPF_CALL) && 262 insn->src_reg == BPF_PSEUDO_CALL; 263 } 264 265 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 266 { 267 return insn->code == (BPF_JMP | BPF_CALL) && 268 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 269 } 270 271 struct bpf_call_arg_meta { 272 struct bpf_map *map_ptr; 273 bool raw_mode; 274 bool pkt_access; 275 u8 release_regno; 276 int regno; 277 int access_size; 278 int mem_size; 279 u64 msize_max_value; 280 int ref_obj_id; 281 int dynptr_id; 282 int map_uid; 283 int func_id; 284 struct btf *btf; 285 u32 btf_id; 286 struct btf *ret_btf; 287 u32 ret_btf_id; 288 u32 subprogno; 289 struct btf_field *kptr_field; 290 s64 const_map_key; 291 }; 292 293 struct bpf_kfunc_call_arg_meta { 294 /* In parameters */ 295 struct btf *btf; 296 u32 func_id; 297 u32 kfunc_flags; 298 const struct btf_type *func_proto; 299 const char *func_name; 300 /* Out parameters */ 301 u32 ref_obj_id; 302 u8 release_regno; 303 bool r0_rdonly; 304 u32 ret_btf_id; 305 u64 r0_size; 306 u32 subprogno; 307 struct { 308 u64 value; 309 bool found; 310 } arg_constant; 311 312 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 313 * generally to pass info about user-defined local kptr types to later 314 * verification logic 315 * bpf_obj_drop/bpf_percpu_obj_drop 316 * Record the local kptr type to be drop'd 317 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 318 * Record the local kptr type to be refcount_incr'd and use 319 * arg_owning_ref to determine whether refcount_acquire should be 320 * fallible 321 */ 322 struct btf *arg_btf; 323 u32 arg_btf_id; 324 bool arg_owning_ref; 325 bool arg_prog; 326 327 struct { 328 struct btf_field *field; 329 } arg_list_head; 330 struct { 331 struct btf_field *field; 332 } arg_rbtree_root; 333 struct { 334 enum bpf_dynptr_type type; 335 u32 id; 336 u32 ref_obj_id; 337 } initialized_dynptr; 338 struct { 339 u8 spi; 340 u8 frameno; 341 } iter; 342 struct { 343 struct bpf_map *ptr; 344 int uid; 345 } map; 346 u64 mem_size; 347 }; 348 349 struct btf *btf_vmlinux; 350 351 static const char *btf_type_name(const struct btf *btf, u32 id) 352 { 353 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 354 } 355 356 static DEFINE_MUTEX(bpf_verifier_lock); 357 static DEFINE_MUTEX(bpf_percpu_ma_lock); 358 359 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 360 { 361 struct bpf_verifier_env *env = private_data; 362 va_list args; 363 364 if (!bpf_verifier_log_needed(&env->log)) 365 return; 366 367 va_start(args, fmt); 368 bpf_verifier_vlog(&env->log, fmt, args); 369 va_end(args); 370 } 371 372 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 373 struct bpf_reg_state *reg, 374 struct bpf_retval_range range, const char *ctx, 375 const char *reg_name) 376 { 377 bool unknown = true; 378 379 verbose(env, "%s the register %s has", ctx, reg_name); 380 if (reg->smin_value > S64_MIN) { 381 verbose(env, " smin=%lld", reg->smin_value); 382 unknown = false; 383 } 384 if (reg->smax_value < S64_MAX) { 385 verbose(env, " smax=%lld", reg->smax_value); 386 unknown = false; 387 } 388 if (unknown) 389 verbose(env, " unknown scalar value"); 390 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 391 } 392 393 static bool reg_not_null(const struct bpf_reg_state *reg) 394 { 395 enum bpf_reg_type type; 396 397 type = reg->type; 398 if (type_may_be_null(type)) 399 return false; 400 401 type = base_type(type); 402 return type == PTR_TO_SOCKET || 403 type == PTR_TO_TCP_SOCK || 404 type == PTR_TO_MAP_VALUE || 405 type == PTR_TO_MAP_KEY || 406 type == PTR_TO_SOCK_COMMON || 407 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 408 type == PTR_TO_MEM; 409 } 410 411 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 412 { 413 struct btf_record *rec = NULL; 414 struct btf_struct_meta *meta; 415 416 if (reg->type == PTR_TO_MAP_VALUE) { 417 rec = reg->map_ptr->record; 418 } else if (type_is_ptr_alloc_obj(reg->type)) { 419 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 420 if (meta) 421 rec = meta->record; 422 } 423 return rec; 424 } 425 426 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 427 { 428 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 429 430 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 431 } 432 433 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 434 { 435 struct bpf_func_info *info; 436 437 if (!env->prog->aux->func_info) 438 return ""; 439 440 info = &env->prog->aux->func_info[subprog]; 441 return btf_type_name(env->prog->aux->btf, info->type_id); 442 } 443 444 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 445 { 446 struct bpf_subprog_info *info = subprog_info(env, subprog); 447 448 info->is_cb = true; 449 info->is_async_cb = true; 450 info->is_exception_cb = true; 451 } 452 453 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 454 { 455 return subprog_info(env, subprog)->is_exception_cb; 456 } 457 458 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 459 { 460 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK); 461 } 462 463 static bool type_is_rdonly_mem(u32 type) 464 { 465 return type & MEM_RDONLY; 466 } 467 468 static bool is_acquire_function(enum bpf_func_id func_id, 469 const struct bpf_map *map) 470 { 471 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 472 473 if (func_id == BPF_FUNC_sk_lookup_tcp || 474 func_id == BPF_FUNC_sk_lookup_udp || 475 func_id == BPF_FUNC_skc_lookup_tcp || 476 func_id == BPF_FUNC_ringbuf_reserve || 477 func_id == BPF_FUNC_kptr_xchg) 478 return true; 479 480 if (func_id == BPF_FUNC_map_lookup_elem && 481 (map_type == BPF_MAP_TYPE_SOCKMAP || 482 map_type == BPF_MAP_TYPE_SOCKHASH)) 483 return true; 484 485 return false; 486 } 487 488 static bool is_ptr_cast_function(enum bpf_func_id func_id) 489 { 490 return func_id == BPF_FUNC_tcp_sock || 491 func_id == BPF_FUNC_sk_fullsock || 492 func_id == BPF_FUNC_skc_to_tcp_sock || 493 func_id == BPF_FUNC_skc_to_tcp6_sock || 494 func_id == BPF_FUNC_skc_to_udp6_sock || 495 func_id == BPF_FUNC_skc_to_mptcp_sock || 496 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 497 func_id == BPF_FUNC_skc_to_tcp_request_sock; 498 } 499 500 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 501 { 502 return func_id == BPF_FUNC_dynptr_data; 503 } 504 505 static bool is_sync_callback_calling_kfunc(u32 btf_id); 506 static bool is_async_callback_calling_kfunc(u32 btf_id); 507 static bool is_callback_calling_kfunc(u32 btf_id); 508 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 509 510 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id); 511 512 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 513 { 514 return func_id == BPF_FUNC_for_each_map_elem || 515 func_id == BPF_FUNC_find_vma || 516 func_id == BPF_FUNC_loop || 517 func_id == BPF_FUNC_user_ringbuf_drain; 518 } 519 520 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 521 { 522 return func_id == BPF_FUNC_timer_set_callback; 523 } 524 525 static bool is_callback_calling_function(enum bpf_func_id func_id) 526 { 527 return is_sync_callback_calling_function(func_id) || 528 is_async_callback_calling_function(func_id); 529 } 530 531 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 532 { 533 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 534 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 535 } 536 537 static bool is_async_callback_calling_insn(struct bpf_insn *insn) 538 { 539 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 540 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 541 } 542 543 static bool is_may_goto_insn(struct bpf_insn *insn) 544 { 545 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 546 } 547 548 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx) 549 { 550 return is_may_goto_insn(&env->prog->insnsi[insn_idx]); 551 } 552 553 static bool is_storage_get_function(enum bpf_func_id func_id) 554 { 555 return func_id == BPF_FUNC_sk_storage_get || 556 func_id == BPF_FUNC_inode_storage_get || 557 func_id == BPF_FUNC_task_storage_get || 558 func_id == BPF_FUNC_cgrp_storage_get; 559 } 560 561 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 562 const struct bpf_map *map) 563 { 564 int ref_obj_uses = 0; 565 566 if (is_ptr_cast_function(func_id)) 567 ref_obj_uses++; 568 if (is_acquire_function(func_id, map)) 569 ref_obj_uses++; 570 if (is_dynptr_ref_function(func_id)) 571 ref_obj_uses++; 572 573 return ref_obj_uses > 1; 574 } 575 576 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 577 { 578 return BPF_CLASS(insn->code) == BPF_STX && 579 BPF_MODE(insn->code) == BPF_ATOMIC && 580 insn->imm == BPF_CMPXCHG; 581 } 582 583 static bool is_atomic_load_insn(const struct bpf_insn *insn) 584 { 585 return BPF_CLASS(insn->code) == BPF_STX && 586 BPF_MODE(insn->code) == BPF_ATOMIC && 587 insn->imm == BPF_LOAD_ACQ; 588 } 589 590 static int __get_spi(s32 off) 591 { 592 return (-off - 1) / BPF_REG_SIZE; 593 } 594 595 static struct bpf_func_state *func(struct bpf_verifier_env *env, 596 const struct bpf_reg_state *reg) 597 { 598 struct bpf_verifier_state *cur = env->cur_state; 599 600 return cur->frame[reg->frameno]; 601 } 602 603 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 604 { 605 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 606 607 /* We need to check that slots between [spi - nr_slots + 1, spi] are 608 * within [0, allocated_stack). 609 * 610 * Please note that the spi grows downwards. For example, a dynptr 611 * takes the size of two stack slots; the first slot will be at 612 * spi and the second slot will be at spi - 1. 613 */ 614 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 615 } 616 617 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 618 const char *obj_kind, int nr_slots) 619 { 620 int off, spi; 621 622 if (!tnum_is_const(reg->var_off)) { 623 verbose(env, "%s has to be at a constant offset\n", obj_kind); 624 return -EINVAL; 625 } 626 627 off = reg->off + reg->var_off.value; 628 if (off % BPF_REG_SIZE) { 629 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 630 return -EINVAL; 631 } 632 633 spi = __get_spi(off); 634 if (spi + 1 < nr_slots) { 635 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 636 return -EINVAL; 637 } 638 639 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 640 return -ERANGE; 641 return spi; 642 } 643 644 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 645 { 646 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 647 } 648 649 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 650 { 651 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 652 } 653 654 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 655 { 656 return stack_slot_obj_get_spi(env, reg, "irq_flag", 1); 657 } 658 659 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 660 { 661 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 662 case DYNPTR_TYPE_LOCAL: 663 return BPF_DYNPTR_TYPE_LOCAL; 664 case DYNPTR_TYPE_RINGBUF: 665 return BPF_DYNPTR_TYPE_RINGBUF; 666 case DYNPTR_TYPE_SKB: 667 return BPF_DYNPTR_TYPE_SKB; 668 case DYNPTR_TYPE_XDP: 669 return BPF_DYNPTR_TYPE_XDP; 670 default: 671 return BPF_DYNPTR_TYPE_INVALID; 672 } 673 } 674 675 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 676 { 677 switch (type) { 678 case BPF_DYNPTR_TYPE_LOCAL: 679 return DYNPTR_TYPE_LOCAL; 680 case BPF_DYNPTR_TYPE_RINGBUF: 681 return DYNPTR_TYPE_RINGBUF; 682 case BPF_DYNPTR_TYPE_SKB: 683 return DYNPTR_TYPE_SKB; 684 case BPF_DYNPTR_TYPE_XDP: 685 return DYNPTR_TYPE_XDP; 686 default: 687 return 0; 688 } 689 } 690 691 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 692 { 693 return type == BPF_DYNPTR_TYPE_RINGBUF; 694 } 695 696 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 697 enum bpf_dynptr_type type, 698 bool first_slot, int dynptr_id); 699 700 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 701 struct bpf_reg_state *reg); 702 703 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 704 struct bpf_reg_state *sreg1, 705 struct bpf_reg_state *sreg2, 706 enum bpf_dynptr_type type) 707 { 708 int id = ++env->id_gen; 709 710 __mark_dynptr_reg(sreg1, type, true, id); 711 __mark_dynptr_reg(sreg2, type, false, id); 712 } 713 714 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 715 struct bpf_reg_state *reg, 716 enum bpf_dynptr_type type) 717 { 718 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 719 } 720 721 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 722 struct bpf_func_state *state, int spi); 723 724 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 725 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 726 { 727 struct bpf_func_state *state = func(env, reg); 728 enum bpf_dynptr_type type; 729 int spi, i, err; 730 731 spi = dynptr_get_spi(env, reg); 732 if (spi < 0) 733 return spi; 734 735 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 736 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 737 * to ensure that for the following example: 738 * [d1][d1][d2][d2] 739 * spi 3 2 1 0 740 * So marking spi = 2 should lead to destruction of both d1 and d2. In 741 * case they do belong to same dynptr, second call won't see slot_type 742 * as STACK_DYNPTR and will simply skip destruction. 743 */ 744 err = destroy_if_dynptr_stack_slot(env, state, spi); 745 if (err) 746 return err; 747 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 748 if (err) 749 return err; 750 751 for (i = 0; i < BPF_REG_SIZE; i++) { 752 state->stack[spi].slot_type[i] = STACK_DYNPTR; 753 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 754 } 755 756 type = arg_to_dynptr_type(arg_type); 757 if (type == BPF_DYNPTR_TYPE_INVALID) 758 return -EINVAL; 759 760 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 761 &state->stack[spi - 1].spilled_ptr, type); 762 763 if (dynptr_type_refcounted(type)) { 764 /* The id is used to track proper releasing */ 765 int id; 766 767 if (clone_ref_obj_id) 768 id = clone_ref_obj_id; 769 else 770 id = acquire_reference(env, insn_idx); 771 772 if (id < 0) 773 return id; 774 775 state->stack[spi].spilled_ptr.ref_obj_id = id; 776 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 777 } 778 779 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 780 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 781 782 return 0; 783 } 784 785 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 786 { 787 int i; 788 789 for (i = 0; i < BPF_REG_SIZE; i++) { 790 state->stack[spi].slot_type[i] = STACK_INVALID; 791 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 792 } 793 794 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 795 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 796 797 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 798 * 799 * While we don't allow reading STACK_INVALID, it is still possible to 800 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 801 * helpers or insns can do partial read of that part without failing, 802 * but check_stack_range_initialized, check_stack_read_var_off, and 803 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 804 * the slot conservatively. Hence we need to prevent those liveness 805 * marking walks. 806 * 807 * This was not a problem before because STACK_INVALID is only set by 808 * default (where the default reg state has its reg->parent as NULL), or 809 * in clean_live_states after REG_LIVE_DONE (at which point 810 * mark_reg_read won't walk reg->parent chain), but not randomly during 811 * verifier state exploration (like we did above). Hence, for our case 812 * parentage chain will still be live (i.e. reg->parent may be 813 * non-NULL), while earlier reg->parent was NULL, so we need 814 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 815 * done later on reads or by mark_dynptr_read as well to unnecessary 816 * mark registers in verifier state. 817 */ 818 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 819 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 820 } 821 822 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 823 { 824 struct bpf_func_state *state = func(env, reg); 825 int spi, ref_obj_id, i; 826 827 spi = dynptr_get_spi(env, reg); 828 if (spi < 0) 829 return spi; 830 831 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 832 invalidate_dynptr(env, state, spi); 833 return 0; 834 } 835 836 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 837 838 /* If the dynptr has a ref_obj_id, then we need to invalidate 839 * two things: 840 * 841 * 1) Any dynptrs with a matching ref_obj_id (clones) 842 * 2) Any slices derived from this dynptr. 843 */ 844 845 /* Invalidate any slices associated with this dynptr */ 846 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 847 848 /* Invalidate any dynptr clones */ 849 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 850 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 851 continue; 852 853 /* it should always be the case that if the ref obj id 854 * matches then the stack slot also belongs to a 855 * dynptr 856 */ 857 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 858 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 859 return -EFAULT; 860 } 861 if (state->stack[i].spilled_ptr.dynptr.first_slot) 862 invalidate_dynptr(env, state, i); 863 } 864 865 return 0; 866 } 867 868 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 869 struct bpf_reg_state *reg); 870 871 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 872 { 873 if (!env->allow_ptr_leaks) 874 __mark_reg_not_init(env, reg); 875 else 876 __mark_reg_unknown(env, reg); 877 } 878 879 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 880 struct bpf_func_state *state, int spi) 881 { 882 struct bpf_func_state *fstate; 883 struct bpf_reg_state *dreg; 884 int i, dynptr_id; 885 886 /* We always ensure that STACK_DYNPTR is never set partially, 887 * hence just checking for slot_type[0] is enough. This is 888 * different for STACK_SPILL, where it may be only set for 889 * 1 byte, so code has to use is_spilled_reg. 890 */ 891 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 892 return 0; 893 894 /* Reposition spi to first slot */ 895 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 896 spi = spi + 1; 897 898 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 899 verbose(env, "cannot overwrite referenced dynptr\n"); 900 return -EINVAL; 901 } 902 903 mark_stack_slot_scratched(env, spi); 904 mark_stack_slot_scratched(env, spi - 1); 905 906 /* Writing partially to one dynptr stack slot destroys both. */ 907 for (i = 0; i < BPF_REG_SIZE; i++) { 908 state->stack[spi].slot_type[i] = STACK_INVALID; 909 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 910 } 911 912 dynptr_id = state->stack[spi].spilled_ptr.id; 913 /* Invalidate any slices associated with this dynptr */ 914 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 915 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 916 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 917 continue; 918 if (dreg->dynptr_id == dynptr_id) 919 mark_reg_invalid(env, dreg); 920 })); 921 922 /* Do not release reference state, we are destroying dynptr on stack, 923 * not using some helper to release it. Just reset register. 924 */ 925 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 926 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 927 928 /* Same reason as unmark_stack_slots_dynptr above */ 929 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 930 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 931 932 return 0; 933 } 934 935 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 936 { 937 int spi; 938 939 if (reg->type == CONST_PTR_TO_DYNPTR) 940 return false; 941 942 spi = dynptr_get_spi(env, reg); 943 944 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 945 * error because this just means the stack state hasn't been updated yet. 946 * We will do check_mem_access to check and update stack bounds later. 947 */ 948 if (spi < 0 && spi != -ERANGE) 949 return false; 950 951 /* We don't need to check if the stack slots are marked by previous 952 * dynptr initializations because we allow overwriting existing unreferenced 953 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 954 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 955 * touching are completely destructed before we reinitialize them for a new 956 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 957 * instead of delaying it until the end where the user will get "Unreleased 958 * reference" error. 959 */ 960 return true; 961 } 962 963 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 964 { 965 struct bpf_func_state *state = func(env, reg); 966 int i, spi; 967 968 /* This already represents first slot of initialized bpf_dynptr. 969 * 970 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 971 * check_func_arg_reg_off's logic, so we don't need to check its 972 * offset and alignment. 973 */ 974 if (reg->type == CONST_PTR_TO_DYNPTR) 975 return true; 976 977 spi = dynptr_get_spi(env, reg); 978 if (spi < 0) 979 return false; 980 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 981 return false; 982 983 for (i = 0; i < BPF_REG_SIZE; i++) { 984 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 985 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 986 return false; 987 } 988 989 return true; 990 } 991 992 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 993 enum bpf_arg_type arg_type) 994 { 995 struct bpf_func_state *state = func(env, reg); 996 enum bpf_dynptr_type dynptr_type; 997 int spi; 998 999 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1000 if (arg_type == ARG_PTR_TO_DYNPTR) 1001 return true; 1002 1003 dynptr_type = arg_to_dynptr_type(arg_type); 1004 if (reg->type == CONST_PTR_TO_DYNPTR) { 1005 return reg->dynptr.type == dynptr_type; 1006 } else { 1007 spi = dynptr_get_spi(env, reg); 1008 if (spi < 0) 1009 return false; 1010 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1011 } 1012 } 1013 1014 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1015 1016 static bool in_rcu_cs(struct bpf_verifier_env *env); 1017 1018 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 1019 1020 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1021 struct bpf_kfunc_call_arg_meta *meta, 1022 struct bpf_reg_state *reg, int insn_idx, 1023 struct btf *btf, u32 btf_id, int nr_slots) 1024 { 1025 struct bpf_func_state *state = func(env, reg); 1026 int spi, i, j, id; 1027 1028 spi = iter_get_spi(env, reg, nr_slots); 1029 if (spi < 0) 1030 return spi; 1031 1032 id = acquire_reference(env, insn_idx); 1033 if (id < 0) 1034 return id; 1035 1036 for (i = 0; i < nr_slots; i++) { 1037 struct bpf_stack_state *slot = &state->stack[spi - i]; 1038 struct bpf_reg_state *st = &slot->spilled_ptr; 1039 1040 __mark_reg_known_zero(st); 1041 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1042 if (is_kfunc_rcu_protected(meta)) { 1043 if (in_rcu_cs(env)) 1044 st->type |= MEM_RCU; 1045 else 1046 st->type |= PTR_UNTRUSTED; 1047 } 1048 st->live |= REG_LIVE_WRITTEN; 1049 st->ref_obj_id = i == 0 ? id : 0; 1050 st->iter.btf = btf; 1051 st->iter.btf_id = btf_id; 1052 st->iter.state = BPF_ITER_STATE_ACTIVE; 1053 st->iter.depth = 0; 1054 1055 for (j = 0; j < BPF_REG_SIZE; j++) 1056 slot->slot_type[j] = STACK_ITER; 1057 1058 mark_stack_slot_scratched(env, spi - i); 1059 } 1060 1061 return 0; 1062 } 1063 1064 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1065 struct bpf_reg_state *reg, int nr_slots) 1066 { 1067 struct bpf_func_state *state = func(env, reg); 1068 int spi, i, j; 1069 1070 spi = iter_get_spi(env, reg, nr_slots); 1071 if (spi < 0) 1072 return spi; 1073 1074 for (i = 0; i < nr_slots; i++) { 1075 struct bpf_stack_state *slot = &state->stack[spi - i]; 1076 struct bpf_reg_state *st = &slot->spilled_ptr; 1077 1078 if (i == 0) 1079 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1080 1081 __mark_reg_not_init(env, st); 1082 1083 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1084 st->live |= REG_LIVE_WRITTEN; 1085 1086 for (j = 0; j < BPF_REG_SIZE; j++) 1087 slot->slot_type[j] = STACK_INVALID; 1088 1089 mark_stack_slot_scratched(env, spi - i); 1090 } 1091 1092 return 0; 1093 } 1094 1095 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1096 struct bpf_reg_state *reg, int nr_slots) 1097 { 1098 struct bpf_func_state *state = func(env, reg); 1099 int spi, i, j; 1100 1101 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1102 * will do check_mem_access to check and update stack bounds later, so 1103 * return true for that case. 1104 */ 1105 spi = iter_get_spi(env, reg, nr_slots); 1106 if (spi == -ERANGE) 1107 return true; 1108 if (spi < 0) 1109 return false; 1110 1111 for (i = 0; i < nr_slots; i++) { 1112 struct bpf_stack_state *slot = &state->stack[spi - i]; 1113 1114 for (j = 0; j < BPF_REG_SIZE; j++) 1115 if (slot->slot_type[j] == STACK_ITER) 1116 return false; 1117 } 1118 1119 return true; 1120 } 1121 1122 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1123 struct btf *btf, u32 btf_id, int nr_slots) 1124 { 1125 struct bpf_func_state *state = func(env, reg); 1126 int spi, i, j; 1127 1128 spi = iter_get_spi(env, reg, nr_slots); 1129 if (spi < 0) 1130 return -EINVAL; 1131 1132 for (i = 0; i < nr_slots; i++) { 1133 struct bpf_stack_state *slot = &state->stack[spi - i]; 1134 struct bpf_reg_state *st = &slot->spilled_ptr; 1135 1136 if (st->type & PTR_UNTRUSTED) 1137 return -EPROTO; 1138 /* only main (first) slot has ref_obj_id set */ 1139 if (i == 0 && !st->ref_obj_id) 1140 return -EINVAL; 1141 if (i != 0 && st->ref_obj_id) 1142 return -EINVAL; 1143 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1144 return -EINVAL; 1145 1146 for (j = 0; j < BPF_REG_SIZE; j++) 1147 if (slot->slot_type[j] != STACK_ITER) 1148 return -EINVAL; 1149 } 1150 1151 return 0; 1152 } 1153 1154 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx); 1155 static int release_irq_state(struct bpf_verifier_state *state, int id); 1156 1157 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env, 1158 struct bpf_kfunc_call_arg_meta *meta, 1159 struct bpf_reg_state *reg, int insn_idx, 1160 int kfunc_class) 1161 { 1162 struct bpf_func_state *state = func(env, reg); 1163 struct bpf_stack_state *slot; 1164 struct bpf_reg_state *st; 1165 int spi, i, id; 1166 1167 spi = irq_flag_get_spi(env, reg); 1168 if (spi < 0) 1169 return spi; 1170 1171 id = acquire_irq_state(env, insn_idx); 1172 if (id < 0) 1173 return id; 1174 1175 slot = &state->stack[spi]; 1176 st = &slot->spilled_ptr; 1177 1178 __mark_reg_known_zero(st); 1179 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1180 st->live |= REG_LIVE_WRITTEN; 1181 st->ref_obj_id = id; 1182 st->irq.kfunc_class = kfunc_class; 1183 1184 for (i = 0; i < BPF_REG_SIZE; i++) 1185 slot->slot_type[i] = STACK_IRQ_FLAG; 1186 1187 mark_stack_slot_scratched(env, spi); 1188 return 0; 1189 } 1190 1191 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1192 int kfunc_class) 1193 { 1194 struct bpf_func_state *state = func(env, reg); 1195 struct bpf_stack_state *slot; 1196 struct bpf_reg_state *st; 1197 int spi, i, err; 1198 1199 spi = irq_flag_get_spi(env, reg); 1200 if (spi < 0) 1201 return spi; 1202 1203 slot = &state->stack[spi]; 1204 st = &slot->spilled_ptr; 1205 1206 if (st->irq.kfunc_class != kfunc_class) { 1207 const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1208 const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1209 1210 verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n", 1211 flag_kfunc, used_kfunc); 1212 return -EINVAL; 1213 } 1214 1215 err = release_irq_state(env->cur_state, st->ref_obj_id); 1216 WARN_ON_ONCE(err && err != -EACCES); 1217 if (err) { 1218 int insn_idx = 0; 1219 1220 for (int i = 0; i < env->cur_state->acquired_refs; i++) { 1221 if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) { 1222 insn_idx = env->cur_state->refs[i].insn_idx; 1223 break; 1224 } 1225 } 1226 1227 verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n", 1228 env->cur_state->active_irq_id, insn_idx); 1229 return err; 1230 } 1231 1232 __mark_reg_not_init(env, st); 1233 1234 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1235 st->live |= REG_LIVE_WRITTEN; 1236 1237 for (i = 0; i < BPF_REG_SIZE; i++) 1238 slot->slot_type[i] = STACK_INVALID; 1239 1240 mark_stack_slot_scratched(env, spi); 1241 return 0; 1242 } 1243 1244 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1245 { 1246 struct bpf_func_state *state = func(env, reg); 1247 struct bpf_stack_state *slot; 1248 int spi, i; 1249 1250 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1251 * will do check_mem_access to check and update stack bounds later, so 1252 * return true for that case. 1253 */ 1254 spi = irq_flag_get_spi(env, reg); 1255 if (spi == -ERANGE) 1256 return true; 1257 if (spi < 0) 1258 return false; 1259 1260 slot = &state->stack[spi]; 1261 1262 for (i = 0; i < BPF_REG_SIZE; i++) 1263 if (slot->slot_type[i] == STACK_IRQ_FLAG) 1264 return false; 1265 return true; 1266 } 1267 1268 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1269 { 1270 struct bpf_func_state *state = func(env, reg); 1271 struct bpf_stack_state *slot; 1272 struct bpf_reg_state *st; 1273 int spi, i; 1274 1275 spi = irq_flag_get_spi(env, reg); 1276 if (spi < 0) 1277 return -EINVAL; 1278 1279 slot = &state->stack[spi]; 1280 st = &slot->spilled_ptr; 1281 1282 if (!st->ref_obj_id) 1283 return -EINVAL; 1284 1285 for (i = 0; i < BPF_REG_SIZE; i++) 1286 if (slot->slot_type[i] != STACK_IRQ_FLAG) 1287 return -EINVAL; 1288 return 0; 1289 } 1290 1291 /* Check if given stack slot is "special": 1292 * - spilled register state (STACK_SPILL); 1293 * - dynptr state (STACK_DYNPTR); 1294 * - iter state (STACK_ITER). 1295 * - irq flag state (STACK_IRQ_FLAG) 1296 */ 1297 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1298 { 1299 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1300 1301 switch (type) { 1302 case STACK_SPILL: 1303 case STACK_DYNPTR: 1304 case STACK_ITER: 1305 case STACK_IRQ_FLAG: 1306 return true; 1307 case STACK_INVALID: 1308 case STACK_MISC: 1309 case STACK_ZERO: 1310 return false; 1311 default: 1312 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1313 return true; 1314 } 1315 } 1316 1317 /* The reg state of a pointer or a bounded scalar was saved when 1318 * it was spilled to the stack. 1319 */ 1320 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1321 { 1322 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1323 } 1324 1325 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1326 { 1327 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1328 stack->spilled_ptr.type == SCALAR_VALUE; 1329 } 1330 1331 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack) 1332 { 1333 return stack->slot_type[0] == STACK_SPILL && 1334 stack->spilled_ptr.type == SCALAR_VALUE; 1335 } 1336 1337 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1338 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1339 * more precise STACK_ZERO. 1340 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged 1341 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is 1342 * unnecessary as both are considered equivalent when loading data and pruning, 1343 * in case of unprivileged mode it will be incorrect to allow reads of invalid 1344 * slots. 1345 */ 1346 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1347 { 1348 if (*stype == STACK_ZERO) 1349 return; 1350 if (*stype == STACK_INVALID) 1351 return; 1352 *stype = STACK_MISC; 1353 } 1354 1355 static void scrub_spilled_slot(u8 *stype) 1356 { 1357 if (*stype != STACK_INVALID) 1358 *stype = STACK_MISC; 1359 } 1360 1361 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1362 * small to hold src. This is different from krealloc since we don't want to preserve 1363 * the contents of dst. 1364 * 1365 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1366 * not be allocated. 1367 */ 1368 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1369 { 1370 size_t alloc_bytes; 1371 void *orig = dst; 1372 size_t bytes; 1373 1374 if (ZERO_OR_NULL_PTR(src)) 1375 goto out; 1376 1377 if (unlikely(check_mul_overflow(n, size, &bytes))) 1378 return NULL; 1379 1380 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1381 dst = krealloc(orig, alloc_bytes, flags); 1382 if (!dst) { 1383 kfree(orig); 1384 return NULL; 1385 } 1386 1387 memcpy(dst, src, bytes); 1388 out: 1389 return dst ? dst : ZERO_SIZE_PTR; 1390 } 1391 1392 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1393 * small to hold new_n items. new items are zeroed out if the array grows. 1394 * 1395 * Contrary to krealloc_array, does not free arr if new_n is zero. 1396 */ 1397 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1398 { 1399 size_t alloc_size; 1400 void *new_arr; 1401 1402 if (!new_n || old_n == new_n) 1403 goto out; 1404 1405 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1406 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1407 if (!new_arr) { 1408 kfree(arr); 1409 return NULL; 1410 } 1411 arr = new_arr; 1412 1413 if (new_n > old_n) 1414 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1415 1416 out: 1417 return arr ? arr : ZERO_SIZE_PTR; 1418 } 1419 1420 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) 1421 { 1422 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1423 sizeof(struct bpf_reference_state), GFP_KERNEL); 1424 if (!dst->refs) 1425 return -ENOMEM; 1426 1427 dst->acquired_refs = src->acquired_refs; 1428 dst->active_locks = src->active_locks; 1429 dst->active_preempt_locks = src->active_preempt_locks; 1430 dst->active_rcu_lock = src->active_rcu_lock; 1431 dst->active_irq_id = src->active_irq_id; 1432 dst->active_lock_id = src->active_lock_id; 1433 dst->active_lock_ptr = src->active_lock_ptr; 1434 return 0; 1435 } 1436 1437 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1438 { 1439 size_t n = src->allocated_stack / BPF_REG_SIZE; 1440 1441 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1442 GFP_KERNEL); 1443 if (!dst->stack) 1444 return -ENOMEM; 1445 1446 dst->allocated_stack = src->allocated_stack; 1447 return 0; 1448 } 1449 1450 static int resize_reference_state(struct bpf_verifier_state *state, size_t n) 1451 { 1452 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1453 sizeof(struct bpf_reference_state)); 1454 if (!state->refs) 1455 return -ENOMEM; 1456 1457 state->acquired_refs = n; 1458 return 0; 1459 } 1460 1461 /* Possibly update state->allocated_stack to be at least size bytes. Also 1462 * possibly update the function's high-water mark in its bpf_subprog_info. 1463 */ 1464 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1465 { 1466 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1467 1468 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1469 size = round_up(size, BPF_REG_SIZE); 1470 n = size / BPF_REG_SIZE; 1471 1472 if (old_n >= n) 1473 return 0; 1474 1475 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1476 if (!state->stack) 1477 return -ENOMEM; 1478 1479 state->allocated_stack = size; 1480 1481 /* update known max for given subprogram */ 1482 if (env->subprog_info[state->subprogno].stack_depth < size) 1483 env->subprog_info[state->subprogno].stack_depth = size; 1484 1485 return 0; 1486 } 1487 1488 /* Acquire a pointer id from the env and update the state->refs to include 1489 * this new pointer reference. 1490 * On success, returns a valid pointer id to associate with the register 1491 * On failure, returns a negative errno. 1492 */ 1493 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1494 { 1495 struct bpf_verifier_state *state = env->cur_state; 1496 int new_ofs = state->acquired_refs; 1497 int err; 1498 1499 err = resize_reference_state(state, state->acquired_refs + 1); 1500 if (err) 1501 return NULL; 1502 state->refs[new_ofs].insn_idx = insn_idx; 1503 1504 return &state->refs[new_ofs]; 1505 } 1506 1507 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx) 1508 { 1509 struct bpf_reference_state *s; 1510 1511 s = acquire_reference_state(env, insn_idx); 1512 if (!s) 1513 return -ENOMEM; 1514 s->type = REF_TYPE_PTR; 1515 s->id = ++env->id_gen; 1516 return s->id; 1517 } 1518 1519 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type, 1520 int id, void *ptr) 1521 { 1522 struct bpf_verifier_state *state = env->cur_state; 1523 struct bpf_reference_state *s; 1524 1525 s = acquire_reference_state(env, insn_idx); 1526 if (!s) 1527 return -ENOMEM; 1528 s->type = type; 1529 s->id = id; 1530 s->ptr = ptr; 1531 1532 state->active_locks++; 1533 state->active_lock_id = id; 1534 state->active_lock_ptr = ptr; 1535 return 0; 1536 } 1537 1538 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx) 1539 { 1540 struct bpf_verifier_state *state = env->cur_state; 1541 struct bpf_reference_state *s; 1542 1543 s = acquire_reference_state(env, insn_idx); 1544 if (!s) 1545 return -ENOMEM; 1546 s->type = REF_TYPE_IRQ; 1547 s->id = ++env->id_gen; 1548 1549 state->active_irq_id = s->id; 1550 return s->id; 1551 } 1552 1553 static void release_reference_state(struct bpf_verifier_state *state, int idx) 1554 { 1555 int last_idx; 1556 size_t rem; 1557 1558 /* IRQ state requires the relative ordering of elements remaining the 1559 * same, since it relies on the refs array to behave as a stack, so that 1560 * it can detect out-of-order IRQ restore. Hence use memmove to shift 1561 * the array instead of swapping the final element into the deleted idx. 1562 */ 1563 last_idx = state->acquired_refs - 1; 1564 rem = state->acquired_refs - idx - 1; 1565 if (last_idx && idx != last_idx) 1566 memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem); 1567 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1568 state->acquired_refs--; 1569 return; 1570 } 1571 1572 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id) 1573 { 1574 int i; 1575 1576 for (i = 0; i < state->acquired_refs; i++) 1577 if (state->refs[i].id == ptr_id) 1578 return true; 1579 1580 return false; 1581 } 1582 1583 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr) 1584 { 1585 void *prev_ptr = NULL; 1586 u32 prev_id = 0; 1587 int i; 1588 1589 for (i = 0; i < state->acquired_refs; i++) { 1590 if (state->refs[i].type == type && state->refs[i].id == id && 1591 state->refs[i].ptr == ptr) { 1592 release_reference_state(state, i); 1593 state->active_locks--; 1594 /* Reassign active lock (id, ptr). */ 1595 state->active_lock_id = prev_id; 1596 state->active_lock_ptr = prev_ptr; 1597 return 0; 1598 } 1599 if (state->refs[i].type & REF_TYPE_LOCK_MASK) { 1600 prev_id = state->refs[i].id; 1601 prev_ptr = state->refs[i].ptr; 1602 } 1603 } 1604 return -EINVAL; 1605 } 1606 1607 static int release_irq_state(struct bpf_verifier_state *state, int id) 1608 { 1609 u32 prev_id = 0; 1610 int i; 1611 1612 if (id != state->active_irq_id) 1613 return -EACCES; 1614 1615 for (i = 0; i < state->acquired_refs; i++) { 1616 if (state->refs[i].type != REF_TYPE_IRQ) 1617 continue; 1618 if (state->refs[i].id == id) { 1619 release_reference_state(state, i); 1620 state->active_irq_id = prev_id; 1621 return 0; 1622 } else { 1623 prev_id = state->refs[i].id; 1624 } 1625 } 1626 return -EINVAL; 1627 } 1628 1629 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type, 1630 int id, void *ptr) 1631 { 1632 int i; 1633 1634 for (i = 0; i < state->acquired_refs; i++) { 1635 struct bpf_reference_state *s = &state->refs[i]; 1636 1637 if (!(s->type & type)) 1638 continue; 1639 1640 if (s->id == id && s->ptr == ptr) 1641 return s; 1642 } 1643 return NULL; 1644 } 1645 1646 static void update_peak_states(struct bpf_verifier_env *env) 1647 { 1648 u32 cur_states; 1649 1650 cur_states = env->explored_states_size + env->free_list_size; 1651 env->peak_states = max(env->peak_states, cur_states); 1652 } 1653 1654 static void free_func_state(struct bpf_func_state *state) 1655 { 1656 if (!state) 1657 return; 1658 kfree(state->stack); 1659 kfree(state); 1660 } 1661 1662 static void free_verifier_state(struct bpf_verifier_state *state, 1663 bool free_self) 1664 { 1665 int i; 1666 1667 for (i = 0; i <= state->curframe; i++) { 1668 free_func_state(state->frame[i]); 1669 state->frame[i] = NULL; 1670 } 1671 kfree(state->refs); 1672 if (free_self) 1673 kfree(state); 1674 } 1675 1676 /* struct bpf_verifier_state->{parent,loop_entry} refer to states 1677 * that are in either of env->{expored_states,free_list}. 1678 * In both cases the state is contained in struct bpf_verifier_state_list. 1679 */ 1680 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st) 1681 { 1682 if (st->parent) 1683 return container_of(st->parent, struct bpf_verifier_state_list, state); 1684 return NULL; 1685 } 1686 1687 static struct bpf_verifier_state_list *state_loop_entry_as_list(struct bpf_verifier_state *st) 1688 { 1689 if (st->loop_entry) 1690 return container_of(st->loop_entry, struct bpf_verifier_state_list, state); 1691 return NULL; 1692 } 1693 1694 /* A state can be freed if it is no longer referenced: 1695 * - is in the env->free_list; 1696 * - has no children states; 1697 * - is not used as loop_entry. 1698 * 1699 * Freeing a state can make it's loop_entry free-able. 1700 */ 1701 static void maybe_free_verifier_state(struct bpf_verifier_env *env, 1702 struct bpf_verifier_state_list *sl) 1703 { 1704 struct bpf_verifier_state_list *loop_entry_sl; 1705 1706 while (sl && sl->in_free_list && 1707 sl->state.branches == 0 && 1708 sl->state.used_as_loop_entry == 0) { 1709 loop_entry_sl = state_loop_entry_as_list(&sl->state); 1710 if (loop_entry_sl) 1711 loop_entry_sl->state.used_as_loop_entry--; 1712 list_del(&sl->node); 1713 free_verifier_state(&sl->state, false); 1714 kfree(sl); 1715 env->free_list_size--; 1716 sl = loop_entry_sl; 1717 } 1718 } 1719 1720 /* copy verifier state from src to dst growing dst stack space 1721 * when necessary to accommodate larger src stack 1722 */ 1723 static int copy_func_state(struct bpf_func_state *dst, 1724 const struct bpf_func_state *src) 1725 { 1726 memcpy(dst, src, offsetof(struct bpf_func_state, stack)); 1727 return copy_stack_state(dst, src); 1728 } 1729 1730 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1731 const struct bpf_verifier_state *src) 1732 { 1733 struct bpf_func_state *dst; 1734 int i, err; 1735 1736 /* if dst has more stack frames then src frame, free them, this is also 1737 * necessary in case of exceptional exits using bpf_throw. 1738 */ 1739 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1740 free_func_state(dst_state->frame[i]); 1741 dst_state->frame[i] = NULL; 1742 } 1743 err = copy_reference_state(dst_state, src); 1744 if (err) 1745 return err; 1746 dst_state->speculative = src->speculative; 1747 dst_state->in_sleepable = src->in_sleepable; 1748 dst_state->curframe = src->curframe; 1749 dst_state->branches = src->branches; 1750 dst_state->parent = src->parent; 1751 dst_state->first_insn_idx = src->first_insn_idx; 1752 dst_state->last_insn_idx = src->last_insn_idx; 1753 dst_state->insn_hist_start = src->insn_hist_start; 1754 dst_state->insn_hist_end = src->insn_hist_end; 1755 dst_state->dfs_depth = src->dfs_depth; 1756 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1757 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1758 dst_state->may_goto_depth = src->may_goto_depth; 1759 dst_state->loop_entry = src->loop_entry; 1760 for (i = 0; i <= src->curframe; i++) { 1761 dst = dst_state->frame[i]; 1762 if (!dst) { 1763 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1764 if (!dst) 1765 return -ENOMEM; 1766 dst_state->frame[i] = dst; 1767 } 1768 err = copy_func_state(dst, src->frame[i]); 1769 if (err) 1770 return err; 1771 } 1772 return 0; 1773 } 1774 1775 static u32 state_htab_size(struct bpf_verifier_env *env) 1776 { 1777 return env->prog->len; 1778 } 1779 1780 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx) 1781 { 1782 struct bpf_verifier_state *cur = env->cur_state; 1783 struct bpf_func_state *state = cur->frame[cur->curframe]; 1784 1785 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1786 } 1787 1788 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1789 { 1790 int fr; 1791 1792 if (a->curframe != b->curframe) 1793 return false; 1794 1795 for (fr = a->curframe; fr >= 0; fr--) 1796 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1797 return false; 1798 1799 return true; 1800 } 1801 1802 /* Open coded iterators allow back-edges in the state graph in order to 1803 * check unbounded loops that iterators. 1804 * 1805 * In is_state_visited() it is necessary to know if explored states are 1806 * part of some loops in order to decide whether non-exact states 1807 * comparison could be used: 1808 * - non-exact states comparison establishes sub-state relation and uses 1809 * read and precision marks to do so, these marks are propagated from 1810 * children states and thus are not guaranteed to be final in a loop; 1811 * - exact states comparison just checks if current and explored states 1812 * are identical (and thus form a back-edge). 1813 * 1814 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1815 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1816 * algorithm for loop structure detection and gives an overview of 1817 * relevant terminology. It also has helpful illustrations. 1818 * 1819 * [1] https://api.semanticscholar.org/CorpusID:15784067 1820 * 1821 * We use a similar algorithm but because loop nested structure is 1822 * irrelevant for verifier ours is significantly simpler and resembles 1823 * strongly connected components algorithm from Sedgewick's textbook. 1824 * 1825 * Define topmost loop entry as a first node of the loop traversed in a 1826 * depth first search starting from initial state. The goal of the loop 1827 * tracking algorithm is to associate topmost loop entries with states 1828 * derived from these entries. 1829 * 1830 * For each step in the DFS states traversal algorithm needs to identify 1831 * the following situations: 1832 * 1833 * initial initial initial 1834 * | | | 1835 * V V V 1836 * ... ... .---------> hdr 1837 * | | | | 1838 * V V | V 1839 * cur .-> succ | .------... 1840 * | | | | | | 1841 * V | V | V V 1842 * succ '-- cur | ... ... 1843 * | | | 1844 * | V V 1845 * | succ <- cur 1846 * | | 1847 * | V 1848 * | ... 1849 * | | 1850 * '----' 1851 * 1852 * (A) successor state of cur (B) successor state of cur or it's entry 1853 * not yet traversed are in current DFS path, thus cur and succ 1854 * are members of the same outermost loop 1855 * 1856 * initial initial 1857 * | | 1858 * V V 1859 * ... ... 1860 * | | 1861 * V V 1862 * .------... .------... 1863 * | | | | 1864 * V V V V 1865 * .-> hdr ... ... ... 1866 * | | | | | 1867 * | V V V V 1868 * | succ <- cur succ <- cur 1869 * | | | 1870 * | V V 1871 * | ... ... 1872 * | | | 1873 * '----' exit 1874 * 1875 * (C) successor state of cur is a part of some loop but this loop 1876 * does not include cur or successor state is not in a loop at all. 1877 * 1878 * Algorithm could be described as the following python code: 1879 * 1880 * traversed = set() # Set of traversed nodes 1881 * entries = {} # Mapping from node to loop entry 1882 * depths = {} # Depth level assigned to graph node 1883 * path = set() # Current DFS path 1884 * 1885 * # Find outermost loop entry known for n 1886 * def get_loop_entry(n): 1887 * h = entries.get(n, None) 1888 * while h in entries: 1889 * h = entries[h] 1890 * return h 1891 * 1892 * # Update n's loop entry if h comes before n in current DFS path. 1893 * def update_loop_entry(n, h): 1894 * if h in path and depths[entries.get(n, n)] < depths[n]: 1895 * entries[n] = h1 1896 * 1897 * def dfs(n, depth): 1898 * traversed.add(n) 1899 * path.add(n) 1900 * depths[n] = depth 1901 * for succ in G.successors(n): 1902 * if succ not in traversed: 1903 * # Case A: explore succ and update cur's loop entry 1904 * # only if succ's entry is in current DFS path. 1905 * dfs(succ, depth + 1) 1906 * h = entries.get(succ, None) 1907 * update_loop_entry(n, h) 1908 * else: 1909 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1910 * update_loop_entry(n, succ) 1911 * path.remove(n) 1912 * 1913 * To adapt this algorithm for use with verifier: 1914 * - use st->branch == 0 as a signal that DFS of succ had been finished 1915 * and cur's loop entry has to be updated (case A), handle this in 1916 * update_branch_counts(); 1917 * - use st->branch > 0 as a signal that st is in the current DFS path; 1918 * - handle cases B and C in is_state_visited(). 1919 */ 1920 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_env *env, 1921 struct bpf_verifier_state *st) 1922 { 1923 struct bpf_verifier_state *topmost = st->loop_entry; 1924 u32 steps = 0; 1925 1926 while (topmost && topmost->loop_entry) { 1927 if (verifier_bug_if(steps++ > st->dfs_depth, env, "infinite loop")) 1928 return ERR_PTR(-EFAULT); 1929 topmost = topmost->loop_entry; 1930 } 1931 return topmost; 1932 } 1933 1934 static void update_loop_entry(struct bpf_verifier_env *env, 1935 struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1936 { 1937 /* The hdr->branches check decides between cases B and C in 1938 * comment for get_loop_entry(). If hdr->branches == 0 then 1939 * head's topmost loop entry is not in current DFS path, 1940 * hence 'cur' and 'hdr' are not in the same loop and there is 1941 * no need to update cur->loop_entry. 1942 */ 1943 if (hdr->branches && hdr->dfs_depth < (cur->loop_entry ?: cur)->dfs_depth) { 1944 if (cur->loop_entry) { 1945 cur->loop_entry->used_as_loop_entry--; 1946 maybe_free_verifier_state(env, state_loop_entry_as_list(cur)); 1947 } 1948 cur->loop_entry = hdr; 1949 hdr->used_as_loop_entry++; 1950 } 1951 } 1952 1953 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1954 { 1955 struct bpf_verifier_state_list *sl = NULL, *parent_sl; 1956 struct bpf_verifier_state *parent; 1957 1958 while (st) { 1959 u32 br = --st->branches; 1960 1961 /* br == 0 signals that DFS exploration for 'st' is finished, 1962 * thus it is necessary to update parent's loop entry if it 1963 * turned out that st is a part of some loop. 1964 * This is a part of 'case A' in get_loop_entry() comment. 1965 */ 1966 if (br == 0 && st->parent && st->loop_entry) 1967 update_loop_entry(env, st->parent, st->loop_entry); 1968 1969 /* WARN_ON(br > 1) technically makes sense here, 1970 * but see comment in push_stack(), hence: 1971 */ 1972 WARN_ONCE((int)br < 0, 1973 "BUG update_branch_counts:branches_to_explore=%d\n", 1974 br); 1975 if (br) 1976 break; 1977 parent = st->parent; 1978 parent_sl = state_parent_as_list(st); 1979 if (sl) 1980 maybe_free_verifier_state(env, sl); 1981 st = parent; 1982 sl = parent_sl; 1983 } 1984 } 1985 1986 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1987 int *insn_idx, bool pop_log) 1988 { 1989 struct bpf_verifier_state *cur = env->cur_state; 1990 struct bpf_verifier_stack_elem *elem, *head = env->head; 1991 int err; 1992 1993 if (env->head == NULL) 1994 return -ENOENT; 1995 1996 if (cur) { 1997 err = copy_verifier_state(cur, &head->st); 1998 if (err) 1999 return err; 2000 } 2001 if (pop_log) 2002 bpf_vlog_reset(&env->log, head->log_pos); 2003 if (insn_idx) 2004 *insn_idx = head->insn_idx; 2005 if (prev_insn_idx) 2006 *prev_insn_idx = head->prev_insn_idx; 2007 elem = head->next; 2008 free_verifier_state(&head->st, false); 2009 kfree(head); 2010 env->head = elem; 2011 env->stack_size--; 2012 return 0; 2013 } 2014 2015 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 2016 int insn_idx, int prev_insn_idx, 2017 bool speculative) 2018 { 2019 struct bpf_verifier_state *cur = env->cur_state; 2020 struct bpf_verifier_stack_elem *elem; 2021 int err; 2022 2023 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2024 if (!elem) 2025 goto err; 2026 2027 elem->insn_idx = insn_idx; 2028 elem->prev_insn_idx = prev_insn_idx; 2029 elem->next = env->head; 2030 elem->log_pos = env->log.end_pos; 2031 env->head = elem; 2032 env->stack_size++; 2033 err = copy_verifier_state(&elem->st, cur); 2034 if (err) 2035 goto err; 2036 elem->st.speculative |= speculative; 2037 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2038 verbose(env, "The sequence of %d jumps is too complex.\n", 2039 env->stack_size); 2040 goto err; 2041 } 2042 if (elem->st.parent) { 2043 ++elem->st.parent->branches; 2044 /* WARN_ON(branches > 2) technically makes sense here, 2045 * but 2046 * 1. speculative states will bump 'branches' for non-branch 2047 * instructions 2048 * 2. is_state_visited() heuristics may decide not to create 2049 * a new state for a sequence of branches and all such current 2050 * and cloned states will be pointing to a single parent state 2051 * which might have large 'branches' count. 2052 */ 2053 } 2054 return &elem->st; 2055 err: 2056 free_verifier_state(env->cur_state, true); 2057 env->cur_state = NULL; 2058 /* pop all elements and return */ 2059 while (!pop_stack(env, NULL, NULL, false)); 2060 return NULL; 2061 } 2062 2063 #define CALLER_SAVED_REGS 6 2064 static const int caller_saved[CALLER_SAVED_REGS] = { 2065 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 2066 }; 2067 2068 /* This helper doesn't clear reg->id */ 2069 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2070 { 2071 reg->var_off = tnum_const(imm); 2072 reg->smin_value = (s64)imm; 2073 reg->smax_value = (s64)imm; 2074 reg->umin_value = imm; 2075 reg->umax_value = imm; 2076 2077 reg->s32_min_value = (s32)imm; 2078 reg->s32_max_value = (s32)imm; 2079 reg->u32_min_value = (u32)imm; 2080 reg->u32_max_value = (u32)imm; 2081 } 2082 2083 /* Mark the unknown part of a register (variable offset or scalar value) as 2084 * known to have the value @imm. 2085 */ 2086 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2087 { 2088 /* Clear off and union(map_ptr, range) */ 2089 memset(((u8 *)reg) + sizeof(reg->type), 0, 2090 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 2091 reg->id = 0; 2092 reg->ref_obj_id = 0; 2093 ___mark_reg_known(reg, imm); 2094 } 2095 2096 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 2097 { 2098 reg->var_off = tnum_const_subreg(reg->var_off, imm); 2099 reg->s32_min_value = (s32)imm; 2100 reg->s32_max_value = (s32)imm; 2101 reg->u32_min_value = (u32)imm; 2102 reg->u32_max_value = (u32)imm; 2103 } 2104 2105 /* Mark the 'variable offset' part of a register as zero. This should be 2106 * used only on registers holding a pointer type. 2107 */ 2108 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 2109 { 2110 __mark_reg_known(reg, 0); 2111 } 2112 2113 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 2114 { 2115 __mark_reg_known(reg, 0); 2116 reg->type = SCALAR_VALUE; 2117 /* all scalars are assumed imprecise initially (unless unprivileged, 2118 * in which case everything is forced to be precise) 2119 */ 2120 reg->precise = !env->bpf_capable; 2121 } 2122 2123 static void mark_reg_known_zero(struct bpf_verifier_env *env, 2124 struct bpf_reg_state *regs, u32 regno) 2125 { 2126 if (WARN_ON(regno >= MAX_BPF_REG)) { 2127 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 2128 /* Something bad happened, let's kill all regs */ 2129 for (regno = 0; regno < MAX_BPF_REG; regno++) 2130 __mark_reg_not_init(env, regs + regno); 2131 return; 2132 } 2133 __mark_reg_known_zero(regs + regno); 2134 } 2135 2136 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 2137 bool first_slot, int dynptr_id) 2138 { 2139 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 2140 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 2141 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 2142 */ 2143 __mark_reg_known_zero(reg); 2144 reg->type = CONST_PTR_TO_DYNPTR; 2145 /* Give each dynptr a unique id to uniquely associate slices to it. */ 2146 reg->id = dynptr_id; 2147 reg->dynptr.type = type; 2148 reg->dynptr.first_slot = first_slot; 2149 } 2150 2151 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 2152 { 2153 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 2154 const struct bpf_map *map = reg->map_ptr; 2155 2156 if (map->inner_map_meta) { 2157 reg->type = CONST_PTR_TO_MAP; 2158 reg->map_ptr = map->inner_map_meta; 2159 /* transfer reg's id which is unique for every map_lookup_elem 2160 * as UID of the inner map. 2161 */ 2162 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 2163 reg->map_uid = reg->id; 2164 if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE)) 2165 reg->map_uid = reg->id; 2166 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 2167 reg->type = PTR_TO_XDP_SOCK; 2168 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 2169 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 2170 reg->type = PTR_TO_SOCKET; 2171 } else { 2172 reg->type = PTR_TO_MAP_VALUE; 2173 } 2174 return; 2175 } 2176 2177 reg->type &= ~PTR_MAYBE_NULL; 2178 } 2179 2180 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 2181 struct btf_field_graph_root *ds_head) 2182 { 2183 __mark_reg_known_zero(®s[regno]); 2184 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 2185 regs[regno].btf = ds_head->btf; 2186 regs[regno].btf_id = ds_head->value_btf_id; 2187 regs[regno].off = ds_head->node_offset; 2188 } 2189 2190 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 2191 { 2192 return type_is_pkt_pointer(reg->type); 2193 } 2194 2195 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 2196 { 2197 return reg_is_pkt_pointer(reg) || 2198 reg->type == PTR_TO_PACKET_END; 2199 } 2200 2201 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 2202 { 2203 return base_type(reg->type) == PTR_TO_MEM && 2204 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 2205 } 2206 2207 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 2208 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 2209 enum bpf_reg_type which) 2210 { 2211 /* The register can already have a range from prior markings. 2212 * This is fine as long as it hasn't been advanced from its 2213 * origin. 2214 */ 2215 return reg->type == which && 2216 reg->id == 0 && 2217 reg->off == 0 && 2218 tnum_equals_const(reg->var_off, 0); 2219 } 2220 2221 /* Reset the min/max bounds of a register */ 2222 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2223 { 2224 reg->smin_value = S64_MIN; 2225 reg->smax_value = S64_MAX; 2226 reg->umin_value = 0; 2227 reg->umax_value = U64_MAX; 2228 2229 reg->s32_min_value = S32_MIN; 2230 reg->s32_max_value = S32_MAX; 2231 reg->u32_min_value = 0; 2232 reg->u32_max_value = U32_MAX; 2233 } 2234 2235 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2236 { 2237 reg->smin_value = S64_MIN; 2238 reg->smax_value = S64_MAX; 2239 reg->umin_value = 0; 2240 reg->umax_value = U64_MAX; 2241 } 2242 2243 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2244 { 2245 reg->s32_min_value = S32_MIN; 2246 reg->s32_max_value = S32_MAX; 2247 reg->u32_min_value = 0; 2248 reg->u32_max_value = U32_MAX; 2249 } 2250 2251 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2252 { 2253 struct tnum var32_off = tnum_subreg(reg->var_off); 2254 2255 /* min signed is max(sign bit) | min(other bits) */ 2256 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2257 var32_off.value | (var32_off.mask & S32_MIN)); 2258 /* max signed is min(sign bit) | max(other bits) */ 2259 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2260 var32_off.value | (var32_off.mask & S32_MAX)); 2261 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2262 reg->u32_max_value = min(reg->u32_max_value, 2263 (u32)(var32_off.value | var32_off.mask)); 2264 } 2265 2266 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2267 { 2268 /* min signed is max(sign bit) | min(other bits) */ 2269 reg->smin_value = max_t(s64, reg->smin_value, 2270 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2271 /* max signed is min(sign bit) | max(other bits) */ 2272 reg->smax_value = min_t(s64, reg->smax_value, 2273 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2274 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2275 reg->umax_value = min(reg->umax_value, 2276 reg->var_off.value | reg->var_off.mask); 2277 } 2278 2279 static void __update_reg_bounds(struct bpf_reg_state *reg) 2280 { 2281 __update_reg32_bounds(reg); 2282 __update_reg64_bounds(reg); 2283 } 2284 2285 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2286 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2287 { 2288 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 2289 * bits to improve our u32/s32 boundaries. 2290 * 2291 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 2292 * u64) is pretty trivial, it's obvious that in u32 we'll also have 2293 * [10, 20] range. But this property holds for any 64-bit range as 2294 * long as upper 32 bits in that entire range of values stay the same. 2295 * 2296 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 2297 * in decimal) has the same upper 32 bits throughout all the values in 2298 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 2299 * range. 2300 * 2301 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 2302 * following the rules outlined below about u64/s64 correspondence 2303 * (which equally applies to u32 vs s32 correspondence). In general it 2304 * depends on actual hexadecimal values of 32-bit range. They can form 2305 * only valid u32, or only valid s32 ranges in some cases. 2306 * 2307 * So we use all these insights to derive bounds for subregisters here. 2308 */ 2309 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 2310 /* u64 to u32 casting preserves validity of low 32 bits as 2311 * a range, if upper 32 bits are the same 2312 */ 2313 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 2314 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 2315 2316 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 2317 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2318 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2319 } 2320 } 2321 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 2322 /* low 32 bits should form a proper u32 range */ 2323 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 2324 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 2325 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 2326 } 2327 /* low 32 bits should form a proper s32 range */ 2328 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 2329 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2330 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2331 } 2332 } 2333 /* Special case where upper bits form a small sequence of two 2334 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 2335 * 0x00000000 is also valid), while lower bits form a proper s32 range 2336 * going from negative numbers to positive numbers. E.g., let's say we 2337 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 2338 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 2339 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 2340 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 2341 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 2342 * upper 32 bits. As a random example, s64 range 2343 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2344 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2345 */ 2346 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2347 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 2348 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2349 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2350 } 2351 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2352 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2353 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2354 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2355 } 2356 /* if u32 range forms a valid s32 range (due to matching sign bit), 2357 * try to learn from that 2358 */ 2359 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2360 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2361 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2362 } 2363 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2364 * are the same, so combine. This works even in the negative case, e.g. 2365 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2366 */ 2367 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2368 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2369 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2370 } 2371 } 2372 2373 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2374 { 2375 /* If u64 range forms a valid s64 range (due to matching sign bit), 2376 * try to learn from that. Let's do a bit of ASCII art to see when 2377 * this is happening. Let's take u64 range first: 2378 * 2379 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2380 * |-------------------------------|--------------------------------| 2381 * 2382 * Valid u64 range is formed when umin and umax are anywhere in the 2383 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2384 * straightforward. Let's see how s64 range maps onto the same range 2385 * of values, annotated below the line for comparison: 2386 * 2387 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2388 * |-------------------------------|--------------------------------| 2389 * 0 S64_MAX S64_MIN -1 2390 * 2391 * So s64 values basically start in the middle and they are logically 2392 * contiguous to the right of it, wrapping around from -1 to 0, and 2393 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2394 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2395 * more visually as mapped to sign-agnostic range of hex values. 2396 * 2397 * u64 start u64 end 2398 * _______________________________________________________________ 2399 * / \ 2400 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2401 * |-------------------------------|--------------------------------| 2402 * 0 S64_MAX S64_MIN -1 2403 * / \ 2404 * >------------------------------ -------------------------------> 2405 * s64 continues... s64 end s64 start s64 "midpoint" 2406 * 2407 * What this means is that, in general, we can't always derive 2408 * something new about u64 from any random s64 range, and vice versa. 2409 * 2410 * But we can do that in two particular cases. One is when entire 2411 * u64/s64 range is *entirely* contained within left half of the above 2412 * diagram or when it is *entirely* contained in the right half. I.e.: 2413 * 2414 * |-------------------------------|--------------------------------| 2415 * ^ ^ ^ ^ 2416 * A B C D 2417 * 2418 * [A, B] and [C, D] are contained entirely in their respective halves 2419 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2420 * will be non-negative both as u64 and s64 (and in fact it will be 2421 * identical ranges no matter the signedness). [C, D] treated as s64 2422 * will be a range of negative values, while in u64 it will be 2423 * non-negative range of values larger than 0x8000000000000000. 2424 * 2425 * Now, any other range here can't be represented in both u64 and s64 2426 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2427 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2428 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2429 * for example. Similarly, valid s64 range [D, A] (going from negative 2430 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2431 * ranges as u64. Currently reg_state can't represent two segments per 2432 * numeric domain, so in such situations we can only derive maximal 2433 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2434 * 2435 * So we use these facts to derive umin/umax from smin/smax and vice 2436 * versa only if they stay within the same "half". This is equivalent 2437 * to checking sign bit: lower half will have sign bit as zero, upper 2438 * half have sign bit 1. Below in code we simplify this by just 2439 * casting umin/umax as smin/smax and checking if they form valid 2440 * range, and vice versa. Those are equivalent checks. 2441 */ 2442 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2443 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2444 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2445 } 2446 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2447 * are the same, so combine. This works even in the negative case, e.g. 2448 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2449 */ 2450 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2451 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2452 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2453 } 2454 } 2455 2456 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2457 { 2458 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2459 * values on both sides of 64-bit range in hope to have tighter range. 2460 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2461 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2462 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2463 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2464 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2465 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2466 * We just need to make sure that derived bounds we are intersecting 2467 * with are well-formed ranges in respective s64 or u64 domain, just 2468 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2469 */ 2470 __u64 new_umin, new_umax; 2471 __s64 new_smin, new_smax; 2472 2473 /* u32 -> u64 tightening, it's always well-formed */ 2474 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2475 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2476 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2477 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2478 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2479 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2480 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2481 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2482 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2483 2484 /* if s32 can be treated as valid u32 range, we can use it as well */ 2485 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2486 /* s32 -> u64 tightening */ 2487 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2488 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2489 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2490 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2491 /* s32 -> s64 tightening */ 2492 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2493 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2494 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2495 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2496 } 2497 2498 /* Here we would like to handle a special case after sign extending load, 2499 * when upper bits for a 64-bit range are all 1s or all 0s. 2500 * 2501 * Upper bits are all 1s when register is in a range: 2502 * [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff] 2503 * Upper bits are all 0s when register is in a range: 2504 * [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff] 2505 * Together this forms are continuous range: 2506 * [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff] 2507 * 2508 * Now, suppose that register range is in fact tighter: 2509 * [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R) 2510 * Also suppose that it's 32-bit range is positive, 2511 * meaning that lower 32-bits of the full 64-bit register 2512 * are in the range: 2513 * [0x0000_0000, 0x7fff_ffff] (W) 2514 * 2515 * If this happens, then any value in a range: 2516 * [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff] 2517 * is smaller than a lowest bound of the range (R): 2518 * 0xffff_ffff_8000_0000 2519 * which means that upper bits of the full 64-bit register 2520 * can't be all 1s, when lower bits are in range (W). 2521 * 2522 * Note that: 2523 * - 0xffff_ffff_8000_0000 == (s64)S32_MIN 2524 * - 0x0000_0000_7fff_ffff == (s64)S32_MAX 2525 * These relations are used in the conditions below. 2526 */ 2527 if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) { 2528 reg->smin_value = reg->s32_min_value; 2529 reg->smax_value = reg->s32_max_value; 2530 reg->umin_value = reg->s32_min_value; 2531 reg->umax_value = reg->s32_max_value; 2532 reg->var_off = tnum_intersect(reg->var_off, 2533 tnum_range(reg->smin_value, reg->smax_value)); 2534 } 2535 } 2536 2537 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2538 { 2539 __reg32_deduce_bounds(reg); 2540 __reg64_deduce_bounds(reg); 2541 __reg_deduce_mixed_bounds(reg); 2542 } 2543 2544 /* Attempts to improve var_off based on unsigned min/max information */ 2545 static void __reg_bound_offset(struct bpf_reg_state *reg) 2546 { 2547 struct tnum var64_off = tnum_intersect(reg->var_off, 2548 tnum_range(reg->umin_value, 2549 reg->umax_value)); 2550 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2551 tnum_range(reg->u32_min_value, 2552 reg->u32_max_value)); 2553 2554 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2555 } 2556 2557 static void reg_bounds_sync(struct bpf_reg_state *reg) 2558 { 2559 /* We might have learned new bounds from the var_off. */ 2560 __update_reg_bounds(reg); 2561 /* We might have learned something about the sign bit. */ 2562 __reg_deduce_bounds(reg); 2563 __reg_deduce_bounds(reg); 2564 /* We might have learned some bits from the bounds. */ 2565 __reg_bound_offset(reg); 2566 /* Intersecting with the old var_off might have improved our bounds 2567 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2568 * then new var_off is (0; 0x7f...fc) which improves our umax. 2569 */ 2570 __update_reg_bounds(reg); 2571 } 2572 2573 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2574 struct bpf_reg_state *reg, const char *ctx) 2575 { 2576 const char *msg; 2577 2578 if (reg->umin_value > reg->umax_value || 2579 reg->smin_value > reg->smax_value || 2580 reg->u32_min_value > reg->u32_max_value || 2581 reg->s32_min_value > reg->s32_max_value) { 2582 msg = "range bounds violation"; 2583 goto out; 2584 } 2585 2586 if (tnum_is_const(reg->var_off)) { 2587 u64 uval = reg->var_off.value; 2588 s64 sval = (s64)uval; 2589 2590 if (reg->umin_value != uval || reg->umax_value != uval || 2591 reg->smin_value != sval || reg->smax_value != sval) { 2592 msg = "const tnum out of sync with range bounds"; 2593 goto out; 2594 } 2595 } 2596 2597 if (tnum_subreg_is_const(reg->var_off)) { 2598 u32 uval32 = tnum_subreg(reg->var_off).value; 2599 s32 sval32 = (s32)uval32; 2600 2601 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2602 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2603 msg = "const subreg tnum out of sync with range bounds"; 2604 goto out; 2605 } 2606 } 2607 2608 return 0; 2609 out: 2610 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2611 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n", 2612 ctx, msg, reg->umin_value, reg->umax_value, 2613 reg->smin_value, reg->smax_value, 2614 reg->u32_min_value, reg->u32_max_value, 2615 reg->s32_min_value, reg->s32_max_value, 2616 reg->var_off.value, reg->var_off.mask); 2617 if (env->test_reg_invariants) 2618 return -EFAULT; 2619 __mark_reg_unbounded(reg); 2620 return 0; 2621 } 2622 2623 static bool __reg32_bound_s64(s32 a) 2624 { 2625 return a >= 0 && a <= S32_MAX; 2626 } 2627 2628 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2629 { 2630 reg->umin_value = reg->u32_min_value; 2631 reg->umax_value = reg->u32_max_value; 2632 2633 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2634 * be positive otherwise set to worse case bounds and refine later 2635 * from tnum. 2636 */ 2637 if (__reg32_bound_s64(reg->s32_min_value) && 2638 __reg32_bound_s64(reg->s32_max_value)) { 2639 reg->smin_value = reg->s32_min_value; 2640 reg->smax_value = reg->s32_max_value; 2641 } else { 2642 reg->smin_value = 0; 2643 reg->smax_value = U32_MAX; 2644 } 2645 } 2646 2647 /* Mark a register as having a completely unknown (scalar) value. */ 2648 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2649 { 2650 /* 2651 * Clear type, off, and union(map_ptr, range) and 2652 * padding between 'type' and union 2653 */ 2654 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2655 reg->type = SCALAR_VALUE; 2656 reg->id = 0; 2657 reg->ref_obj_id = 0; 2658 reg->var_off = tnum_unknown; 2659 reg->frameno = 0; 2660 reg->precise = false; 2661 __mark_reg_unbounded(reg); 2662 } 2663 2664 /* Mark a register as having a completely unknown (scalar) value, 2665 * initialize .precise as true when not bpf capable. 2666 */ 2667 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2668 struct bpf_reg_state *reg) 2669 { 2670 __mark_reg_unknown_imprecise(reg); 2671 reg->precise = !env->bpf_capable; 2672 } 2673 2674 static void mark_reg_unknown(struct bpf_verifier_env *env, 2675 struct bpf_reg_state *regs, u32 regno) 2676 { 2677 if (WARN_ON(regno >= MAX_BPF_REG)) { 2678 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2679 /* Something bad happened, let's kill all regs except FP */ 2680 for (regno = 0; regno < BPF_REG_FP; regno++) 2681 __mark_reg_not_init(env, regs + regno); 2682 return; 2683 } 2684 __mark_reg_unknown(env, regs + regno); 2685 } 2686 2687 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2688 struct bpf_reg_state *regs, 2689 u32 regno, 2690 s32 s32_min, 2691 s32 s32_max) 2692 { 2693 struct bpf_reg_state *reg = regs + regno; 2694 2695 reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min); 2696 reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max); 2697 2698 reg->smin_value = max_t(s64, reg->smin_value, s32_min); 2699 reg->smax_value = min_t(s64, reg->smax_value, s32_max); 2700 2701 reg_bounds_sync(reg); 2702 2703 return reg_bounds_sanity_check(env, reg, "s32_range"); 2704 } 2705 2706 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2707 struct bpf_reg_state *reg) 2708 { 2709 __mark_reg_unknown(env, reg); 2710 reg->type = NOT_INIT; 2711 } 2712 2713 static void mark_reg_not_init(struct bpf_verifier_env *env, 2714 struct bpf_reg_state *regs, u32 regno) 2715 { 2716 if (WARN_ON(regno >= MAX_BPF_REG)) { 2717 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2718 /* Something bad happened, let's kill all regs except FP */ 2719 for (regno = 0; regno < BPF_REG_FP; regno++) 2720 __mark_reg_not_init(env, regs + regno); 2721 return; 2722 } 2723 __mark_reg_not_init(env, regs + regno); 2724 } 2725 2726 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2727 struct bpf_reg_state *regs, u32 regno, 2728 enum bpf_reg_type reg_type, 2729 struct btf *btf, u32 btf_id, 2730 enum bpf_type_flag flag) 2731 { 2732 if (reg_type == SCALAR_VALUE) { 2733 mark_reg_unknown(env, regs, regno); 2734 return; 2735 } 2736 mark_reg_known_zero(env, regs, regno); 2737 regs[regno].type = PTR_TO_BTF_ID | flag; 2738 regs[regno].btf = btf; 2739 regs[regno].btf_id = btf_id; 2740 if (type_may_be_null(flag)) 2741 regs[regno].id = ++env->id_gen; 2742 } 2743 2744 #define DEF_NOT_SUBREG (0) 2745 static void init_reg_state(struct bpf_verifier_env *env, 2746 struct bpf_func_state *state) 2747 { 2748 struct bpf_reg_state *regs = state->regs; 2749 int i; 2750 2751 for (i = 0; i < MAX_BPF_REG; i++) { 2752 mark_reg_not_init(env, regs, i); 2753 regs[i].live = REG_LIVE_NONE; 2754 regs[i].parent = NULL; 2755 regs[i].subreg_def = DEF_NOT_SUBREG; 2756 } 2757 2758 /* frame pointer */ 2759 regs[BPF_REG_FP].type = PTR_TO_STACK; 2760 mark_reg_known_zero(env, regs, BPF_REG_FP); 2761 regs[BPF_REG_FP].frameno = state->frameno; 2762 } 2763 2764 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2765 { 2766 return (struct bpf_retval_range){ minval, maxval }; 2767 } 2768 2769 #define BPF_MAIN_FUNC (-1) 2770 static void init_func_state(struct bpf_verifier_env *env, 2771 struct bpf_func_state *state, 2772 int callsite, int frameno, int subprogno) 2773 { 2774 state->callsite = callsite; 2775 state->frameno = frameno; 2776 state->subprogno = subprogno; 2777 state->callback_ret_range = retval_range(0, 0); 2778 init_reg_state(env, state); 2779 mark_verifier_state_scratched(env); 2780 } 2781 2782 /* Similar to push_stack(), but for async callbacks */ 2783 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2784 int insn_idx, int prev_insn_idx, 2785 int subprog, bool is_sleepable) 2786 { 2787 struct bpf_verifier_stack_elem *elem; 2788 struct bpf_func_state *frame; 2789 2790 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2791 if (!elem) 2792 goto err; 2793 2794 elem->insn_idx = insn_idx; 2795 elem->prev_insn_idx = prev_insn_idx; 2796 elem->next = env->head; 2797 elem->log_pos = env->log.end_pos; 2798 env->head = elem; 2799 env->stack_size++; 2800 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2801 verbose(env, 2802 "The sequence of %d jumps is too complex for async cb.\n", 2803 env->stack_size); 2804 goto err; 2805 } 2806 /* Unlike push_stack() do not copy_verifier_state(). 2807 * The caller state doesn't matter. 2808 * This is async callback. It starts in a fresh stack. 2809 * Initialize it similar to do_check_common(). 2810 * But we do need to make sure to not clobber insn_hist, so we keep 2811 * chaining insn_hist_start/insn_hist_end indices as for a normal 2812 * child state. 2813 */ 2814 elem->st.branches = 1; 2815 elem->st.in_sleepable = is_sleepable; 2816 elem->st.insn_hist_start = env->cur_state->insn_hist_end; 2817 elem->st.insn_hist_end = elem->st.insn_hist_start; 2818 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2819 if (!frame) 2820 goto err; 2821 init_func_state(env, frame, 2822 BPF_MAIN_FUNC /* callsite */, 2823 0 /* frameno within this callchain */, 2824 subprog /* subprog number within this prog */); 2825 elem->st.frame[0] = frame; 2826 return &elem->st; 2827 err: 2828 free_verifier_state(env->cur_state, true); 2829 env->cur_state = NULL; 2830 /* pop all elements and return */ 2831 while (!pop_stack(env, NULL, NULL, false)); 2832 return NULL; 2833 } 2834 2835 2836 enum reg_arg_type { 2837 SRC_OP, /* register is used as source operand */ 2838 DST_OP, /* register is used as destination operand */ 2839 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2840 }; 2841 2842 static int cmp_subprogs(const void *a, const void *b) 2843 { 2844 return ((struct bpf_subprog_info *)a)->start - 2845 ((struct bpf_subprog_info *)b)->start; 2846 } 2847 2848 /* Find subprogram that contains instruction at 'off' */ 2849 static struct bpf_subprog_info *find_containing_subprog(struct bpf_verifier_env *env, int off) 2850 { 2851 struct bpf_subprog_info *vals = env->subprog_info; 2852 int l, r, m; 2853 2854 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0) 2855 return NULL; 2856 2857 l = 0; 2858 r = env->subprog_cnt - 1; 2859 while (l < r) { 2860 m = l + (r - l + 1) / 2; 2861 if (vals[m].start <= off) 2862 l = m; 2863 else 2864 r = m - 1; 2865 } 2866 return &vals[l]; 2867 } 2868 2869 /* Find subprogram that starts exactly at 'off' */ 2870 static int find_subprog(struct bpf_verifier_env *env, int off) 2871 { 2872 struct bpf_subprog_info *p; 2873 2874 p = find_containing_subprog(env, off); 2875 if (!p || p->start != off) 2876 return -ENOENT; 2877 return p - env->subprog_info; 2878 } 2879 2880 static int add_subprog(struct bpf_verifier_env *env, int off) 2881 { 2882 int insn_cnt = env->prog->len; 2883 int ret; 2884 2885 if (off >= insn_cnt || off < 0) { 2886 verbose(env, "call to invalid destination\n"); 2887 return -EINVAL; 2888 } 2889 ret = find_subprog(env, off); 2890 if (ret >= 0) 2891 return ret; 2892 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2893 verbose(env, "too many subprograms\n"); 2894 return -E2BIG; 2895 } 2896 /* determine subprog starts. The end is one before the next starts */ 2897 env->subprog_info[env->subprog_cnt++].start = off; 2898 sort(env->subprog_info, env->subprog_cnt, 2899 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2900 return env->subprog_cnt - 1; 2901 } 2902 2903 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2904 { 2905 struct bpf_prog_aux *aux = env->prog->aux; 2906 struct btf *btf = aux->btf; 2907 const struct btf_type *t; 2908 u32 main_btf_id, id; 2909 const char *name; 2910 int ret, i; 2911 2912 /* Non-zero func_info_cnt implies valid btf */ 2913 if (!aux->func_info_cnt) 2914 return 0; 2915 main_btf_id = aux->func_info[0].type_id; 2916 2917 t = btf_type_by_id(btf, main_btf_id); 2918 if (!t) { 2919 verbose(env, "invalid btf id for main subprog in func_info\n"); 2920 return -EINVAL; 2921 } 2922 2923 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2924 if (IS_ERR(name)) { 2925 ret = PTR_ERR(name); 2926 /* If there is no tag present, there is no exception callback */ 2927 if (ret == -ENOENT) 2928 ret = 0; 2929 else if (ret == -EEXIST) 2930 verbose(env, "multiple exception callback tags for main subprog\n"); 2931 return ret; 2932 } 2933 2934 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2935 if (ret < 0) { 2936 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2937 return ret; 2938 } 2939 id = ret; 2940 t = btf_type_by_id(btf, id); 2941 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2942 verbose(env, "exception callback '%s' must have global linkage\n", name); 2943 return -EINVAL; 2944 } 2945 ret = 0; 2946 for (i = 0; i < aux->func_info_cnt; i++) { 2947 if (aux->func_info[i].type_id != id) 2948 continue; 2949 ret = aux->func_info[i].insn_off; 2950 /* Further func_info and subprog checks will also happen 2951 * later, so assume this is the right insn_off for now. 2952 */ 2953 if (!ret) { 2954 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2955 ret = -EINVAL; 2956 } 2957 } 2958 if (!ret) { 2959 verbose(env, "exception callback type id not found in func_info\n"); 2960 ret = -EINVAL; 2961 } 2962 return ret; 2963 } 2964 2965 #define MAX_KFUNC_DESCS 256 2966 #define MAX_KFUNC_BTFS 256 2967 2968 struct bpf_kfunc_desc { 2969 struct btf_func_model func_model; 2970 u32 func_id; 2971 s32 imm; 2972 u16 offset; 2973 unsigned long addr; 2974 }; 2975 2976 struct bpf_kfunc_btf { 2977 struct btf *btf; 2978 struct module *module; 2979 u16 offset; 2980 }; 2981 2982 struct bpf_kfunc_desc_tab { 2983 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2984 * verification. JITs do lookups by bpf_insn, where func_id may not be 2985 * available, therefore at the end of verification do_misc_fixups() 2986 * sorts this by imm and offset. 2987 */ 2988 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2989 u32 nr_descs; 2990 }; 2991 2992 struct bpf_kfunc_btf_tab { 2993 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2994 u32 nr_descs; 2995 }; 2996 2997 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2998 { 2999 const struct bpf_kfunc_desc *d0 = a; 3000 const struct bpf_kfunc_desc *d1 = b; 3001 3002 /* func_id is not greater than BTF_MAX_TYPE */ 3003 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 3004 } 3005 3006 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 3007 { 3008 const struct bpf_kfunc_btf *d0 = a; 3009 const struct bpf_kfunc_btf *d1 = b; 3010 3011 return d0->offset - d1->offset; 3012 } 3013 3014 static const struct bpf_kfunc_desc * 3015 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 3016 { 3017 struct bpf_kfunc_desc desc = { 3018 .func_id = func_id, 3019 .offset = offset, 3020 }; 3021 struct bpf_kfunc_desc_tab *tab; 3022 3023 tab = prog->aux->kfunc_tab; 3024 return bsearch(&desc, tab->descs, tab->nr_descs, 3025 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 3026 } 3027 3028 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 3029 u16 btf_fd_idx, u8 **func_addr) 3030 { 3031 const struct bpf_kfunc_desc *desc; 3032 3033 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 3034 if (!desc) 3035 return -EFAULT; 3036 3037 *func_addr = (u8 *)desc->addr; 3038 return 0; 3039 } 3040 3041 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 3042 s16 offset) 3043 { 3044 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 3045 struct bpf_kfunc_btf_tab *tab; 3046 struct bpf_kfunc_btf *b; 3047 struct module *mod; 3048 struct btf *btf; 3049 int btf_fd; 3050 3051 tab = env->prog->aux->kfunc_btf_tab; 3052 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 3053 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 3054 if (!b) { 3055 if (tab->nr_descs == MAX_KFUNC_BTFS) { 3056 verbose(env, "too many different module BTFs\n"); 3057 return ERR_PTR(-E2BIG); 3058 } 3059 3060 if (bpfptr_is_null(env->fd_array)) { 3061 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 3062 return ERR_PTR(-EPROTO); 3063 } 3064 3065 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 3066 offset * sizeof(btf_fd), 3067 sizeof(btf_fd))) 3068 return ERR_PTR(-EFAULT); 3069 3070 btf = btf_get_by_fd(btf_fd); 3071 if (IS_ERR(btf)) { 3072 verbose(env, "invalid module BTF fd specified\n"); 3073 return btf; 3074 } 3075 3076 if (!btf_is_module(btf)) { 3077 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 3078 btf_put(btf); 3079 return ERR_PTR(-EINVAL); 3080 } 3081 3082 mod = btf_try_get_module(btf); 3083 if (!mod) { 3084 btf_put(btf); 3085 return ERR_PTR(-ENXIO); 3086 } 3087 3088 b = &tab->descs[tab->nr_descs++]; 3089 b->btf = btf; 3090 b->module = mod; 3091 b->offset = offset; 3092 3093 /* sort() reorders entries by value, so b may no longer point 3094 * to the right entry after this 3095 */ 3096 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3097 kfunc_btf_cmp_by_off, NULL); 3098 } else { 3099 btf = b->btf; 3100 } 3101 3102 return btf; 3103 } 3104 3105 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 3106 { 3107 if (!tab) 3108 return; 3109 3110 while (tab->nr_descs--) { 3111 module_put(tab->descs[tab->nr_descs].module); 3112 btf_put(tab->descs[tab->nr_descs].btf); 3113 } 3114 kfree(tab); 3115 } 3116 3117 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 3118 { 3119 if (offset) { 3120 if (offset < 0) { 3121 /* In the future, this can be allowed to increase limit 3122 * of fd index into fd_array, interpreted as u16. 3123 */ 3124 verbose(env, "negative offset disallowed for kernel module function call\n"); 3125 return ERR_PTR(-EINVAL); 3126 } 3127 3128 return __find_kfunc_desc_btf(env, offset); 3129 } 3130 return btf_vmlinux ?: ERR_PTR(-ENOENT); 3131 } 3132 3133 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 3134 { 3135 const struct btf_type *func, *func_proto; 3136 struct bpf_kfunc_btf_tab *btf_tab; 3137 struct bpf_kfunc_desc_tab *tab; 3138 struct bpf_prog_aux *prog_aux; 3139 struct bpf_kfunc_desc *desc; 3140 const char *func_name; 3141 struct btf *desc_btf; 3142 unsigned long call_imm; 3143 unsigned long addr; 3144 int err; 3145 3146 prog_aux = env->prog->aux; 3147 tab = prog_aux->kfunc_tab; 3148 btf_tab = prog_aux->kfunc_btf_tab; 3149 if (!tab) { 3150 if (!btf_vmlinux) { 3151 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 3152 return -ENOTSUPP; 3153 } 3154 3155 if (!env->prog->jit_requested) { 3156 verbose(env, "JIT is required for calling kernel function\n"); 3157 return -ENOTSUPP; 3158 } 3159 3160 if (!bpf_jit_supports_kfunc_call()) { 3161 verbose(env, "JIT does not support calling kernel function\n"); 3162 return -ENOTSUPP; 3163 } 3164 3165 if (!env->prog->gpl_compatible) { 3166 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 3167 return -EINVAL; 3168 } 3169 3170 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 3171 if (!tab) 3172 return -ENOMEM; 3173 prog_aux->kfunc_tab = tab; 3174 } 3175 3176 /* func_id == 0 is always invalid, but instead of returning an error, be 3177 * conservative and wait until the code elimination pass before returning 3178 * error, so that invalid calls that get pruned out can be in BPF programs 3179 * loaded from userspace. It is also required that offset be untouched 3180 * for such calls. 3181 */ 3182 if (!func_id && !offset) 3183 return 0; 3184 3185 if (!btf_tab && offset) { 3186 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 3187 if (!btf_tab) 3188 return -ENOMEM; 3189 prog_aux->kfunc_btf_tab = btf_tab; 3190 } 3191 3192 desc_btf = find_kfunc_desc_btf(env, offset); 3193 if (IS_ERR(desc_btf)) { 3194 verbose(env, "failed to find BTF for kernel function\n"); 3195 return PTR_ERR(desc_btf); 3196 } 3197 3198 if (find_kfunc_desc(env->prog, func_id, offset)) 3199 return 0; 3200 3201 if (tab->nr_descs == MAX_KFUNC_DESCS) { 3202 verbose(env, "too many different kernel function calls\n"); 3203 return -E2BIG; 3204 } 3205 3206 func = btf_type_by_id(desc_btf, func_id); 3207 if (!func || !btf_type_is_func(func)) { 3208 verbose(env, "kernel btf_id %u is not a function\n", 3209 func_id); 3210 return -EINVAL; 3211 } 3212 func_proto = btf_type_by_id(desc_btf, func->type); 3213 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 3214 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 3215 func_id); 3216 return -EINVAL; 3217 } 3218 3219 func_name = btf_name_by_offset(desc_btf, func->name_off); 3220 addr = kallsyms_lookup_name(func_name); 3221 if (!addr) { 3222 verbose(env, "cannot find address for kernel function %s\n", 3223 func_name); 3224 return -EINVAL; 3225 } 3226 specialize_kfunc(env, func_id, offset, &addr); 3227 3228 if (bpf_jit_supports_far_kfunc_call()) { 3229 call_imm = func_id; 3230 } else { 3231 call_imm = BPF_CALL_IMM(addr); 3232 /* Check whether the relative offset overflows desc->imm */ 3233 if ((unsigned long)(s32)call_imm != call_imm) { 3234 verbose(env, "address of kernel function %s is out of range\n", 3235 func_name); 3236 return -EINVAL; 3237 } 3238 } 3239 3240 if (bpf_dev_bound_kfunc_id(func_id)) { 3241 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 3242 if (err) 3243 return err; 3244 } 3245 3246 desc = &tab->descs[tab->nr_descs++]; 3247 desc->func_id = func_id; 3248 desc->imm = call_imm; 3249 desc->offset = offset; 3250 desc->addr = addr; 3251 err = btf_distill_func_proto(&env->log, desc_btf, 3252 func_proto, func_name, 3253 &desc->func_model); 3254 if (!err) 3255 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3256 kfunc_desc_cmp_by_id_off, NULL); 3257 return err; 3258 } 3259 3260 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 3261 { 3262 const struct bpf_kfunc_desc *d0 = a; 3263 const struct bpf_kfunc_desc *d1 = b; 3264 3265 if (d0->imm != d1->imm) 3266 return d0->imm < d1->imm ? -1 : 1; 3267 if (d0->offset != d1->offset) 3268 return d0->offset < d1->offset ? -1 : 1; 3269 return 0; 3270 } 3271 3272 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 3273 { 3274 struct bpf_kfunc_desc_tab *tab; 3275 3276 tab = prog->aux->kfunc_tab; 3277 if (!tab) 3278 return; 3279 3280 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3281 kfunc_desc_cmp_by_imm_off, NULL); 3282 } 3283 3284 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 3285 { 3286 return !!prog->aux->kfunc_tab; 3287 } 3288 3289 const struct btf_func_model * 3290 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 3291 const struct bpf_insn *insn) 3292 { 3293 const struct bpf_kfunc_desc desc = { 3294 .imm = insn->imm, 3295 .offset = insn->off, 3296 }; 3297 const struct bpf_kfunc_desc *res; 3298 struct bpf_kfunc_desc_tab *tab; 3299 3300 tab = prog->aux->kfunc_tab; 3301 res = bsearch(&desc, tab->descs, tab->nr_descs, 3302 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 3303 3304 return res ? &res->func_model : NULL; 3305 } 3306 3307 static int add_kfunc_in_insns(struct bpf_verifier_env *env, 3308 struct bpf_insn *insn, int cnt) 3309 { 3310 int i, ret; 3311 3312 for (i = 0; i < cnt; i++, insn++) { 3313 if (bpf_pseudo_kfunc_call(insn)) { 3314 ret = add_kfunc_call(env, insn->imm, insn->off); 3315 if (ret < 0) 3316 return ret; 3317 } 3318 } 3319 return 0; 3320 } 3321 3322 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 3323 { 3324 struct bpf_subprog_info *subprog = env->subprog_info; 3325 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 3326 struct bpf_insn *insn = env->prog->insnsi; 3327 3328 /* Add entry function. */ 3329 ret = add_subprog(env, 0); 3330 if (ret) 3331 return ret; 3332 3333 for (i = 0; i < insn_cnt; i++, insn++) { 3334 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 3335 !bpf_pseudo_kfunc_call(insn)) 3336 continue; 3337 3338 if (!env->bpf_capable) { 3339 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 3340 return -EPERM; 3341 } 3342 3343 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 3344 ret = add_subprog(env, i + insn->imm + 1); 3345 else 3346 ret = add_kfunc_call(env, insn->imm, insn->off); 3347 3348 if (ret < 0) 3349 return ret; 3350 } 3351 3352 ret = bpf_find_exception_callback_insn_off(env); 3353 if (ret < 0) 3354 return ret; 3355 ex_cb_insn = ret; 3356 3357 /* If ex_cb_insn > 0, this means that the main program has a subprog 3358 * marked using BTF decl tag to serve as the exception callback. 3359 */ 3360 if (ex_cb_insn) { 3361 ret = add_subprog(env, ex_cb_insn); 3362 if (ret < 0) 3363 return ret; 3364 for (i = 1; i < env->subprog_cnt; i++) { 3365 if (env->subprog_info[i].start != ex_cb_insn) 3366 continue; 3367 env->exception_callback_subprog = i; 3368 mark_subprog_exc_cb(env, i); 3369 break; 3370 } 3371 } 3372 3373 /* Add a fake 'exit' subprog which could simplify subprog iteration 3374 * logic. 'subprog_cnt' should not be increased. 3375 */ 3376 subprog[env->subprog_cnt].start = insn_cnt; 3377 3378 if (env->log.level & BPF_LOG_LEVEL2) 3379 for (i = 0; i < env->subprog_cnt; i++) 3380 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3381 3382 return 0; 3383 } 3384 3385 static int jmp_offset(struct bpf_insn *insn) 3386 { 3387 u8 code = insn->code; 3388 3389 if (code == (BPF_JMP32 | BPF_JA)) 3390 return insn->imm; 3391 return insn->off; 3392 } 3393 3394 static int check_subprogs(struct bpf_verifier_env *env) 3395 { 3396 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3397 struct bpf_subprog_info *subprog = env->subprog_info; 3398 struct bpf_insn *insn = env->prog->insnsi; 3399 int insn_cnt = env->prog->len; 3400 3401 /* now check that all jumps are within the same subprog */ 3402 subprog_start = subprog[cur_subprog].start; 3403 subprog_end = subprog[cur_subprog + 1].start; 3404 for (i = 0; i < insn_cnt; i++) { 3405 u8 code = insn[i].code; 3406 3407 if (code == (BPF_JMP | BPF_CALL) && 3408 insn[i].src_reg == 0 && 3409 insn[i].imm == BPF_FUNC_tail_call) { 3410 subprog[cur_subprog].has_tail_call = true; 3411 subprog[cur_subprog].tail_call_reachable = true; 3412 } 3413 if (BPF_CLASS(code) == BPF_LD && 3414 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3415 subprog[cur_subprog].has_ld_abs = true; 3416 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3417 goto next; 3418 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 3419 goto next; 3420 off = i + jmp_offset(&insn[i]) + 1; 3421 if (off < subprog_start || off >= subprog_end) { 3422 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3423 return -EINVAL; 3424 } 3425 next: 3426 if (i == subprog_end - 1) { 3427 /* to avoid fall-through from one subprog into another 3428 * the last insn of the subprog should be either exit 3429 * or unconditional jump back or bpf_throw call 3430 */ 3431 if (code != (BPF_JMP | BPF_EXIT) && 3432 code != (BPF_JMP32 | BPF_JA) && 3433 code != (BPF_JMP | BPF_JA)) { 3434 verbose(env, "last insn is not an exit or jmp\n"); 3435 return -EINVAL; 3436 } 3437 subprog_start = subprog_end; 3438 cur_subprog++; 3439 if (cur_subprog < env->subprog_cnt) 3440 subprog_end = subprog[cur_subprog + 1].start; 3441 } 3442 } 3443 return 0; 3444 } 3445 3446 /* Parentage chain of this register (or stack slot) should take care of all 3447 * issues like callee-saved registers, stack slot allocation time, etc. 3448 */ 3449 static int mark_reg_read(struct bpf_verifier_env *env, 3450 const struct bpf_reg_state *state, 3451 struct bpf_reg_state *parent, u8 flag) 3452 { 3453 bool writes = parent == state->parent; /* Observe write marks */ 3454 int cnt = 0; 3455 3456 while (parent) { 3457 /* if read wasn't screened by an earlier write ... */ 3458 if (writes && state->live & REG_LIVE_WRITTEN) 3459 break; 3460 if (verifier_bug_if(parent->live & REG_LIVE_DONE, env, 3461 "type %s var_off %lld off %d", 3462 reg_type_str(env, parent->type), 3463 parent->var_off.value, parent->off)) 3464 return -EFAULT; 3465 /* The first condition is more likely to be true than the 3466 * second, checked it first. 3467 */ 3468 if ((parent->live & REG_LIVE_READ) == flag || 3469 parent->live & REG_LIVE_READ64) 3470 /* The parentage chain never changes and 3471 * this parent was already marked as LIVE_READ. 3472 * There is no need to keep walking the chain again and 3473 * keep re-marking all parents as LIVE_READ. 3474 * This case happens when the same register is read 3475 * multiple times without writes into it in-between. 3476 * Also, if parent has the stronger REG_LIVE_READ64 set, 3477 * then no need to set the weak REG_LIVE_READ32. 3478 */ 3479 break; 3480 /* ... then we depend on parent's value */ 3481 parent->live |= flag; 3482 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3483 if (flag == REG_LIVE_READ64) 3484 parent->live &= ~REG_LIVE_READ32; 3485 state = parent; 3486 parent = state->parent; 3487 writes = true; 3488 cnt++; 3489 } 3490 3491 if (env->longest_mark_read_walk < cnt) 3492 env->longest_mark_read_walk = cnt; 3493 return 0; 3494 } 3495 3496 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3497 int spi, int nr_slots) 3498 { 3499 struct bpf_func_state *state = func(env, reg); 3500 int err, i; 3501 3502 for (i = 0; i < nr_slots; i++) { 3503 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3504 3505 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3506 if (err) 3507 return err; 3508 3509 mark_stack_slot_scratched(env, spi - i); 3510 } 3511 return 0; 3512 } 3513 3514 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3515 { 3516 int spi; 3517 3518 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3519 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3520 * check_kfunc_call. 3521 */ 3522 if (reg->type == CONST_PTR_TO_DYNPTR) 3523 return 0; 3524 spi = dynptr_get_spi(env, reg); 3525 if (spi < 0) 3526 return spi; 3527 /* Caller ensures dynptr is valid and initialized, which means spi is in 3528 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3529 * read. 3530 */ 3531 return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS); 3532 } 3533 3534 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3535 int spi, int nr_slots) 3536 { 3537 return mark_stack_slot_obj_read(env, reg, spi, nr_slots); 3538 } 3539 3540 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3541 { 3542 int spi; 3543 3544 spi = irq_flag_get_spi(env, reg); 3545 if (spi < 0) 3546 return spi; 3547 return mark_stack_slot_obj_read(env, reg, spi, 1); 3548 } 3549 3550 /* This function is supposed to be used by the following 32-bit optimization 3551 * code only. It returns TRUE if the source or destination register operates 3552 * on 64-bit, otherwise return FALSE. 3553 */ 3554 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3555 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3556 { 3557 u8 code, class, op; 3558 3559 code = insn->code; 3560 class = BPF_CLASS(code); 3561 op = BPF_OP(code); 3562 if (class == BPF_JMP) { 3563 /* BPF_EXIT for "main" will reach here. Return TRUE 3564 * conservatively. 3565 */ 3566 if (op == BPF_EXIT) 3567 return true; 3568 if (op == BPF_CALL) { 3569 /* BPF to BPF call will reach here because of marking 3570 * caller saved clobber with DST_OP_NO_MARK for which we 3571 * don't care the register def because they are anyway 3572 * marked as NOT_INIT already. 3573 */ 3574 if (insn->src_reg == BPF_PSEUDO_CALL) 3575 return false; 3576 /* Helper call will reach here because of arg type 3577 * check, conservatively return TRUE. 3578 */ 3579 if (t == SRC_OP) 3580 return true; 3581 3582 return false; 3583 } 3584 } 3585 3586 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3587 return false; 3588 3589 if (class == BPF_ALU64 || class == BPF_JMP || 3590 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3591 return true; 3592 3593 if (class == BPF_ALU || class == BPF_JMP32) 3594 return false; 3595 3596 if (class == BPF_LDX) { 3597 if (t != SRC_OP) 3598 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3599 /* LDX source must be ptr. */ 3600 return true; 3601 } 3602 3603 if (class == BPF_STX) { 3604 /* BPF_STX (including atomic variants) has one or more source 3605 * operands, one of which is a ptr. Check whether the caller is 3606 * asking about it. 3607 */ 3608 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3609 return true; 3610 return BPF_SIZE(code) == BPF_DW; 3611 } 3612 3613 if (class == BPF_LD) { 3614 u8 mode = BPF_MODE(code); 3615 3616 /* LD_IMM64 */ 3617 if (mode == BPF_IMM) 3618 return true; 3619 3620 /* Both LD_IND and LD_ABS return 32-bit data. */ 3621 if (t != SRC_OP) 3622 return false; 3623 3624 /* Implicit ctx ptr. */ 3625 if (regno == BPF_REG_6) 3626 return true; 3627 3628 /* Explicit source could be any width. */ 3629 return true; 3630 } 3631 3632 if (class == BPF_ST) 3633 /* The only source register for BPF_ST is a ptr. */ 3634 return true; 3635 3636 /* Conservatively return true at default. */ 3637 return true; 3638 } 3639 3640 /* Return the regno defined by the insn, or -1. */ 3641 static int insn_def_regno(const struct bpf_insn *insn) 3642 { 3643 switch (BPF_CLASS(insn->code)) { 3644 case BPF_JMP: 3645 case BPF_JMP32: 3646 case BPF_ST: 3647 return -1; 3648 case BPF_STX: 3649 if (BPF_MODE(insn->code) == BPF_ATOMIC || 3650 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) { 3651 if (insn->imm == BPF_CMPXCHG) 3652 return BPF_REG_0; 3653 else if (insn->imm == BPF_LOAD_ACQ) 3654 return insn->dst_reg; 3655 else if (insn->imm & BPF_FETCH) 3656 return insn->src_reg; 3657 } 3658 return -1; 3659 default: 3660 return insn->dst_reg; 3661 } 3662 } 3663 3664 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3665 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3666 { 3667 int dst_reg = insn_def_regno(insn); 3668 3669 if (dst_reg == -1) 3670 return false; 3671 3672 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3673 } 3674 3675 static void mark_insn_zext(struct bpf_verifier_env *env, 3676 struct bpf_reg_state *reg) 3677 { 3678 s32 def_idx = reg->subreg_def; 3679 3680 if (def_idx == DEF_NOT_SUBREG) 3681 return; 3682 3683 env->insn_aux_data[def_idx - 1].zext_dst = true; 3684 /* The dst will be zero extended, so won't be sub-register anymore. */ 3685 reg->subreg_def = DEF_NOT_SUBREG; 3686 } 3687 3688 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3689 enum reg_arg_type t) 3690 { 3691 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3692 struct bpf_reg_state *reg; 3693 bool rw64; 3694 3695 if (regno >= MAX_BPF_REG) { 3696 verbose(env, "R%d is invalid\n", regno); 3697 return -EINVAL; 3698 } 3699 3700 mark_reg_scratched(env, regno); 3701 3702 reg = ®s[regno]; 3703 rw64 = is_reg64(env, insn, regno, reg, t); 3704 if (t == SRC_OP) { 3705 /* check whether register used as source operand can be read */ 3706 if (reg->type == NOT_INIT) { 3707 verbose(env, "R%d !read_ok\n", regno); 3708 return -EACCES; 3709 } 3710 /* We don't need to worry about FP liveness because it's read-only */ 3711 if (regno == BPF_REG_FP) 3712 return 0; 3713 3714 if (rw64) 3715 mark_insn_zext(env, reg); 3716 3717 return mark_reg_read(env, reg, reg->parent, 3718 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3719 } else { 3720 /* check whether register used as dest operand can be written to */ 3721 if (regno == BPF_REG_FP) { 3722 verbose(env, "frame pointer is read only\n"); 3723 return -EACCES; 3724 } 3725 reg->live |= REG_LIVE_WRITTEN; 3726 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3727 if (t == DST_OP) 3728 mark_reg_unknown(env, regs, regno); 3729 } 3730 return 0; 3731 } 3732 3733 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3734 enum reg_arg_type t) 3735 { 3736 struct bpf_verifier_state *vstate = env->cur_state; 3737 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3738 3739 return __check_reg_arg(env, state->regs, regno, t); 3740 } 3741 3742 static int insn_stack_access_flags(int frameno, int spi) 3743 { 3744 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3745 } 3746 3747 static int insn_stack_access_spi(int insn_flags) 3748 { 3749 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3750 } 3751 3752 static int insn_stack_access_frameno(int insn_flags) 3753 { 3754 return insn_flags & INSN_F_FRAMENO_MASK; 3755 } 3756 3757 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3758 { 3759 env->insn_aux_data[idx].jmp_point = true; 3760 } 3761 3762 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3763 { 3764 return env->insn_aux_data[insn_idx].jmp_point; 3765 } 3766 3767 #define LR_FRAMENO_BITS 3 3768 #define LR_SPI_BITS 6 3769 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3770 #define LR_SIZE_BITS 4 3771 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3772 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3773 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3774 #define LR_SPI_OFF LR_FRAMENO_BITS 3775 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3776 #define LINKED_REGS_MAX 6 3777 3778 struct linked_reg { 3779 u8 frameno; 3780 union { 3781 u8 spi; 3782 u8 regno; 3783 }; 3784 bool is_reg; 3785 }; 3786 3787 struct linked_regs { 3788 int cnt; 3789 struct linked_reg entries[LINKED_REGS_MAX]; 3790 }; 3791 3792 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3793 { 3794 if (s->cnt < LINKED_REGS_MAX) 3795 return &s->entries[s->cnt++]; 3796 3797 return NULL; 3798 } 3799 3800 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track 3801 * number of elements currently in stack. 3802 * Pack one history entry for linked registers as 10 bits in the following format: 3803 * - 3-bits frameno 3804 * - 6-bits spi_or_reg 3805 * - 1-bit is_reg 3806 */ 3807 static u64 linked_regs_pack(struct linked_regs *s) 3808 { 3809 u64 val = 0; 3810 int i; 3811 3812 for (i = 0; i < s->cnt; ++i) { 3813 struct linked_reg *e = &s->entries[i]; 3814 u64 tmp = 0; 3815 3816 tmp |= e->frameno; 3817 tmp |= e->spi << LR_SPI_OFF; 3818 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3819 3820 val <<= LR_ENTRY_BITS; 3821 val |= tmp; 3822 } 3823 val <<= LR_SIZE_BITS; 3824 val |= s->cnt; 3825 return val; 3826 } 3827 3828 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3829 { 3830 int i; 3831 3832 s->cnt = val & LR_SIZE_MASK; 3833 val >>= LR_SIZE_BITS; 3834 3835 for (i = 0; i < s->cnt; ++i) { 3836 struct linked_reg *e = &s->entries[i]; 3837 3838 e->frameno = val & LR_FRAMENO_MASK; 3839 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3840 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3841 val >>= LR_ENTRY_BITS; 3842 } 3843 } 3844 3845 /* for any branch, call, exit record the history of jmps in the given state */ 3846 static int push_insn_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3847 int insn_flags, u64 linked_regs) 3848 { 3849 struct bpf_insn_hist_entry *p; 3850 size_t alloc_size; 3851 3852 /* combine instruction flags if we already recorded this instruction */ 3853 if (env->cur_hist_ent) { 3854 /* atomic instructions push insn_flags twice, for READ and 3855 * WRITE sides, but they should agree on stack slot 3856 */ 3857 verifier_bug_if((env->cur_hist_ent->flags & insn_flags) && 3858 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3859 env, "insn history: insn_idx %d cur flags %x new flags %x", 3860 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3861 env->cur_hist_ent->flags |= insn_flags; 3862 verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env, 3863 "insn history: insn_idx %d linked_regs: %#llx", 3864 env->insn_idx, env->cur_hist_ent->linked_regs); 3865 env->cur_hist_ent->linked_regs = linked_regs; 3866 return 0; 3867 } 3868 3869 if (cur->insn_hist_end + 1 > env->insn_hist_cap) { 3870 alloc_size = size_mul(cur->insn_hist_end + 1, sizeof(*p)); 3871 p = kvrealloc(env->insn_hist, alloc_size, GFP_USER); 3872 if (!p) 3873 return -ENOMEM; 3874 env->insn_hist = p; 3875 env->insn_hist_cap = alloc_size / sizeof(*p); 3876 } 3877 3878 p = &env->insn_hist[cur->insn_hist_end]; 3879 p->idx = env->insn_idx; 3880 p->prev_idx = env->prev_insn_idx; 3881 p->flags = insn_flags; 3882 p->linked_regs = linked_regs; 3883 3884 cur->insn_hist_end++; 3885 env->cur_hist_ent = p; 3886 3887 return 0; 3888 } 3889 3890 static struct bpf_insn_hist_entry *get_insn_hist_entry(struct bpf_verifier_env *env, 3891 u32 hist_start, u32 hist_end, int insn_idx) 3892 { 3893 if (hist_end > hist_start && env->insn_hist[hist_end - 1].idx == insn_idx) 3894 return &env->insn_hist[hist_end - 1]; 3895 return NULL; 3896 } 3897 3898 /* Backtrack one insn at a time. If idx is not at the top of recorded 3899 * history then previous instruction came from straight line execution. 3900 * Return -ENOENT if we exhausted all instructions within given state. 3901 * 3902 * It's legal to have a bit of a looping with the same starting and ending 3903 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3904 * instruction index is the same as state's first_idx doesn't mean we are 3905 * done. If there is still some jump history left, we should keep going. We 3906 * need to take into account that we might have a jump history between given 3907 * state's parent and itself, due to checkpointing. In this case, we'll have 3908 * history entry recording a jump from last instruction of parent state and 3909 * first instruction of given state. 3910 */ 3911 static int get_prev_insn_idx(const struct bpf_verifier_env *env, 3912 struct bpf_verifier_state *st, 3913 int insn_idx, u32 hist_start, u32 *hist_endp) 3914 { 3915 u32 hist_end = *hist_endp; 3916 u32 cnt = hist_end - hist_start; 3917 3918 if (insn_idx == st->first_insn_idx) { 3919 if (cnt == 0) 3920 return -ENOENT; 3921 if (cnt == 1 && env->insn_hist[hist_start].idx == insn_idx) 3922 return -ENOENT; 3923 } 3924 3925 if (cnt && env->insn_hist[hist_end - 1].idx == insn_idx) { 3926 (*hist_endp)--; 3927 return env->insn_hist[hist_end - 1].prev_idx; 3928 } else { 3929 return insn_idx - 1; 3930 } 3931 } 3932 3933 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3934 { 3935 const struct btf_type *func; 3936 struct btf *desc_btf; 3937 3938 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3939 return NULL; 3940 3941 desc_btf = find_kfunc_desc_btf(data, insn->off); 3942 if (IS_ERR(desc_btf)) 3943 return "<error>"; 3944 3945 func = btf_type_by_id(desc_btf, insn->imm); 3946 return btf_name_by_offset(desc_btf, func->name_off); 3947 } 3948 3949 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn) 3950 { 3951 const struct bpf_insn_cbs cbs = { 3952 .cb_call = disasm_kfunc_name, 3953 .cb_print = verbose, 3954 .private_data = env, 3955 }; 3956 3957 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3958 } 3959 3960 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3961 { 3962 bt->frame = frame; 3963 } 3964 3965 static inline void bt_reset(struct backtrack_state *bt) 3966 { 3967 struct bpf_verifier_env *env = bt->env; 3968 3969 memset(bt, 0, sizeof(*bt)); 3970 bt->env = env; 3971 } 3972 3973 static inline u32 bt_empty(struct backtrack_state *bt) 3974 { 3975 u64 mask = 0; 3976 int i; 3977 3978 for (i = 0; i <= bt->frame; i++) 3979 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3980 3981 return mask == 0; 3982 } 3983 3984 static inline int bt_subprog_enter(struct backtrack_state *bt) 3985 { 3986 if (bt->frame == MAX_CALL_FRAMES - 1) { 3987 verifier_bug(bt->env, "subprog enter from frame %d", bt->frame); 3988 return -EFAULT; 3989 } 3990 bt->frame++; 3991 return 0; 3992 } 3993 3994 static inline int bt_subprog_exit(struct backtrack_state *bt) 3995 { 3996 if (bt->frame == 0) { 3997 verifier_bug(bt->env, "subprog exit from frame 0"); 3998 return -EFAULT; 3999 } 4000 bt->frame--; 4001 return 0; 4002 } 4003 4004 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 4005 { 4006 bt->reg_masks[frame] |= 1 << reg; 4007 } 4008 4009 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 4010 { 4011 bt->reg_masks[frame] &= ~(1 << reg); 4012 } 4013 4014 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 4015 { 4016 bt_set_frame_reg(bt, bt->frame, reg); 4017 } 4018 4019 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 4020 { 4021 bt_clear_frame_reg(bt, bt->frame, reg); 4022 } 4023 4024 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 4025 { 4026 bt->stack_masks[frame] |= 1ull << slot; 4027 } 4028 4029 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 4030 { 4031 bt->stack_masks[frame] &= ~(1ull << slot); 4032 } 4033 4034 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 4035 { 4036 return bt->reg_masks[frame]; 4037 } 4038 4039 static inline u32 bt_reg_mask(struct backtrack_state *bt) 4040 { 4041 return bt->reg_masks[bt->frame]; 4042 } 4043 4044 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 4045 { 4046 return bt->stack_masks[frame]; 4047 } 4048 4049 static inline u64 bt_stack_mask(struct backtrack_state *bt) 4050 { 4051 return bt->stack_masks[bt->frame]; 4052 } 4053 4054 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 4055 { 4056 return bt->reg_masks[bt->frame] & (1 << reg); 4057 } 4058 4059 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg) 4060 { 4061 return bt->reg_masks[frame] & (1 << reg); 4062 } 4063 4064 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 4065 { 4066 return bt->stack_masks[frame] & (1ull << slot); 4067 } 4068 4069 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 4070 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 4071 { 4072 DECLARE_BITMAP(mask, 64); 4073 bool first = true; 4074 int i, n; 4075 4076 buf[0] = '\0'; 4077 4078 bitmap_from_u64(mask, reg_mask); 4079 for_each_set_bit(i, mask, 32) { 4080 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 4081 first = false; 4082 buf += n; 4083 buf_sz -= n; 4084 if (buf_sz < 0) 4085 break; 4086 } 4087 } 4088 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 4089 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 4090 { 4091 DECLARE_BITMAP(mask, 64); 4092 bool first = true; 4093 int i, n; 4094 4095 buf[0] = '\0'; 4096 4097 bitmap_from_u64(mask, stack_mask); 4098 for_each_set_bit(i, mask, 64) { 4099 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 4100 first = false; 4101 buf += n; 4102 buf_sz -= n; 4103 if (buf_sz < 0) 4104 break; 4105 } 4106 } 4107 4108 /* If any register R in hist->linked_regs is marked as precise in bt, 4109 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 4110 */ 4111 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_insn_hist_entry *hist) 4112 { 4113 struct linked_regs linked_regs; 4114 bool some_precise = false; 4115 int i; 4116 4117 if (!hist || hist->linked_regs == 0) 4118 return; 4119 4120 linked_regs_unpack(hist->linked_regs, &linked_regs); 4121 for (i = 0; i < linked_regs.cnt; ++i) { 4122 struct linked_reg *e = &linked_regs.entries[i]; 4123 4124 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 4125 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 4126 some_precise = true; 4127 break; 4128 } 4129 } 4130 4131 if (!some_precise) 4132 return; 4133 4134 for (i = 0; i < linked_regs.cnt; ++i) { 4135 struct linked_reg *e = &linked_regs.entries[i]; 4136 4137 if (e->is_reg) 4138 bt_set_frame_reg(bt, e->frameno, e->regno); 4139 else 4140 bt_set_frame_slot(bt, e->frameno, e->spi); 4141 } 4142 } 4143 4144 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 4145 4146 /* For given verifier state backtrack_insn() is called from the last insn to 4147 * the first insn. Its purpose is to compute a bitmask of registers and 4148 * stack slots that needs precision in the parent verifier state. 4149 * 4150 * @idx is an index of the instruction we are currently processing; 4151 * @subseq_idx is an index of the subsequent instruction that: 4152 * - *would be* executed next, if jump history is viewed in forward order; 4153 * - *was* processed previously during backtracking. 4154 */ 4155 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 4156 struct bpf_insn_hist_entry *hist, struct backtrack_state *bt) 4157 { 4158 struct bpf_insn *insn = env->prog->insnsi + idx; 4159 u8 class = BPF_CLASS(insn->code); 4160 u8 opcode = BPF_OP(insn->code); 4161 u8 mode = BPF_MODE(insn->code); 4162 u32 dreg = insn->dst_reg; 4163 u32 sreg = insn->src_reg; 4164 u32 spi, i, fr; 4165 4166 if (insn->code == 0) 4167 return 0; 4168 if (env->log.level & BPF_LOG_LEVEL2) { 4169 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 4170 verbose(env, "mark_precise: frame%d: regs=%s ", 4171 bt->frame, env->tmp_str_buf); 4172 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 4173 verbose(env, "stack=%s before ", env->tmp_str_buf); 4174 verbose(env, "%d: ", idx); 4175 verbose_insn(env, insn); 4176 } 4177 4178 /* If there is a history record that some registers gained range at this insn, 4179 * propagate precision marks to those registers, so that bt_is_reg_set() 4180 * accounts for these registers. 4181 */ 4182 bt_sync_linked_regs(bt, hist); 4183 4184 if (class == BPF_ALU || class == BPF_ALU64) { 4185 if (!bt_is_reg_set(bt, dreg)) 4186 return 0; 4187 if (opcode == BPF_END || opcode == BPF_NEG) { 4188 /* sreg is reserved and unused 4189 * dreg still need precision before this insn 4190 */ 4191 return 0; 4192 } else if (opcode == BPF_MOV) { 4193 if (BPF_SRC(insn->code) == BPF_X) { 4194 /* dreg = sreg or dreg = (s8, s16, s32)sreg 4195 * dreg needs precision after this insn 4196 * sreg needs precision before this insn 4197 */ 4198 bt_clear_reg(bt, dreg); 4199 if (sreg != BPF_REG_FP) 4200 bt_set_reg(bt, sreg); 4201 } else { 4202 /* dreg = K 4203 * dreg needs precision after this insn. 4204 * Corresponding register is already marked 4205 * as precise=true in this verifier state. 4206 * No further markings in parent are necessary 4207 */ 4208 bt_clear_reg(bt, dreg); 4209 } 4210 } else { 4211 if (BPF_SRC(insn->code) == BPF_X) { 4212 /* dreg += sreg 4213 * both dreg and sreg need precision 4214 * before this insn 4215 */ 4216 if (sreg != BPF_REG_FP) 4217 bt_set_reg(bt, sreg); 4218 } /* else dreg += K 4219 * dreg still needs precision before this insn 4220 */ 4221 } 4222 } else if (class == BPF_LDX || is_atomic_load_insn(insn)) { 4223 if (!bt_is_reg_set(bt, dreg)) 4224 return 0; 4225 bt_clear_reg(bt, dreg); 4226 4227 /* scalars can only be spilled into stack w/o losing precision. 4228 * Load from any other memory can be zero extended. 4229 * The desire to keep that precision is already indicated 4230 * by 'precise' mark in corresponding register of this state. 4231 * No further tracking necessary. 4232 */ 4233 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 4234 return 0; 4235 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 4236 * that [fp - off] slot contains scalar that needs to be 4237 * tracked with precision 4238 */ 4239 spi = insn_stack_access_spi(hist->flags); 4240 fr = insn_stack_access_frameno(hist->flags); 4241 bt_set_frame_slot(bt, fr, spi); 4242 } else if (class == BPF_STX || class == BPF_ST) { 4243 if (bt_is_reg_set(bt, dreg)) 4244 /* stx & st shouldn't be using _scalar_ dst_reg 4245 * to access memory. It means backtracking 4246 * encountered a case of pointer subtraction. 4247 */ 4248 return -ENOTSUPP; 4249 /* scalars can only be spilled into stack */ 4250 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 4251 return 0; 4252 spi = insn_stack_access_spi(hist->flags); 4253 fr = insn_stack_access_frameno(hist->flags); 4254 if (!bt_is_frame_slot_set(bt, fr, spi)) 4255 return 0; 4256 bt_clear_frame_slot(bt, fr, spi); 4257 if (class == BPF_STX) 4258 bt_set_reg(bt, sreg); 4259 } else if (class == BPF_JMP || class == BPF_JMP32) { 4260 if (bpf_pseudo_call(insn)) { 4261 int subprog_insn_idx, subprog; 4262 4263 subprog_insn_idx = idx + insn->imm + 1; 4264 subprog = find_subprog(env, subprog_insn_idx); 4265 if (subprog < 0) 4266 return -EFAULT; 4267 4268 if (subprog_is_global(env, subprog)) { 4269 /* check that jump history doesn't have any 4270 * extra instructions from subprog; the next 4271 * instruction after call to global subprog 4272 * should be literally next instruction in 4273 * caller program 4274 */ 4275 verifier_bug_if(idx + 1 != subseq_idx, env, 4276 "extra insn from subprog"); 4277 /* r1-r5 are invalidated after subprog call, 4278 * so for global func call it shouldn't be set 4279 * anymore 4280 */ 4281 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 4282 verifier_bug(env, "global subprog unexpected regs %x", 4283 bt_reg_mask(bt)); 4284 return -EFAULT; 4285 } 4286 /* global subprog always sets R0 */ 4287 bt_clear_reg(bt, BPF_REG_0); 4288 return 0; 4289 } else { 4290 /* static subprog call instruction, which 4291 * means that we are exiting current subprog, 4292 * so only r1-r5 could be still requested as 4293 * precise, r0 and r6-r10 or any stack slot in 4294 * the current frame should be zero by now 4295 */ 4296 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 4297 verifier_bug(env, "static subprog unexpected regs %x", 4298 bt_reg_mask(bt)); 4299 return -EFAULT; 4300 } 4301 /* we are now tracking register spills correctly, 4302 * so any instance of leftover slots is a bug 4303 */ 4304 if (bt_stack_mask(bt) != 0) { 4305 verifier_bug(env, 4306 "static subprog leftover stack slots %llx", 4307 bt_stack_mask(bt)); 4308 return -EFAULT; 4309 } 4310 /* propagate r1-r5 to the caller */ 4311 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 4312 if (bt_is_reg_set(bt, i)) { 4313 bt_clear_reg(bt, i); 4314 bt_set_frame_reg(bt, bt->frame - 1, i); 4315 } 4316 } 4317 if (bt_subprog_exit(bt)) 4318 return -EFAULT; 4319 return 0; 4320 } 4321 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 4322 /* exit from callback subprog to callback-calling helper or 4323 * kfunc call. Use idx/subseq_idx check to discern it from 4324 * straight line code backtracking. 4325 * Unlike the subprog call handling above, we shouldn't 4326 * propagate precision of r1-r5 (if any requested), as they are 4327 * not actually arguments passed directly to callback subprogs 4328 */ 4329 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 4330 verifier_bug(env, "callback unexpected regs %x", 4331 bt_reg_mask(bt)); 4332 return -EFAULT; 4333 } 4334 if (bt_stack_mask(bt) != 0) { 4335 verifier_bug(env, "callback leftover stack slots %llx", 4336 bt_stack_mask(bt)); 4337 return -EFAULT; 4338 } 4339 /* clear r1-r5 in callback subprog's mask */ 4340 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 4341 bt_clear_reg(bt, i); 4342 if (bt_subprog_exit(bt)) 4343 return -EFAULT; 4344 return 0; 4345 } else if (opcode == BPF_CALL) { 4346 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 4347 * catch this error later. Make backtracking conservative 4348 * with ENOTSUPP. 4349 */ 4350 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 4351 return -ENOTSUPP; 4352 /* regular helper call sets R0 */ 4353 bt_clear_reg(bt, BPF_REG_0); 4354 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 4355 /* if backtracking was looking for registers R1-R5 4356 * they should have been found already. 4357 */ 4358 verifier_bug(env, "backtracking call unexpected regs %x", 4359 bt_reg_mask(bt)); 4360 return -EFAULT; 4361 } 4362 } else if (opcode == BPF_EXIT) { 4363 bool r0_precise; 4364 4365 /* Backtracking to a nested function call, 'idx' is a part of 4366 * the inner frame 'subseq_idx' is a part of the outer frame. 4367 * In case of a regular function call, instructions giving 4368 * precision to registers R1-R5 should have been found already. 4369 * In case of a callback, it is ok to have R1-R5 marked for 4370 * backtracking, as these registers are set by the function 4371 * invoking callback. 4372 */ 4373 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 4374 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 4375 bt_clear_reg(bt, i); 4376 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 4377 verifier_bug(env, "backtracking exit unexpected regs %x", 4378 bt_reg_mask(bt)); 4379 return -EFAULT; 4380 } 4381 4382 /* BPF_EXIT in subprog or callback always returns 4383 * right after the call instruction, so by checking 4384 * whether the instruction at subseq_idx-1 is subprog 4385 * call or not we can distinguish actual exit from 4386 * *subprog* from exit from *callback*. In the former 4387 * case, we need to propagate r0 precision, if 4388 * necessary. In the former we never do that. 4389 */ 4390 r0_precise = subseq_idx - 1 >= 0 && 4391 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 4392 bt_is_reg_set(bt, BPF_REG_0); 4393 4394 bt_clear_reg(bt, BPF_REG_0); 4395 if (bt_subprog_enter(bt)) 4396 return -EFAULT; 4397 4398 if (r0_precise) 4399 bt_set_reg(bt, BPF_REG_0); 4400 /* r6-r9 and stack slots will stay set in caller frame 4401 * bitmasks until we return back from callee(s) 4402 */ 4403 return 0; 4404 } else if (BPF_SRC(insn->code) == BPF_X) { 4405 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 4406 return 0; 4407 /* dreg <cond> sreg 4408 * Both dreg and sreg need precision before 4409 * this insn. If only sreg was marked precise 4410 * before it would be equally necessary to 4411 * propagate it to dreg. 4412 */ 4413 if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK)) 4414 bt_set_reg(bt, sreg); 4415 if (!hist || !(hist->flags & INSN_F_DST_REG_STACK)) 4416 bt_set_reg(bt, dreg); 4417 } else if (BPF_SRC(insn->code) == BPF_K) { 4418 /* dreg <cond> K 4419 * Only dreg still needs precision before 4420 * this insn, so for the K-based conditional 4421 * there is nothing new to be marked. 4422 */ 4423 } 4424 } else if (class == BPF_LD) { 4425 if (!bt_is_reg_set(bt, dreg)) 4426 return 0; 4427 bt_clear_reg(bt, dreg); 4428 /* It's ld_imm64 or ld_abs or ld_ind. 4429 * For ld_imm64 no further tracking of precision 4430 * into parent is necessary 4431 */ 4432 if (mode == BPF_IND || mode == BPF_ABS) 4433 /* to be analyzed */ 4434 return -ENOTSUPP; 4435 } 4436 /* Propagate precision marks to linked registers, to account for 4437 * registers marked as precise in this function. 4438 */ 4439 bt_sync_linked_regs(bt, hist); 4440 return 0; 4441 } 4442 4443 /* the scalar precision tracking algorithm: 4444 * . at the start all registers have precise=false. 4445 * . scalar ranges are tracked as normal through alu and jmp insns. 4446 * . once precise value of the scalar register is used in: 4447 * . ptr + scalar alu 4448 * . if (scalar cond K|scalar) 4449 * . helper_call(.., scalar, ...) where ARG_CONST is expected 4450 * backtrack through the verifier states and mark all registers and 4451 * stack slots with spilled constants that these scalar regisers 4452 * should be precise. 4453 * . during state pruning two registers (or spilled stack slots) 4454 * are equivalent if both are not precise. 4455 * 4456 * Note the verifier cannot simply walk register parentage chain, 4457 * since many different registers and stack slots could have been 4458 * used to compute single precise scalar. 4459 * 4460 * The approach of starting with precise=true for all registers and then 4461 * backtrack to mark a register as not precise when the verifier detects 4462 * that program doesn't care about specific value (e.g., when helper 4463 * takes register as ARG_ANYTHING parameter) is not safe. 4464 * 4465 * It's ok to walk single parentage chain of the verifier states. 4466 * It's possible that this backtracking will go all the way till 1st insn. 4467 * All other branches will be explored for needing precision later. 4468 * 4469 * The backtracking needs to deal with cases like: 4470 * 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) 4471 * r9 -= r8 4472 * r5 = r9 4473 * if r5 > 0x79f goto pc+7 4474 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 4475 * r5 += 1 4476 * ... 4477 * call bpf_perf_event_output#25 4478 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 4479 * 4480 * and this case: 4481 * r6 = 1 4482 * call foo // uses callee's r6 inside to compute r0 4483 * r0 += r6 4484 * if r0 == 0 goto 4485 * 4486 * to track above reg_mask/stack_mask needs to be independent for each frame. 4487 * 4488 * Also if parent's curframe > frame where backtracking started, 4489 * the verifier need to mark registers in both frames, otherwise callees 4490 * may incorrectly prune callers. This is similar to 4491 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 4492 * 4493 * For now backtracking falls back into conservative marking. 4494 */ 4495 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 4496 struct bpf_verifier_state *st) 4497 { 4498 struct bpf_func_state *func; 4499 struct bpf_reg_state *reg; 4500 int i, j; 4501 4502 if (env->log.level & BPF_LOG_LEVEL2) { 4503 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 4504 st->curframe); 4505 } 4506 4507 /* big hammer: mark all scalars precise in this path. 4508 * pop_stack may still get !precise scalars. 4509 * We also skip current state and go straight to first parent state, 4510 * because precision markings in current non-checkpointed state are 4511 * not needed. See why in the comment in __mark_chain_precision below. 4512 */ 4513 for (st = st->parent; st; st = st->parent) { 4514 for (i = 0; i <= st->curframe; i++) { 4515 func = st->frame[i]; 4516 for (j = 0; j < BPF_REG_FP; j++) { 4517 reg = &func->regs[j]; 4518 if (reg->type != SCALAR_VALUE || reg->precise) 4519 continue; 4520 reg->precise = true; 4521 if (env->log.level & BPF_LOG_LEVEL2) { 4522 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 4523 i, j); 4524 } 4525 } 4526 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4527 if (!is_spilled_reg(&func->stack[j])) 4528 continue; 4529 reg = &func->stack[j].spilled_ptr; 4530 if (reg->type != SCALAR_VALUE || reg->precise) 4531 continue; 4532 reg->precise = true; 4533 if (env->log.level & BPF_LOG_LEVEL2) { 4534 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 4535 i, -(j + 1) * 8); 4536 } 4537 } 4538 } 4539 } 4540 } 4541 4542 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4543 { 4544 struct bpf_func_state *func; 4545 struct bpf_reg_state *reg; 4546 int i, j; 4547 4548 for (i = 0; i <= st->curframe; i++) { 4549 func = st->frame[i]; 4550 for (j = 0; j < BPF_REG_FP; j++) { 4551 reg = &func->regs[j]; 4552 if (reg->type != SCALAR_VALUE) 4553 continue; 4554 reg->precise = false; 4555 } 4556 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4557 if (!is_spilled_reg(&func->stack[j])) 4558 continue; 4559 reg = &func->stack[j].spilled_ptr; 4560 if (reg->type != SCALAR_VALUE) 4561 continue; 4562 reg->precise = false; 4563 } 4564 } 4565 } 4566 4567 /* 4568 * __mark_chain_precision() backtracks BPF program instruction sequence and 4569 * chain of verifier states making sure that register *regno* (if regno >= 0) 4570 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4571 * SCALARS, as well as any other registers and slots that contribute to 4572 * a tracked state of given registers/stack slots, depending on specific BPF 4573 * assembly instructions (see backtrack_insns() for exact instruction handling 4574 * logic). This backtracking relies on recorded insn_hist and is able to 4575 * traverse entire chain of parent states. This process ends only when all the 4576 * necessary registers/slots and their transitive dependencies are marked as 4577 * precise. 4578 * 4579 * One important and subtle aspect is that precise marks *do not matter* in 4580 * the currently verified state (current state). It is important to understand 4581 * why this is the case. 4582 * 4583 * First, note that current state is the state that is not yet "checkpointed", 4584 * i.e., it is not yet put into env->explored_states, and it has no children 4585 * states as well. It's ephemeral, and can end up either a) being discarded if 4586 * compatible explored state is found at some point or BPF_EXIT instruction is 4587 * reached or b) checkpointed and put into env->explored_states, branching out 4588 * into one or more children states. 4589 * 4590 * In the former case, precise markings in current state are completely 4591 * ignored by state comparison code (see regsafe() for details). Only 4592 * checkpointed ("old") state precise markings are important, and if old 4593 * state's register/slot is precise, regsafe() assumes current state's 4594 * register/slot as precise and checks value ranges exactly and precisely. If 4595 * states turn out to be compatible, current state's necessary precise 4596 * markings and any required parent states' precise markings are enforced 4597 * after the fact with propagate_precision() logic, after the fact. But it's 4598 * important to realize that in this case, even after marking current state 4599 * registers/slots as precise, we immediately discard current state. So what 4600 * actually matters is any of the precise markings propagated into current 4601 * state's parent states, which are always checkpointed (due to b) case above). 4602 * As such, for scenario a) it doesn't matter if current state has precise 4603 * markings set or not. 4604 * 4605 * Now, for the scenario b), checkpointing and forking into child(ren) 4606 * state(s). Note that before current state gets to checkpointing step, any 4607 * processed instruction always assumes precise SCALAR register/slot 4608 * knowledge: if precise value or range is useful to prune jump branch, BPF 4609 * verifier takes this opportunity enthusiastically. Similarly, when 4610 * register's value is used to calculate offset or memory address, exact 4611 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4612 * what we mentioned above about state comparison ignoring precise markings 4613 * during state comparison, BPF verifier ignores and also assumes precise 4614 * markings *at will* during instruction verification process. But as verifier 4615 * assumes precision, it also propagates any precision dependencies across 4616 * parent states, which are not yet finalized, so can be further restricted 4617 * based on new knowledge gained from restrictions enforced by their children 4618 * states. This is so that once those parent states are finalized, i.e., when 4619 * they have no more active children state, state comparison logic in 4620 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4621 * required for correctness. 4622 * 4623 * To build a bit more intuition, note also that once a state is checkpointed, 4624 * the path we took to get to that state is not important. This is crucial 4625 * property for state pruning. When state is checkpointed and finalized at 4626 * some instruction index, it can be correctly and safely used to "short 4627 * circuit" any *compatible* state that reaches exactly the same instruction 4628 * index. I.e., if we jumped to that instruction from a completely different 4629 * code path than original finalized state was derived from, it doesn't 4630 * matter, current state can be discarded because from that instruction 4631 * forward having a compatible state will ensure we will safely reach the 4632 * exit. States describe preconditions for further exploration, but completely 4633 * forget the history of how we got here. 4634 * 4635 * This also means that even if we needed precise SCALAR range to get to 4636 * finalized state, but from that point forward *that same* SCALAR register is 4637 * never used in a precise context (i.e., it's precise value is not needed for 4638 * correctness), it's correct and safe to mark such register as "imprecise" 4639 * (i.e., precise marking set to false). This is what we rely on when we do 4640 * not set precise marking in current state. If no child state requires 4641 * precision for any given SCALAR register, it's safe to dictate that it can 4642 * be imprecise. If any child state does require this register to be precise, 4643 * we'll mark it precise later retroactively during precise markings 4644 * propagation from child state to parent states. 4645 * 4646 * Skipping precise marking setting in current state is a mild version of 4647 * relying on the above observation. But we can utilize this property even 4648 * more aggressively by proactively forgetting any precise marking in the 4649 * current state (which we inherited from the parent state), right before we 4650 * checkpoint it and branch off into new child state. This is done by 4651 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4652 * finalized states which help in short circuiting more future states. 4653 */ 4654 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4655 { 4656 struct backtrack_state *bt = &env->bt; 4657 struct bpf_verifier_state *st = env->cur_state; 4658 int first_idx = st->first_insn_idx; 4659 int last_idx = env->insn_idx; 4660 int subseq_idx = -1; 4661 struct bpf_func_state *func; 4662 struct bpf_reg_state *reg; 4663 bool skip_first = true; 4664 int i, fr, err; 4665 4666 if (!env->bpf_capable) 4667 return 0; 4668 4669 /* set frame number from which we are starting to backtrack */ 4670 bt_init(bt, env->cur_state->curframe); 4671 4672 /* Do sanity checks against current state of register and/or stack 4673 * slot, but don't set precise flag in current state, as precision 4674 * tracking in the current state is unnecessary. 4675 */ 4676 func = st->frame[bt->frame]; 4677 if (regno >= 0) { 4678 reg = &func->regs[regno]; 4679 if (reg->type != SCALAR_VALUE) { 4680 WARN_ONCE(1, "backtracing misuse"); 4681 return -EFAULT; 4682 } 4683 bt_set_reg(bt, regno); 4684 } 4685 4686 if (bt_empty(bt)) 4687 return 0; 4688 4689 for (;;) { 4690 DECLARE_BITMAP(mask, 64); 4691 u32 hist_start = st->insn_hist_start; 4692 u32 hist_end = st->insn_hist_end; 4693 struct bpf_insn_hist_entry *hist; 4694 4695 if (env->log.level & BPF_LOG_LEVEL2) { 4696 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4697 bt->frame, last_idx, first_idx, subseq_idx); 4698 } 4699 4700 if (last_idx < 0) { 4701 /* we are at the entry into subprog, which 4702 * is expected for global funcs, but only if 4703 * requested precise registers are R1-R5 4704 * (which are global func's input arguments) 4705 */ 4706 if (st->curframe == 0 && 4707 st->frame[0]->subprogno > 0 && 4708 st->frame[0]->callsite == BPF_MAIN_FUNC && 4709 bt_stack_mask(bt) == 0 && 4710 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4711 bitmap_from_u64(mask, bt_reg_mask(bt)); 4712 for_each_set_bit(i, mask, 32) { 4713 reg = &st->frame[0]->regs[i]; 4714 bt_clear_reg(bt, i); 4715 if (reg->type == SCALAR_VALUE) 4716 reg->precise = true; 4717 } 4718 return 0; 4719 } 4720 4721 verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx", 4722 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4723 return -EFAULT; 4724 } 4725 4726 for (i = last_idx;;) { 4727 if (skip_first) { 4728 err = 0; 4729 skip_first = false; 4730 } else { 4731 hist = get_insn_hist_entry(env, hist_start, hist_end, i); 4732 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4733 } 4734 if (err == -ENOTSUPP) { 4735 mark_all_scalars_precise(env, env->cur_state); 4736 bt_reset(bt); 4737 return 0; 4738 } else if (err) { 4739 return err; 4740 } 4741 if (bt_empty(bt)) 4742 /* Found assignment(s) into tracked register in this state. 4743 * Since this state is already marked, just return. 4744 * Nothing to be tracked further in the parent state. 4745 */ 4746 return 0; 4747 subseq_idx = i; 4748 i = get_prev_insn_idx(env, st, i, hist_start, &hist_end); 4749 if (i == -ENOENT) 4750 break; 4751 if (i >= env->prog->len) { 4752 /* This can happen if backtracking reached insn 0 4753 * and there are still reg_mask or stack_mask 4754 * to backtrack. 4755 * It means the backtracking missed the spot where 4756 * particular register was initialized with a constant. 4757 */ 4758 verifier_bug(env, "backtracking idx %d", i); 4759 return -EFAULT; 4760 } 4761 } 4762 st = st->parent; 4763 if (!st) 4764 break; 4765 4766 for (fr = bt->frame; fr >= 0; fr--) { 4767 func = st->frame[fr]; 4768 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4769 for_each_set_bit(i, mask, 32) { 4770 reg = &func->regs[i]; 4771 if (reg->type != SCALAR_VALUE) { 4772 bt_clear_frame_reg(bt, fr, i); 4773 continue; 4774 } 4775 if (reg->precise) 4776 bt_clear_frame_reg(bt, fr, i); 4777 else 4778 reg->precise = true; 4779 } 4780 4781 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4782 for_each_set_bit(i, mask, 64) { 4783 if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE, 4784 env, "stack slot %d, total slots %d", 4785 i, func->allocated_stack / BPF_REG_SIZE)) 4786 return -EFAULT; 4787 4788 if (!is_spilled_scalar_reg(&func->stack[i])) { 4789 bt_clear_frame_slot(bt, fr, i); 4790 continue; 4791 } 4792 reg = &func->stack[i].spilled_ptr; 4793 if (reg->precise) 4794 bt_clear_frame_slot(bt, fr, i); 4795 else 4796 reg->precise = true; 4797 } 4798 if (env->log.level & BPF_LOG_LEVEL2) { 4799 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4800 bt_frame_reg_mask(bt, fr)); 4801 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4802 fr, env->tmp_str_buf); 4803 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4804 bt_frame_stack_mask(bt, fr)); 4805 verbose(env, "stack=%s: ", env->tmp_str_buf); 4806 print_verifier_state(env, st, fr, true); 4807 } 4808 } 4809 4810 if (bt_empty(bt)) 4811 return 0; 4812 4813 subseq_idx = first_idx; 4814 last_idx = st->last_insn_idx; 4815 first_idx = st->first_insn_idx; 4816 } 4817 4818 /* if we still have requested precise regs or slots, we missed 4819 * something (e.g., stack access through non-r10 register), so 4820 * fallback to marking all precise 4821 */ 4822 if (!bt_empty(bt)) { 4823 mark_all_scalars_precise(env, env->cur_state); 4824 bt_reset(bt); 4825 } 4826 4827 return 0; 4828 } 4829 4830 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4831 { 4832 return __mark_chain_precision(env, regno); 4833 } 4834 4835 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4836 * desired reg and stack masks across all relevant frames 4837 */ 4838 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4839 { 4840 return __mark_chain_precision(env, -1); 4841 } 4842 4843 static bool is_spillable_regtype(enum bpf_reg_type type) 4844 { 4845 switch (base_type(type)) { 4846 case PTR_TO_MAP_VALUE: 4847 case PTR_TO_STACK: 4848 case PTR_TO_CTX: 4849 case PTR_TO_PACKET: 4850 case PTR_TO_PACKET_META: 4851 case PTR_TO_PACKET_END: 4852 case PTR_TO_FLOW_KEYS: 4853 case CONST_PTR_TO_MAP: 4854 case PTR_TO_SOCKET: 4855 case PTR_TO_SOCK_COMMON: 4856 case PTR_TO_TCP_SOCK: 4857 case PTR_TO_XDP_SOCK: 4858 case PTR_TO_BTF_ID: 4859 case PTR_TO_BUF: 4860 case PTR_TO_MEM: 4861 case PTR_TO_FUNC: 4862 case PTR_TO_MAP_KEY: 4863 case PTR_TO_ARENA: 4864 return true; 4865 default: 4866 return false; 4867 } 4868 } 4869 4870 /* Does this register contain a constant zero? */ 4871 static bool register_is_null(struct bpf_reg_state *reg) 4872 { 4873 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4874 } 4875 4876 /* check if register is a constant scalar value */ 4877 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 4878 { 4879 return reg->type == SCALAR_VALUE && 4880 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 4881 } 4882 4883 /* assuming is_reg_const() is true, return constant value of a register */ 4884 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 4885 { 4886 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 4887 } 4888 4889 static bool __is_pointer_value(bool allow_ptr_leaks, 4890 const struct bpf_reg_state *reg) 4891 { 4892 if (allow_ptr_leaks) 4893 return false; 4894 4895 return reg->type != SCALAR_VALUE; 4896 } 4897 4898 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 4899 struct bpf_reg_state *src_reg) 4900 { 4901 if (src_reg->type != SCALAR_VALUE) 4902 return; 4903 4904 if (src_reg->id & BPF_ADD_CONST) { 4905 /* 4906 * The verifier is processing rX = rY insn and 4907 * rY->id has special linked register already. 4908 * Cleared it, since multiple rX += const are not supported. 4909 */ 4910 src_reg->id = 0; 4911 src_reg->off = 0; 4912 } 4913 4914 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 4915 /* Ensure that src_reg has a valid ID that will be copied to 4916 * dst_reg and then will be used by sync_linked_regs() to 4917 * propagate min/max range. 4918 */ 4919 src_reg->id = ++env->id_gen; 4920 } 4921 4922 /* Copy src state preserving dst->parent and dst->live fields */ 4923 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4924 { 4925 struct bpf_reg_state *parent = dst->parent; 4926 enum bpf_reg_liveness live = dst->live; 4927 4928 *dst = *src; 4929 dst->parent = parent; 4930 dst->live = live; 4931 } 4932 4933 static void save_register_state(struct bpf_verifier_env *env, 4934 struct bpf_func_state *state, 4935 int spi, struct bpf_reg_state *reg, 4936 int size) 4937 { 4938 int i; 4939 4940 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4941 if (size == BPF_REG_SIZE) 4942 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4943 4944 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4945 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4946 4947 /* size < 8 bytes spill */ 4948 for (; i; i--) 4949 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4950 } 4951 4952 static bool is_bpf_st_mem(struct bpf_insn *insn) 4953 { 4954 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4955 } 4956 4957 static int get_reg_width(struct bpf_reg_state *reg) 4958 { 4959 return fls64(reg->umax_value); 4960 } 4961 4962 /* See comment for mark_fastcall_pattern_for_call() */ 4963 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 4964 struct bpf_func_state *state, int insn_idx, int off) 4965 { 4966 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4967 struct bpf_insn_aux_data *aux = env->insn_aux_data; 4968 int i; 4969 4970 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 4971 return; 4972 /* access to the region [max_stack_depth .. fastcall_stack_off) 4973 * from something that is not a part of the fastcall pattern, 4974 * disable fastcall rewrites for current subprogram by setting 4975 * fastcall_stack_off to a value smaller than any possible offset. 4976 */ 4977 subprog->fastcall_stack_off = S16_MIN; 4978 /* reset fastcall aux flags within subprogram, 4979 * happens at most once per subprogram 4980 */ 4981 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 4982 aux[i].fastcall_spills_num = 0; 4983 aux[i].fastcall_pattern = 0; 4984 } 4985 } 4986 4987 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4988 * stack boundary and alignment are checked in check_mem_access() 4989 */ 4990 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4991 /* stack frame we're writing to */ 4992 struct bpf_func_state *state, 4993 int off, int size, int value_regno, 4994 int insn_idx) 4995 { 4996 struct bpf_func_state *cur; /* state of the current function */ 4997 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4998 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4999 struct bpf_reg_state *reg = NULL; 5000 int insn_flags = insn_stack_access_flags(state->frameno, spi); 5001 5002 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 5003 * so it's aligned access and [off, off + size) are within stack limits 5004 */ 5005 if (!env->allow_ptr_leaks && 5006 is_spilled_reg(&state->stack[spi]) && 5007 !is_spilled_scalar_reg(&state->stack[spi]) && 5008 size != BPF_REG_SIZE) { 5009 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 5010 return -EACCES; 5011 } 5012 5013 cur = env->cur_state->frame[env->cur_state->curframe]; 5014 if (value_regno >= 0) 5015 reg = &cur->regs[value_regno]; 5016 if (!env->bypass_spec_v4) { 5017 bool sanitize = reg && is_spillable_regtype(reg->type); 5018 5019 for (i = 0; i < size; i++) { 5020 u8 type = state->stack[spi].slot_type[i]; 5021 5022 if (type != STACK_MISC && type != STACK_ZERO) { 5023 sanitize = true; 5024 break; 5025 } 5026 } 5027 5028 if (sanitize) 5029 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 5030 } 5031 5032 err = destroy_if_dynptr_stack_slot(env, state, spi); 5033 if (err) 5034 return err; 5035 5036 check_fastcall_stack_contract(env, state, insn_idx, off); 5037 mark_stack_slot_scratched(env, spi); 5038 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 5039 bool reg_value_fits; 5040 5041 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 5042 /* Make sure that reg had an ID to build a relation on spill. */ 5043 if (reg_value_fits) 5044 assign_scalar_id_before_mov(env, reg); 5045 save_register_state(env, state, spi, reg, size); 5046 /* Break the relation on a narrowing spill. */ 5047 if (!reg_value_fits) 5048 state->stack[spi].spilled_ptr.id = 0; 5049 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 5050 env->bpf_capable) { 5051 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 5052 5053 memset(tmp_reg, 0, sizeof(*tmp_reg)); 5054 __mark_reg_known(tmp_reg, insn->imm); 5055 tmp_reg->type = SCALAR_VALUE; 5056 save_register_state(env, state, spi, tmp_reg, size); 5057 } else if (reg && is_spillable_regtype(reg->type)) { 5058 /* register containing pointer is being spilled into stack */ 5059 if (size != BPF_REG_SIZE) { 5060 verbose_linfo(env, insn_idx, "; "); 5061 verbose(env, "invalid size of register spill\n"); 5062 return -EACCES; 5063 } 5064 if (state != cur && reg->type == PTR_TO_STACK) { 5065 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 5066 return -EINVAL; 5067 } 5068 save_register_state(env, state, spi, reg, size); 5069 } else { 5070 u8 type = STACK_MISC; 5071 5072 /* regular write of data into stack destroys any spilled ptr */ 5073 state->stack[spi].spilled_ptr.type = NOT_INIT; 5074 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 5075 if (is_stack_slot_special(&state->stack[spi])) 5076 for (i = 0; i < BPF_REG_SIZE; i++) 5077 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 5078 5079 /* only mark the slot as written if all 8 bytes were written 5080 * otherwise read propagation may incorrectly stop too soon 5081 * when stack slots are partially written. 5082 * This heuristic means that read propagation will be 5083 * conservative, since it will add reg_live_read marks 5084 * to stack slots all the way to first state when programs 5085 * writes+reads less than 8 bytes 5086 */ 5087 if (size == BPF_REG_SIZE) 5088 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 5089 5090 /* when we zero initialize stack slots mark them as such */ 5091 if ((reg && register_is_null(reg)) || 5092 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 5093 /* STACK_ZERO case happened because register spill 5094 * wasn't properly aligned at the stack slot boundary, 5095 * so it's not a register spill anymore; force 5096 * originating register to be precise to make 5097 * STACK_ZERO correct for subsequent states 5098 */ 5099 err = mark_chain_precision(env, value_regno); 5100 if (err) 5101 return err; 5102 type = STACK_ZERO; 5103 } 5104 5105 /* Mark slots affected by this stack write. */ 5106 for (i = 0; i < size; i++) 5107 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 5108 insn_flags = 0; /* not a register spill */ 5109 } 5110 5111 if (insn_flags) 5112 return push_insn_history(env, env->cur_state, insn_flags, 0); 5113 return 0; 5114 } 5115 5116 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 5117 * known to contain a variable offset. 5118 * This function checks whether the write is permitted and conservatively 5119 * tracks the effects of the write, considering that each stack slot in the 5120 * dynamic range is potentially written to. 5121 * 5122 * 'off' includes 'regno->off'. 5123 * 'value_regno' can be -1, meaning that an unknown value is being written to 5124 * the stack. 5125 * 5126 * Spilled pointers in range are not marked as written because we don't know 5127 * what's going to be actually written. This means that read propagation for 5128 * future reads cannot be terminated by this write. 5129 * 5130 * For privileged programs, uninitialized stack slots are considered 5131 * initialized by this write (even though we don't know exactly what offsets 5132 * are going to be written to). The idea is that we don't want the verifier to 5133 * reject future reads that access slots written to through variable offsets. 5134 */ 5135 static int check_stack_write_var_off(struct bpf_verifier_env *env, 5136 /* func where register points to */ 5137 struct bpf_func_state *state, 5138 int ptr_regno, int off, int size, 5139 int value_regno, int insn_idx) 5140 { 5141 struct bpf_func_state *cur; /* state of the current function */ 5142 int min_off, max_off; 5143 int i, err; 5144 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 5145 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5146 bool writing_zero = false; 5147 /* set if the fact that we're writing a zero is used to let any 5148 * stack slots remain STACK_ZERO 5149 */ 5150 bool zero_used = false; 5151 5152 cur = env->cur_state->frame[env->cur_state->curframe]; 5153 ptr_reg = &cur->regs[ptr_regno]; 5154 min_off = ptr_reg->smin_value + off; 5155 max_off = ptr_reg->smax_value + off + size; 5156 if (value_regno >= 0) 5157 value_reg = &cur->regs[value_regno]; 5158 if ((value_reg && register_is_null(value_reg)) || 5159 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 5160 writing_zero = true; 5161 5162 for (i = min_off; i < max_off; i++) { 5163 int spi; 5164 5165 spi = __get_spi(i); 5166 err = destroy_if_dynptr_stack_slot(env, state, spi); 5167 if (err) 5168 return err; 5169 } 5170 5171 check_fastcall_stack_contract(env, state, insn_idx, min_off); 5172 /* Variable offset writes destroy any spilled pointers in range. */ 5173 for (i = min_off; i < max_off; i++) { 5174 u8 new_type, *stype; 5175 int slot, spi; 5176 5177 slot = -i - 1; 5178 spi = slot / BPF_REG_SIZE; 5179 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 5180 mark_stack_slot_scratched(env, spi); 5181 5182 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 5183 /* Reject the write if range we may write to has not 5184 * been initialized beforehand. If we didn't reject 5185 * here, the ptr status would be erased below (even 5186 * though not all slots are actually overwritten), 5187 * possibly opening the door to leaks. 5188 * 5189 * We do however catch STACK_INVALID case below, and 5190 * only allow reading possibly uninitialized memory 5191 * later for CAP_PERFMON, as the write may not happen to 5192 * that slot. 5193 */ 5194 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 5195 insn_idx, i); 5196 return -EINVAL; 5197 } 5198 5199 /* If writing_zero and the spi slot contains a spill of value 0, 5200 * maintain the spill type. 5201 */ 5202 if (writing_zero && *stype == STACK_SPILL && 5203 is_spilled_scalar_reg(&state->stack[spi])) { 5204 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 5205 5206 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 5207 zero_used = true; 5208 continue; 5209 } 5210 } 5211 5212 /* Erase all other spilled pointers. */ 5213 state->stack[spi].spilled_ptr.type = NOT_INIT; 5214 5215 /* Update the slot type. */ 5216 new_type = STACK_MISC; 5217 if (writing_zero && *stype == STACK_ZERO) { 5218 new_type = STACK_ZERO; 5219 zero_used = true; 5220 } 5221 /* If the slot is STACK_INVALID, we check whether it's OK to 5222 * pretend that it will be initialized by this write. The slot 5223 * might not actually be written to, and so if we mark it as 5224 * initialized future reads might leak uninitialized memory. 5225 * For privileged programs, we will accept such reads to slots 5226 * that may or may not be written because, if we're reject 5227 * them, the error would be too confusing. 5228 */ 5229 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 5230 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 5231 insn_idx, i); 5232 return -EINVAL; 5233 } 5234 *stype = new_type; 5235 } 5236 if (zero_used) { 5237 /* backtracking doesn't work for STACK_ZERO yet. */ 5238 err = mark_chain_precision(env, value_regno); 5239 if (err) 5240 return err; 5241 } 5242 return 0; 5243 } 5244 5245 /* When register 'dst_regno' is assigned some values from stack[min_off, 5246 * max_off), we set the register's type according to the types of the 5247 * respective stack slots. If all the stack values are known to be zeros, then 5248 * so is the destination reg. Otherwise, the register is considered to be 5249 * SCALAR. This function does not deal with register filling; the caller must 5250 * ensure that all spilled registers in the stack range have been marked as 5251 * read. 5252 */ 5253 static void mark_reg_stack_read(struct bpf_verifier_env *env, 5254 /* func where src register points to */ 5255 struct bpf_func_state *ptr_state, 5256 int min_off, int max_off, int dst_regno) 5257 { 5258 struct bpf_verifier_state *vstate = env->cur_state; 5259 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5260 int i, slot, spi; 5261 u8 *stype; 5262 int zeros = 0; 5263 5264 for (i = min_off; i < max_off; i++) { 5265 slot = -i - 1; 5266 spi = slot / BPF_REG_SIZE; 5267 mark_stack_slot_scratched(env, spi); 5268 stype = ptr_state->stack[spi].slot_type; 5269 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 5270 break; 5271 zeros++; 5272 } 5273 if (zeros == max_off - min_off) { 5274 /* Any access_size read into register is zero extended, 5275 * so the whole register == const_zero. 5276 */ 5277 __mark_reg_const_zero(env, &state->regs[dst_regno]); 5278 } else { 5279 /* have read misc data from the stack */ 5280 mark_reg_unknown(env, state->regs, dst_regno); 5281 } 5282 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5283 } 5284 5285 /* Read the stack at 'off' and put the results into the register indicated by 5286 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 5287 * spilled reg. 5288 * 5289 * 'dst_regno' can be -1, meaning that the read value is not going to a 5290 * register. 5291 * 5292 * The access is assumed to be within the current stack bounds. 5293 */ 5294 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 5295 /* func where src register points to */ 5296 struct bpf_func_state *reg_state, 5297 int off, int size, int dst_regno) 5298 { 5299 struct bpf_verifier_state *vstate = env->cur_state; 5300 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5301 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 5302 struct bpf_reg_state *reg; 5303 u8 *stype, type; 5304 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 5305 5306 stype = reg_state->stack[spi].slot_type; 5307 reg = ®_state->stack[spi].spilled_ptr; 5308 5309 mark_stack_slot_scratched(env, spi); 5310 check_fastcall_stack_contract(env, state, env->insn_idx, off); 5311 5312 if (is_spilled_reg(®_state->stack[spi])) { 5313 u8 spill_size = 1; 5314 5315 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 5316 spill_size++; 5317 5318 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 5319 if (reg->type != SCALAR_VALUE) { 5320 verbose_linfo(env, env->insn_idx, "; "); 5321 verbose(env, "invalid size of register fill\n"); 5322 return -EACCES; 5323 } 5324 5325 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5326 if (dst_regno < 0) 5327 return 0; 5328 5329 if (size <= spill_size && 5330 bpf_stack_narrow_access_ok(off, size, spill_size)) { 5331 /* The earlier check_reg_arg() has decided the 5332 * subreg_def for this insn. Save it first. 5333 */ 5334 s32 subreg_def = state->regs[dst_regno].subreg_def; 5335 5336 copy_register_state(&state->regs[dst_regno], reg); 5337 state->regs[dst_regno].subreg_def = subreg_def; 5338 5339 /* Break the relation on a narrowing fill. 5340 * coerce_reg_to_size will adjust the boundaries. 5341 */ 5342 if (get_reg_width(reg) > size * BITS_PER_BYTE) 5343 state->regs[dst_regno].id = 0; 5344 } else { 5345 int spill_cnt = 0, zero_cnt = 0; 5346 5347 for (i = 0; i < size; i++) { 5348 type = stype[(slot - i) % BPF_REG_SIZE]; 5349 if (type == STACK_SPILL) { 5350 spill_cnt++; 5351 continue; 5352 } 5353 if (type == STACK_MISC) 5354 continue; 5355 if (type == STACK_ZERO) { 5356 zero_cnt++; 5357 continue; 5358 } 5359 if (type == STACK_INVALID && env->allow_uninit_stack) 5360 continue; 5361 verbose(env, "invalid read from stack off %d+%d size %d\n", 5362 off, i, size); 5363 return -EACCES; 5364 } 5365 5366 if (spill_cnt == size && 5367 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 5368 __mark_reg_const_zero(env, &state->regs[dst_regno]); 5369 /* this IS register fill, so keep insn_flags */ 5370 } else if (zero_cnt == size) { 5371 /* similarly to mark_reg_stack_read(), preserve zeroes */ 5372 __mark_reg_const_zero(env, &state->regs[dst_regno]); 5373 insn_flags = 0; /* not restoring original register state */ 5374 } else { 5375 mark_reg_unknown(env, state->regs, dst_regno); 5376 insn_flags = 0; /* not restoring original register state */ 5377 } 5378 } 5379 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5380 } else if (dst_regno >= 0) { 5381 /* restore register state from stack */ 5382 copy_register_state(&state->regs[dst_regno], reg); 5383 /* mark reg as written since spilled pointer state likely 5384 * has its liveness marks cleared by is_state_visited() 5385 * which resets stack/reg liveness for state transitions 5386 */ 5387 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5388 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 5389 /* If dst_regno==-1, the caller is asking us whether 5390 * it is acceptable to use this value as a SCALAR_VALUE 5391 * (e.g. for XADD). 5392 * We must not allow unprivileged callers to do that 5393 * with spilled pointers. 5394 */ 5395 verbose(env, "leaking pointer from stack off %d\n", 5396 off); 5397 return -EACCES; 5398 } 5399 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5400 } else { 5401 for (i = 0; i < size; i++) { 5402 type = stype[(slot - i) % BPF_REG_SIZE]; 5403 if (type == STACK_MISC) 5404 continue; 5405 if (type == STACK_ZERO) 5406 continue; 5407 if (type == STACK_INVALID && env->allow_uninit_stack) 5408 continue; 5409 verbose(env, "invalid read from stack off %d+%d size %d\n", 5410 off, i, size); 5411 return -EACCES; 5412 } 5413 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5414 if (dst_regno >= 0) 5415 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 5416 insn_flags = 0; /* we are not restoring spilled register */ 5417 } 5418 if (insn_flags) 5419 return push_insn_history(env, env->cur_state, insn_flags, 0); 5420 return 0; 5421 } 5422 5423 enum bpf_access_src { 5424 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 5425 ACCESS_HELPER = 2, /* the access is performed by a helper */ 5426 }; 5427 5428 static int check_stack_range_initialized(struct bpf_verifier_env *env, 5429 int regno, int off, int access_size, 5430 bool zero_size_allowed, 5431 enum bpf_access_type type, 5432 struct bpf_call_arg_meta *meta); 5433 5434 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 5435 { 5436 return cur_regs(env) + regno; 5437 } 5438 5439 /* Read the stack at 'ptr_regno + off' and put the result into the register 5440 * 'dst_regno'. 5441 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 5442 * but not its variable offset. 5443 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 5444 * 5445 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 5446 * filling registers (i.e. reads of spilled register cannot be detected when 5447 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 5448 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 5449 * offset; for a fixed offset check_stack_read_fixed_off should be used 5450 * instead. 5451 */ 5452 static int check_stack_read_var_off(struct bpf_verifier_env *env, 5453 int ptr_regno, int off, int size, int dst_regno) 5454 { 5455 /* The state of the source register. */ 5456 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5457 struct bpf_func_state *ptr_state = func(env, reg); 5458 int err; 5459 int min_off, max_off; 5460 5461 /* Note that we pass a NULL meta, so raw access will not be permitted. 5462 */ 5463 err = check_stack_range_initialized(env, ptr_regno, off, size, 5464 false, BPF_READ, NULL); 5465 if (err) 5466 return err; 5467 5468 min_off = reg->smin_value + off; 5469 max_off = reg->smax_value + off; 5470 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 5471 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 5472 return 0; 5473 } 5474 5475 /* check_stack_read dispatches to check_stack_read_fixed_off or 5476 * check_stack_read_var_off. 5477 * 5478 * The caller must ensure that the offset falls within the allocated stack 5479 * bounds. 5480 * 5481 * 'dst_regno' is a register which will receive the value from the stack. It 5482 * can be -1, meaning that the read value is not going to a register. 5483 */ 5484 static int check_stack_read(struct bpf_verifier_env *env, 5485 int ptr_regno, int off, int size, 5486 int dst_regno) 5487 { 5488 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5489 struct bpf_func_state *state = func(env, reg); 5490 int err; 5491 /* Some accesses are only permitted with a static offset. */ 5492 bool var_off = !tnum_is_const(reg->var_off); 5493 5494 /* The offset is required to be static when reads don't go to a 5495 * register, in order to not leak pointers (see 5496 * check_stack_read_fixed_off). 5497 */ 5498 if (dst_regno < 0 && var_off) { 5499 char tn_buf[48]; 5500 5501 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5502 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5503 tn_buf, off, size); 5504 return -EACCES; 5505 } 5506 /* Variable offset is prohibited for unprivileged mode for simplicity 5507 * since it requires corresponding support in Spectre masking for stack 5508 * ALU. See also retrieve_ptr_limit(). The check in 5509 * check_stack_access_for_ptr_arithmetic() called by 5510 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5511 * with variable offsets, therefore no check is required here. Further, 5512 * just checking it here would be insufficient as speculative stack 5513 * writes could still lead to unsafe speculative behaviour. 5514 */ 5515 if (!var_off) { 5516 off += reg->var_off.value; 5517 err = check_stack_read_fixed_off(env, state, off, size, 5518 dst_regno); 5519 } else { 5520 /* Variable offset stack reads need more conservative handling 5521 * than fixed offset ones. Note that dst_regno >= 0 on this 5522 * branch. 5523 */ 5524 err = check_stack_read_var_off(env, ptr_regno, off, size, 5525 dst_regno); 5526 } 5527 return err; 5528 } 5529 5530 5531 /* check_stack_write dispatches to check_stack_write_fixed_off or 5532 * check_stack_write_var_off. 5533 * 5534 * 'ptr_regno' is the register used as a pointer into the stack. 5535 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5536 * 'value_regno' is the register whose value we're writing to the stack. It can 5537 * be -1, meaning that we're not writing from a register. 5538 * 5539 * The caller must ensure that the offset falls within the maximum stack size. 5540 */ 5541 static int check_stack_write(struct bpf_verifier_env *env, 5542 int ptr_regno, int off, int size, 5543 int value_regno, int insn_idx) 5544 { 5545 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5546 struct bpf_func_state *state = func(env, reg); 5547 int err; 5548 5549 if (tnum_is_const(reg->var_off)) { 5550 off += reg->var_off.value; 5551 err = check_stack_write_fixed_off(env, state, off, size, 5552 value_regno, insn_idx); 5553 } else { 5554 /* Variable offset stack reads need more conservative handling 5555 * than fixed offset ones. 5556 */ 5557 err = check_stack_write_var_off(env, state, 5558 ptr_regno, off, size, 5559 value_regno, insn_idx); 5560 } 5561 return err; 5562 } 5563 5564 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5565 int off, int size, enum bpf_access_type type) 5566 { 5567 struct bpf_reg_state *regs = cur_regs(env); 5568 struct bpf_map *map = regs[regno].map_ptr; 5569 u32 cap = bpf_map_flags_to_cap(map); 5570 5571 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5572 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5573 map->value_size, off, size); 5574 return -EACCES; 5575 } 5576 5577 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5578 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5579 map->value_size, off, size); 5580 return -EACCES; 5581 } 5582 5583 return 0; 5584 } 5585 5586 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5587 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5588 int off, int size, u32 mem_size, 5589 bool zero_size_allowed) 5590 { 5591 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5592 struct bpf_reg_state *reg; 5593 5594 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5595 return 0; 5596 5597 reg = &cur_regs(env)[regno]; 5598 switch (reg->type) { 5599 case PTR_TO_MAP_KEY: 5600 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5601 mem_size, off, size); 5602 break; 5603 case PTR_TO_MAP_VALUE: 5604 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5605 mem_size, off, size); 5606 break; 5607 case PTR_TO_PACKET: 5608 case PTR_TO_PACKET_META: 5609 case PTR_TO_PACKET_END: 5610 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5611 off, size, regno, reg->id, off, mem_size); 5612 break; 5613 case PTR_TO_MEM: 5614 default: 5615 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5616 mem_size, off, size); 5617 } 5618 5619 return -EACCES; 5620 } 5621 5622 /* check read/write into a memory region with possible variable offset */ 5623 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5624 int off, int size, u32 mem_size, 5625 bool zero_size_allowed) 5626 { 5627 struct bpf_verifier_state *vstate = env->cur_state; 5628 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5629 struct bpf_reg_state *reg = &state->regs[regno]; 5630 int err; 5631 5632 /* We may have adjusted the register pointing to memory region, so we 5633 * need to try adding each of min_value and max_value to off 5634 * to make sure our theoretical access will be safe. 5635 * 5636 * The minimum value is only important with signed 5637 * comparisons where we can't assume the floor of a 5638 * value is 0. If we are using signed variables for our 5639 * index'es we need to make sure that whatever we use 5640 * will have a set floor within our range. 5641 */ 5642 if (reg->smin_value < 0 && 5643 (reg->smin_value == S64_MIN || 5644 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5645 reg->smin_value + off < 0)) { 5646 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5647 regno); 5648 return -EACCES; 5649 } 5650 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5651 mem_size, zero_size_allowed); 5652 if (err) { 5653 verbose(env, "R%d min value is outside of the allowed memory range\n", 5654 regno); 5655 return err; 5656 } 5657 5658 /* If we haven't set a max value then we need to bail since we can't be 5659 * sure we won't do bad things. 5660 * If reg->umax_value + off could overflow, treat that as unbounded too. 5661 */ 5662 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5663 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5664 regno); 5665 return -EACCES; 5666 } 5667 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5668 mem_size, zero_size_allowed); 5669 if (err) { 5670 verbose(env, "R%d max value is outside of the allowed memory range\n", 5671 regno); 5672 return err; 5673 } 5674 5675 return 0; 5676 } 5677 5678 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5679 const struct bpf_reg_state *reg, int regno, 5680 bool fixed_off_ok) 5681 { 5682 /* Access to this pointer-typed register or passing it to a helper 5683 * is only allowed in its original, unmodified form. 5684 */ 5685 5686 if (reg->off < 0) { 5687 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5688 reg_type_str(env, reg->type), regno, reg->off); 5689 return -EACCES; 5690 } 5691 5692 if (!fixed_off_ok && reg->off) { 5693 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5694 reg_type_str(env, reg->type), regno, reg->off); 5695 return -EACCES; 5696 } 5697 5698 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5699 char tn_buf[48]; 5700 5701 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5702 verbose(env, "variable %s access var_off=%s disallowed\n", 5703 reg_type_str(env, reg->type), tn_buf); 5704 return -EACCES; 5705 } 5706 5707 return 0; 5708 } 5709 5710 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5711 const struct bpf_reg_state *reg, int regno) 5712 { 5713 return __check_ptr_off_reg(env, reg, regno, false); 5714 } 5715 5716 static int map_kptr_match_type(struct bpf_verifier_env *env, 5717 struct btf_field *kptr_field, 5718 struct bpf_reg_state *reg, u32 regno) 5719 { 5720 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5721 int perm_flags; 5722 const char *reg_name = ""; 5723 5724 if (btf_is_kernel(reg->btf)) { 5725 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5726 5727 /* Only unreferenced case accepts untrusted pointers */ 5728 if (kptr_field->type == BPF_KPTR_UNREF) 5729 perm_flags |= PTR_UNTRUSTED; 5730 } else { 5731 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5732 if (kptr_field->type == BPF_KPTR_PERCPU) 5733 perm_flags |= MEM_PERCPU; 5734 } 5735 5736 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5737 goto bad_type; 5738 5739 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5740 reg_name = btf_type_name(reg->btf, reg->btf_id); 5741 5742 /* For ref_ptr case, release function check should ensure we get one 5743 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5744 * normal store of unreferenced kptr, we must ensure var_off is zero. 5745 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5746 * reg->off and reg->ref_obj_id are not needed here. 5747 */ 5748 if (__check_ptr_off_reg(env, reg, regno, true)) 5749 return -EACCES; 5750 5751 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5752 * we also need to take into account the reg->off. 5753 * 5754 * We want to support cases like: 5755 * 5756 * struct foo { 5757 * struct bar br; 5758 * struct baz bz; 5759 * }; 5760 * 5761 * struct foo *v; 5762 * v = func(); // PTR_TO_BTF_ID 5763 * val->foo = v; // reg->off is zero, btf and btf_id match type 5764 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5765 * // first member type of struct after comparison fails 5766 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5767 * // to match type 5768 * 5769 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5770 * is zero. We must also ensure that btf_struct_ids_match does not walk 5771 * the struct to match type against first member of struct, i.e. reject 5772 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5773 * strict mode to true for type match. 5774 */ 5775 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5776 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5777 kptr_field->type != BPF_KPTR_UNREF)) 5778 goto bad_type; 5779 return 0; 5780 bad_type: 5781 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5782 reg_type_str(env, reg->type), reg_name); 5783 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5784 if (kptr_field->type == BPF_KPTR_UNREF) 5785 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5786 targ_name); 5787 else 5788 verbose(env, "\n"); 5789 return -EINVAL; 5790 } 5791 5792 static bool in_sleepable(struct bpf_verifier_env *env) 5793 { 5794 return env->prog->sleepable || 5795 (env->cur_state && env->cur_state->in_sleepable); 5796 } 5797 5798 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5799 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5800 */ 5801 static bool in_rcu_cs(struct bpf_verifier_env *env) 5802 { 5803 return env->cur_state->active_rcu_lock || 5804 env->cur_state->active_locks || 5805 !in_sleepable(env); 5806 } 5807 5808 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5809 BTF_SET_START(rcu_protected_types) 5810 #ifdef CONFIG_NET 5811 BTF_ID(struct, prog_test_ref_kfunc) 5812 #endif 5813 #ifdef CONFIG_CGROUPS 5814 BTF_ID(struct, cgroup) 5815 #endif 5816 #ifdef CONFIG_BPF_JIT 5817 BTF_ID(struct, bpf_cpumask) 5818 #endif 5819 BTF_ID(struct, task_struct) 5820 #ifdef CONFIG_CRYPTO 5821 BTF_ID(struct, bpf_crypto_ctx) 5822 #endif 5823 BTF_SET_END(rcu_protected_types) 5824 5825 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5826 { 5827 if (!btf_is_kernel(btf)) 5828 return true; 5829 return btf_id_set_contains(&rcu_protected_types, btf_id); 5830 } 5831 5832 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5833 { 5834 struct btf_struct_meta *meta; 5835 5836 if (btf_is_kernel(kptr_field->kptr.btf)) 5837 return NULL; 5838 5839 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5840 kptr_field->kptr.btf_id); 5841 5842 return meta ? meta->record : NULL; 5843 } 5844 5845 static bool rcu_safe_kptr(const struct btf_field *field) 5846 { 5847 const struct btf_field_kptr *kptr = &field->kptr; 5848 5849 return field->type == BPF_KPTR_PERCPU || 5850 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5851 } 5852 5853 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5854 { 5855 struct btf_record *rec; 5856 u32 ret; 5857 5858 ret = PTR_MAYBE_NULL; 5859 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5860 ret |= MEM_RCU; 5861 if (kptr_field->type == BPF_KPTR_PERCPU) 5862 ret |= MEM_PERCPU; 5863 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5864 ret |= MEM_ALLOC; 5865 5866 rec = kptr_pointee_btf_record(kptr_field); 5867 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5868 ret |= NON_OWN_REF; 5869 } else { 5870 ret |= PTR_UNTRUSTED; 5871 } 5872 5873 return ret; 5874 } 5875 5876 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 5877 struct btf_field *field) 5878 { 5879 struct bpf_reg_state *reg; 5880 const struct btf_type *t; 5881 5882 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 5883 mark_reg_known_zero(env, cur_regs(env), regno); 5884 reg = reg_state(env, regno); 5885 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 5886 reg->mem_size = t->size; 5887 reg->id = ++env->id_gen; 5888 5889 return 0; 5890 } 5891 5892 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5893 int value_regno, int insn_idx, 5894 struct btf_field *kptr_field) 5895 { 5896 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5897 int class = BPF_CLASS(insn->code); 5898 struct bpf_reg_state *val_reg; 5899 5900 /* Things we already checked for in check_map_access and caller: 5901 * - Reject cases where variable offset may touch kptr 5902 * - size of access (must be BPF_DW) 5903 * - tnum_is_const(reg->var_off) 5904 * - kptr_field->offset == off + reg->var_off.value 5905 */ 5906 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5907 if (BPF_MODE(insn->code) != BPF_MEM) { 5908 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5909 return -EACCES; 5910 } 5911 5912 /* We only allow loading referenced kptr, since it will be marked as 5913 * untrusted, similar to unreferenced kptr. 5914 */ 5915 if (class != BPF_LDX && 5916 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5917 verbose(env, "store to referenced kptr disallowed\n"); 5918 return -EACCES; 5919 } 5920 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 5921 verbose(env, "store to uptr disallowed\n"); 5922 return -EACCES; 5923 } 5924 5925 if (class == BPF_LDX) { 5926 if (kptr_field->type == BPF_UPTR) 5927 return mark_uptr_ld_reg(env, value_regno, kptr_field); 5928 5929 /* We can simply mark the value_regno receiving the pointer 5930 * value from map as PTR_TO_BTF_ID, with the correct type. 5931 */ 5932 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5933 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5934 } else if (class == BPF_STX) { 5935 val_reg = reg_state(env, value_regno); 5936 if (!register_is_null(val_reg) && 5937 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5938 return -EACCES; 5939 } else if (class == BPF_ST) { 5940 if (insn->imm) { 5941 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5942 kptr_field->offset); 5943 return -EACCES; 5944 } 5945 } else { 5946 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5947 return -EACCES; 5948 } 5949 return 0; 5950 } 5951 5952 /* check read/write into a map element with possible variable offset */ 5953 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5954 int off, int size, bool zero_size_allowed, 5955 enum bpf_access_src src) 5956 { 5957 struct bpf_verifier_state *vstate = env->cur_state; 5958 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5959 struct bpf_reg_state *reg = &state->regs[regno]; 5960 struct bpf_map *map = reg->map_ptr; 5961 struct btf_record *rec; 5962 int err, i; 5963 5964 err = check_mem_region_access(env, regno, off, size, map->value_size, 5965 zero_size_allowed); 5966 if (err) 5967 return err; 5968 5969 if (IS_ERR_OR_NULL(map->record)) 5970 return 0; 5971 rec = map->record; 5972 for (i = 0; i < rec->cnt; i++) { 5973 struct btf_field *field = &rec->fields[i]; 5974 u32 p = field->offset; 5975 5976 /* If any part of a field can be touched by load/store, reject 5977 * this program. To check that [x1, x2) overlaps with [y1, y2), 5978 * it is sufficient to check x1 < y2 && y1 < x2. 5979 */ 5980 if (reg->smin_value + off < p + field->size && 5981 p < reg->umax_value + off + size) { 5982 switch (field->type) { 5983 case BPF_KPTR_UNREF: 5984 case BPF_KPTR_REF: 5985 case BPF_KPTR_PERCPU: 5986 case BPF_UPTR: 5987 if (src != ACCESS_DIRECT) { 5988 verbose(env, "%s cannot be accessed indirectly by helper\n", 5989 btf_field_type_name(field->type)); 5990 return -EACCES; 5991 } 5992 if (!tnum_is_const(reg->var_off)) { 5993 verbose(env, "%s access cannot have variable offset\n", 5994 btf_field_type_name(field->type)); 5995 return -EACCES; 5996 } 5997 if (p != off + reg->var_off.value) { 5998 verbose(env, "%s access misaligned expected=%u off=%llu\n", 5999 btf_field_type_name(field->type), 6000 p, off + reg->var_off.value); 6001 return -EACCES; 6002 } 6003 if (size != bpf_size_to_bytes(BPF_DW)) { 6004 verbose(env, "%s access size must be BPF_DW\n", 6005 btf_field_type_name(field->type)); 6006 return -EACCES; 6007 } 6008 break; 6009 default: 6010 verbose(env, "%s cannot be accessed directly by load/store\n", 6011 btf_field_type_name(field->type)); 6012 return -EACCES; 6013 } 6014 } 6015 } 6016 return 0; 6017 } 6018 6019 #define MAX_PACKET_OFF 0xffff 6020 6021 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 6022 const struct bpf_call_arg_meta *meta, 6023 enum bpf_access_type t) 6024 { 6025 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 6026 6027 switch (prog_type) { 6028 /* Program types only with direct read access go here! */ 6029 case BPF_PROG_TYPE_LWT_IN: 6030 case BPF_PROG_TYPE_LWT_OUT: 6031 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 6032 case BPF_PROG_TYPE_SK_REUSEPORT: 6033 case BPF_PROG_TYPE_FLOW_DISSECTOR: 6034 case BPF_PROG_TYPE_CGROUP_SKB: 6035 if (t == BPF_WRITE) 6036 return false; 6037 fallthrough; 6038 6039 /* Program types with direct read + write access go here! */ 6040 case BPF_PROG_TYPE_SCHED_CLS: 6041 case BPF_PROG_TYPE_SCHED_ACT: 6042 case BPF_PROG_TYPE_XDP: 6043 case BPF_PROG_TYPE_LWT_XMIT: 6044 case BPF_PROG_TYPE_SK_SKB: 6045 case BPF_PROG_TYPE_SK_MSG: 6046 if (meta) 6047 return meta->pkt_access; 6048 6049 env->seen_direct_write = true; 6050 return true; 6051 6052 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 6053 if (t == BPF_WRITE) 6054 env->seen_direct_write = true; 6055 6056 return true; 6057 6058 default: 6059 return false; 6060 } 6061 } 6062 6063 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 6064 int size, bool zero_size_allowed) 6065 { 6066 struct bpf_reg_state *regs = cur_regs(env); 6067 struct bpf_reg_state *reg = ®s[regno]; 6068 int err; 6069 6070 /* We may have added a variable offset to the packet pointer; but any 6071 * reg->range we have comes after that. We are only checking the fixed 6072 * offset. 6073 */ 6074 6075 /* We don't allow negative numbers, because we aren't tracking enough 6076 * detail to prove they're safe. 6077 */ 6078 if (reg->smin_value < 0) { 6079 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 6080 regno); 6081 return -EACCES; 6082 } 6083 6084 err = reg->range < 0 ? -EINVAL : 6085 __check_mem_access(env, regno, off, size, reg->range, 6086 zero_size_allowed); 6087 if (err) { 6088 verbose(env, "R%d offset is outside of the packet\n", regno); 6089 return err; 6090 } 6091 6092 /* __check_mem_access has made sure "off + size - 1" is within u16. 6093 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 6094 * otherwise find_good_pkt_pointers would have refused to set range info 6095 * that __check_mem_access would have rejected this pkt access. 6096 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 6097 */ 6098 env->prog->aux->max_pkt_offset = 6099 max_t(u32, env->prog->aux->max_pkt_offset, 6100 off + reg->umax_value + size - 1); 6101 6102 return err; 6103 } 6104 6105 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 6106 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 6107 enum bpf_access_type t, struct bpf_insn_access_aux *info) 6108 { 6109 if (env->ops->is_valid_access && 6110 env->ops->is_valid_access(off, size, t, env->prog, info)) { 6111 /* A non zero info.ctx_field_size indicates that this field is a 6112 * candidate for later verifier transformation to load the whole 6113 * field and then apply a mask when accessed with a narrower 6114 * access than actual ctx access size. A zero info.ctx_field_size 6115 * will only allow for whole field access and rejects any other 6116 * type of narrower access. 6117 */ 6118 if (base_type(info->reg_type) == PTR_TO_BTF_ID) { 6119 if (info->ref_obj_id && 6120 !find_reference_state(env->cur_state, info->ref_obj_id)) { 6121 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n", 6122 off); 6123 return -EACCES; 6124 } 6125 } else { 6126 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size; 6127 } 6128 /* remember the offset of last byte accessed in ctx */ 6129 if (env->prog->aux->max_ctx_offset < off + size) 6130 env->prog->aux->max_ctx_offset = off + size; 6131 return 0; 6132 } 6133 6134 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 6135 return -EACCES; 6136 } 6137 6138 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 6139 int size) 6140 { 6141 if (size < 0 || off < 0 || 6142 (u64)off + size > sizeof(struct bpf_flow_keys)) { 6143 verbose(env, "invalid access to flow keys off=%d size=%d\n", 6144 off, size); 6145 return -EACCES; 6146 } 6147 return 0; 6148 } 6149 6150 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 6151 u32 regno, int off, int size, 6152 enum bpf_access_type t) 6153 { 6154 struct bpf_reg_state *regs = cur_regs(env); 6155 struct bpf_reg_state *reg = ®s[regno]; 6156 struct bpf_insn_access_aux info = {}; 6157 bool valid; 6158 6159 if (reg->smin_value < 0) { 6160 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 6161 regno); 6162 return -EACCES; 6163 } 6164 6165 switch (reg->type) { 6166 case PTR_TO_SOCK_COMMON: 6167 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 6168 break; 6169 case PTR_TO_SOCKET: 6170 valid = bpf_sock_is_valid_access(off, size, t, &info); 6171 break; 6172 case PTR_TO_TCP_SOCK: 6173 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 6174 break; 6175 case PTR_TO_XDP_SOCK: 6176 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 6177 break; 6178 default: 6179 valid = false; 6180 } 6181 6182 6183 if (valid) { 6184 env->insn_aux_data[insn_idx].ctx_field_size = 6185 info.ctx_field_size; 6186 return 0; 6187 } 6188 6189 verbose(env, "R%d invalid %s access off=%d size=%d\n", 6190 regno, reg_type_str(env, reg->type), off, size); 6191 6192 return -EACCES; 6193 } 6194 6195 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 6196 { 6197 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 6198 } 6199 6200 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 6201 { 6202 const struct bpf_reg_state *reg = reg_state(env, regno); 6203 6204 return reg->type == PTR_TO_CTX; 6205 } 6206 6207 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 6208 { 6209 const struct bpf_reg_state *reg = reg_state(env, regno); 6210 6211 return type_is_sk_pointer(reg->type); 6212 } 6213 6214 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 6215 { 6216 const struct bpf_reg_state *reg = reg_state(env, regno); 6217 6218 return type_is_pkt_pointer(reg->type); 6219 } 6220 6221 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 6222 { 6223 const struct bpf_reg_state *reg = reg_state(env, regno); 6224 6225 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 6226 return reg->type == PTR_TO_FLOW_KEYS; 6227 } 6228 6229 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 6230 { 6231 const struct bpf_reg_state *reg = reg_state(env, regno); 6232 6233 return reg->type == PTR_TO_ARENA; 6234 } 6235 6236 /* Return false if @regno contains a pointer whose type isn't supported for 6237 * atomic instruction @insn. 6238 */ 6239 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno, 6240 struct bpf_insn *insn) 6241 { 6242 if (is_ctx_reg(env, regno)) 6243 return false; 6244 if (is_pkt_reg(env, regno)) 6245 return false; 6246 if (is_flow_key_reg(env, regno)) 6247 return false; 6248 if (is_sk_reg(env, regno)) 6249 return false; 6250 if (is_arena_reg(env, regno)) 6251 return bpf_jit_supports_insn(insn, true); 6252 6253 return true; 6254 } 6255 6256 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 6257 #ifdef CONFIG_NET 6258 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 6259 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 6260 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 6261 #endif 6262 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 6263 }; 6264 6265 static bool is_trusted_reg(const struct bpf_reg_state *reg) 6266 { 6267 /* A referenced register is always trusted. */ 6268 if (reg->ref_obj_id) 6269 return true; 6270 6271 /* Types listed in the reg2btf_ids are always trusted */ 6272 if (reg2btf_ids[base_type(reg->type)] && 6273 !bpf_type_has_unsafe_modifiers(reg->type)) 6274 return true; 6275 6276 /* If a register is not referenced, it is trusted if it has the 6277 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 6278 * other type modifiers may be safe, but we elect to take an opt-in 6279 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 6280 * not. 6281 * 6282 * Eventually, we should make PTR_TRUSTED the single source of truth 6283 * for whether a register is trusted. 6284 */ 6285 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 6286 !bpf_type_has_unsafe_modifiers(reg->type); 6287 } 6288 6289 static bool is_rcu_reg(const struct bpf_reg_state *reg) 6290 { 6291 return reg->type & MEM_RCU; 6292 } 6293 6294 static void clear_trusted_flags(enum bpf_type_flag *flag) 6295 { 6296 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 6297 } 6298 6299 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 6300 const struct bpf_reg_state *reg, 6301 int off, int size, bool strict) 6302 { 6303 struct tnum reg_off; 6304 int ip_align; 6305 6306 /* Byte size accesses are always allowed. */ 6307 if (!strict || size == 1) 6308 return 0; 6309 6310 /* For platforms that do not have a Kconfig enabling 6311 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 6312 * NET_IP_ALIGN is universally set to '2'. And on platforms 6313 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 6314 * to this code only in strict mode where we want to emulate 6315 * the NET_IP_ALIGN==2 checking. Therefore use an 6316 * unconditional IP align value of '2'. 6317 */ 6318 ip_align = 2; 6319 6320 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 6321 if (!tnum_is_aligned(reg_off, size)) { 6322 char tn_buf[48]; 6323 6324 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6325 verbose(env, 6326 "misaligned packet access off %d+%s+%d+%d size %d\n", 6327 ip_align, tn_buf, reg->off, off, size); 6328 return -EACCES; 6329 } 6330 6331 return 0; 6332 } 6333 6334 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 6335 const struct bpf_reg_state *reg, 6336 const char *pointer_desc, 6337 int off, int size, bool strict) 6338 { 6339 struct tnum reg_off; 6340 6341 /* Byte size accesses are always allowed. */ 6342 if (!strict || size == 1) 6343 return 0; 6344 6345 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 6346 if (!tnum_is_aligned(reg_off, size)) { 6347 char tn_buf[48]; 6348 6349 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6350 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 6351 pointer_desc, tn_buf, reg->off, off, size); 6352 return -EACCES; 6353 } 6354 6355 return 0; 6356 } 6357 6358 static int check_ptr_alignment(struct bpf_verifier_env *env, 6359 const struct bpf_reg_state *reg, int off, 6360 int size, bool strict_alignment_once) 6361 { 6362 bool strict = env->strict_alignment || strict_alignment_once; 6363 const char *pointer_desc = ""; 6364 6365 switch (reg->type) { 6366 case PTR_TO_PACKET: 6367 case PTR_TO_PACKET_META: 6368 /* Special case, because of NET_IP_ALIGN. Given metadata sits 6369 * right in front, treat it the very same way. 6370 */ 6371 return check_pkt_ptr_alignment(env, reg, off, size, strict); 6372 case PTR_TO_FLOW_KEYS: 6373 pointer_desc = "flow keys "; 6374 break; 6375 case PTR_TO_MAP_KEY: 6376 pointer_desc = "key "; 6377 break; 6378 case PTR_TO_MAP_VALUE: 6379 pointer_desc = "value "; 6380 break; 6381 case PTR_TO_CTX: 6382 pointer_desc = "context "; 6383 break; 6384 case PTR_TO_STACK: 6385 pointer_desc = "stack "; 6386 /* The stack spill tracking logic in check_stack_write_fixed_off() 6387 * and check_stack_read_fixed_off() relies on stack accesses being 6388 * aligned. 6389 */ 6390 strict = true; 6391 break; 6392 case PTR_TO_SOCKET: 6393 pointer_desc = "sock "; 6394 break; 6395 case PTR_TO_SOCK_COMMON: 6396 pointer_desc = "sock_common "; 6397 break; 6398 case PTR_TO_TCP_SOCK: 6399 pointer_desc = "tcp_sock "; 6400 break; 6401 case PTR_TO_XDP_SOCK: 6402 pointer_desc = "xdp_sock "; 6403 break; 6404 case PTR_TO_ARENA: 6405 return 0; 6406 default: 6407 break; 6408 } 6409 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 6410 strict); 6411 } 6412 6413 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 6414 { 6415 if (!bpf_jit_supports_private_stack()) 6416 return NO_PRIV_STACK; 6417 6418 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 6419 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 6420 * explicitly. 6421 */ 6422 switch (prog->type) { 6423 case BPF_PROG_TYPE_KPROBE: 6424 case BPF_PROG_TYPE_TRACEPOINT: 6425 case BPF_PROG_TYPE_PERF_EVENT: 6426 case BPF_PROG_TYPE_RAW_TRACEPOINT: 6427 return PRIV_STACK_ADAPTIVE; 6428 case BPF_PROG_TYPE_TRACING: 6429 case BPF_PROG_TYPE_LSM: 6430 case BPF_PROG_TYPE_STRUCT_OPS: 6431 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 6432 return PRIV_STACK_ADAPTIVE; 6433 fallthrough; 6434 default: 6435 break; 6436 } 6437 6438 return NO_PRIV_STACK; 6439 } 6440 6441 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 6442 { 6443 if (env->prog->jit_requested) 6444 return round_up(stack_depth, 16); 6445 6446 /* round up to 32-bytes, since this is granularity 6447 * of interpreter stack size 6448 */ 6449 return round_up(max_t(u32, stack_depth, 1), 32); 6450 } 6451 6452 /* starting from main bpf function walk all instructions of the function 6453 * and recursively walk all callees that given function can call. 6454 * Ignore jump and exit insns. 6455 * Since recursion is prevented by check_cfg() this algorithm 6456 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 6457 */ 6458 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 6459 bool priv_stack_supported) 6460 { 6461 struct bpf_subprog_info *subprog = env->subprog_info; 6462 struct bpf_insn *insn = env->prog->insnsi; 6463 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 6464 bool tail_call_reachable = false; 6465 int ret_insn[MAX_CALL_FRAMES]; 6466 int ret_prog[MAX_CALL_FRAMES]; 6467 int j; 6468 6469 i = subprog[idx].start; 6470 if (!priv_stack_supported) 6471 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 6472 process_func: 6473 /* protect against potential stack overflow that might happen when 6474 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 6475 * depth for such case down to 256 so that the worst case scenario 6476 * would result in 8k stack size (32 which is tailcall limit * 256 = 6477 * 8k). 6478 * 6479 * To get the idea what might happen, see an example: 6480 * func1 -> sub rsp, 128 6481 * subfunc1 -> sub rsp, 256 6482 * tailcall1 -> add rsp, 256 6483 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 6484 * subfunc2 -> sub rsp, 64 6485 * subfunc22 -> sub rsp, 128 6486 * tailcall2 -> add rsp, 128 6487 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 6488 * 6489 * tailcall will unwind the current stack frame but it will not get rid 6490 * of caller's stack as shown on the example above. 6491 */ 6492 if (idx && subprog[idx].has_tail_call && depth >= 256) { 6493 verbose(env, 6494 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 6495 depth); 6496 return -EACCES; 6497 } 6498 6499 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 6500 if (priv_stack_supported) { 6501 /* Request private stack support only if the subprog stack 6502 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 6503 * avoid jit penalty if the stack usage is small. 6504 */ 6505 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 6506 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 6507 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 6508 } 6509 6510 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 6511 if (subprog_depth > MAX_BPF_STACK) { 6512 verbose(env, "stack size of subprog %d is %d. Too large\n", 6513 idx, subprog_depth); 6514 return -EACCES; 6515 } 6516 } else { 6517 depth += subprog_depth; 6518 if (depth > MAX_BPF_STACK) { 6519 verbose(env, "combined stack size of %d calls is %d. Too large\n", 6520 frame + 1, depth); 6521 return -EACCES; 6522 } 6523 } 6524 continue_func: 6525 subprog_end = subprog[idx + 1].start; 6526 for (; i < subprog_end; i++) { 6527 int next_insn, sidx; 6528 6529 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 6530 bool err = false; 6531 6532 if (!is_bpf_throw_kfunc(insn + i)) 6533 continue; 6534 if (subprog[idx].is_cb) 6535 err = true; 6536 for (int c = 0; c < frame && !err; c++) { 6537 if (subprog[ret_prog[c]].is_cb) { 6538 err = true; 6539 break; 6540 } 6541 } 6542 if (!err) 6543 continue; 6544 verbose(env, 6545 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 6546 i, idx); 6547 return -EINVAL; 6548 } 6549 6550 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 6551 continue; 6552 /* remember insn and function to return to */ 6553 ret_insn[frame] = i + 1; 6554 ret_prog[frame] = idx; 6555 6556 /* find the callee */ 6557 next_insn = i + insn[i].imm + 1; 6558 sidx = find_subprog(env, next_insn); 6559 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn)) 6560 return -EFAULT; 6561 if (subprog[sidx].is_async_cb) { 6562 if (subprog[sidx].has_tail_call) { 6563 verifier_bug(env, "subprog has tail_call and async cb"); 6564 return -EFAULT; 6565 } 6566 /* async callbacks don't increase bpf prog stack size unless called directly */ 6567 if (!bpf_pseudo_call(insn + i)) 6568 continue; 6569 if (subprog[sidx].is_exception_cb) { 6570 verbose(env, "insn %d cannot call exception cb directly", i); 6571 return -EINVAL; 6572 } 6573 } 6574 i = next_insn; 6575 idx = sidx; 6576 if (!priv_stack_supported) 6577 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 6578 6579 if (subprog[idx].has_tail_call) 6580 tail_call_reachable = true; 6581 6582 frame++; 6583 if (frame >= MAX_CALL_FRAMES) { 6584 verbose(env, "the call stack of %d frames is too deep !\n", 6585 frame); 6586 return -E2BIG; 6587 } 6588 goto process_func; 6589 } 6590 /* if tail call got detected across bpf2bpf calls then mark each of the 6591 * currently present subprog frames as tail call reachable subprogs; 6592 * this info will be utilized by JIT so that we will be preserving the 6593 * tail call counter throughout bpf2bpf calls combined with tailcalls 6594 */ 6595 if (tail_call_reachable) 6596 for (j = 0; j < frame; j++) { 6597 if (subprog[ret_prog[j]].is_exception_cb) { 6598 verbose(env, "cannot tail call within exception cb\n"); 6599 return -EINVAL; 6600 } 6601 subprog[ret_prog[j]].tail_call_reachable = true; 6602 } 6603 if (subprog[0].tail_call_reachable) 6604 env->prog->aux->tail_call_reachable = true; 6605 6606 /* end of for() loop means the last insn of the 'subprog' 6607 * was reached. Doesn't matter whether it was JA or EXIT 6608 */ 6609 if (frame == 0) 6610 return 0; 6611 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 6612 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 6613 frame--; 6614 i = ret_insn[frame]; 6615 idx = ret_prog[frame]; 6616 goto continue_func; 6617 } 6618 6619 static int check_max_stack_depth(struct bpf_verifier_env *env) 6620 { 6621 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 6622 struct bpf_subprog_info *si = env->subprog_info; 6623 bool priv_stack_supported; 6624 int ret; 6625 6626 for (int i = 0; i < env->subprog_cnt; i++) { 6627 if (si[i].has_tail_call) { 6628 priv_stack_mode = NO_PRIV_STACK; 6629 break; 6630 } 6631 } 6632 6633 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 6634 priv_stack_mode = bpf_enable_priv_stack(env->prog); 6635 6636 /* All async_cb subprogs use normal kernel stack. If a particular 6637 * subprog appears in both main prog and async_cb subtree, that 6638 * subprog will use normal kernel stack to avoid potential nesting. 6639 * The reverse subprog traversal ensures when main prog subtree is 6640 * checked, the subprogs appearing in async_cb subtrees are already 6641 * marked as using normal kernel stack, so stack size checking can 6642 * be done properly. 6643 */ 6644 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 6645 if (!i || si[i].is_async_cb) { 6646 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 6647 ret = check_max_stack_depth_subprog(env, i, priv_stack_supported); 6648 if (ret < 0) 6649 return ret; 6650 } 6651 } 6652 6653 for (int i = 0; i < env->subprog_cnt; i++) { 6654 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 6655 env->prog->aux->jits_use_priv_stack = true; 6656 break; 6657 } 6658 } 6659 6660 return 0; 6661 } 6662 6663 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6664 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6665 const struct bpf_insn *insn, int idx) 6666 { 6667 int start = idx + insn->imm + 1, subprog; 6668 6669 subprog = find_subprog(env, start); 6670 if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start)) 6671 return -EFAULT; 6672 return env->subprog_info[subprog].stack_depth; 6673 } 6674 #endif 6675 6676 static int __check_buffer_access(struct bpf_verifier_env *env, 6677 const char *buf_info, 6678 const struct bpf_reg_state *reg, 6679 int regno, int off, int size) 6680 { 6681 if (off < 0) { 6682 verbose(env, 6683 "R%d invalid %s buffer access: off=%d, size=%d\n", 6684 regno, buf_info, off, size); 6685 return -EACCES; 6686 } 6687 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6688 char tn_buf[48]; 6689 6690 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6691 verbose(env, 6692 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6693 regno, off, tn_buf); 6694 return -EACCES; 6695 } 6696 6697 return 0; 6698 } 6699 6700 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6701 const struct bpf_reg_state *reg, 6702 int regno, int off, int size) 6703 { 6704 int err; 6705 6706 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6707 if (err) 6708 return err; 6709 6710 if (off + size > env->prog->aux->max_tp_access) 6711 env->prog->aux->max_tp_access = off + size; 6712 6713 return 0; 6714 } 6715 6716 static int check_buffer_access(struct bpf_verifier_env *env, 6717 const struct bpf_reg_state *reg, 6718 int regno, int off, int size, 6719 bool zero_size_allowed, 6720 u32 *max_access) 6721 { 6722 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6723 int err; 6724 6725 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6726 if (err) 6727 return err; 6728 6729 if (off + size > *max_access) 6730 *max_access = off + size; 6731 6732 return 0; 6733 } 6734 6735 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6736 static void zext_32_to_64(struct bpf_reg_state *reg) 6737 { 6738 reg->var_off = tnum_subreg(reg->var_off); 6739 __reg_assign_32_into_64(reg); 6740 } 6741 6742 /* truncate register to smaller size (in bytes) 6743 * must be called with size < BPF_REG_SIZE 6744 */ 6745 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6746 { 6747 u64 mask; 6748 6749 /* clear high bits in bit representation */ 6750 reg->var_off = tnum_cast(reg->var_off, size); 6751 6752 /* fix arithmetic bounds */ 6753 mask = ((u64)1 << (size * 8)) - 1; 6754 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6755 reg->umin_value &= mask; 6756 reg->umax_value &= mask; 6757 } else { 6758 reg->umin_value = 0; 6759 reg->umax_value = mask; 6760 } 6761 reg->smin_value = reg->umin_value; 6762 reg->smax_value = reg->umax_value; 6763 6764 /* If size is smaller than 32bit register the 32bit register 6765 * values are also truncated so we push 64-bit bounds into 6766 * 32-bit bounds. Above were truncated < 32-bits already. 6767 */ 6768 if (size < 4) 6769 __mark_reg32_unbounded(reg); 6770 6771 reg_bounds_sync(reg); 6772 } 6773 6774 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6775 { 6776 if (size == 1) { 6777 reg->smin_value = reg->s32_min_value = S8_MIN; 6778 reg->smax_value = reg->s32_max_value = S8_MAX; 6779 } else if (size == 2) { 6780 reg->smin_value = reg->s32_min_value = S16_MIN; 6781 reg->smax_value = reg->s32_max_value = S16_MAX; 6782 } else { 6783 /* size == 4 */ 6784 reg->smin_value = reg->s32_min_value = S32_MIN; 6785 reg->smax_value = reg->s32_max_value = S32_MAX; 6786 } 6787 reg->umin_value = reg->u32_min_value = 0; 6788 reg->umax_value = U64_MAX; 6789 reg->u32_max_value = U32_MAX; 6790 reg->var_off = tnum_unknown; 6791 } 6792 6793 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6794 { 6795 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6796 u64 top_smax_value, top_smin_value; 6797 u64 num_bits = size * 8; 6798 6799 if (tnum_is_const(reg->var_off)) { 6800 u64_cval = reg->var_off.value; 6801 if (size == 1) 6802 reg->var_off = tnum_const((s8)u64_cval); 6803 else if (size == 2) 6804 reg->var_off = tnum_const((s16)u64_cval); 6805 else 6806 /* size == 4 */ 6807 reg->var_off = tnum_const((s32)u64_cval); 6808 6809 u64_cval = reg->var_off.value; 6810 reg->smax_value = reg->smin_value = u64_cval; 6811 reg->umax_value = reg->umin_value = u64_cval; 6812 reg->s32_max_value = reg->s32_min_value = u64_cval; 6813 reg->u32_max_value = reg->u32_min_value = u64_cval; 6814 return; 6815 } 6816 6817 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6818 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6819 6820 if (top_smax_value != top_smin_value) 6821 goto out; 6822 6823 /* find the s64_min and s64_min after sign extension */ 6824 if (size == 1) { 6825 init_s64_max = (s8)reg->smax_value; 6826 init_s64_min = (s8)reg->smin_value; 6827 } else if (size == 2) { 6828 init_s64_max = (s16)reg->smax_value; 6829 init_s64_min = (s16)reg->smin_value; 6830 } else { 6831 init_s64_max = (s32)reg->smax_value; 6832 init_s64_min = (s32)reg->smin_value; 6833 } 6834 6835 s64_max = max(init_s64_max, init_s64_min); 6836 s64_min = min(init_s64_max, init_s64_min); 6837 6838 /* both of s64_max/s64_min positive or negative */ 6839 if ((s64_max >= 0) == (s64_min >= 0)) { 6840 reg->s32_min_value = reg->smin_value = s64_min; 6841 reg->s32_max_value = reg->smax_value = s64_max; 6842 reg->u32_min_value = reg->umin_value = s64_min; 6843 reg->u32_max_value = reg->umax_value = s64_max; 6844 reg->var_off = tnum_range(s64_min, s64_max); 6845 return; 6846 } 6847 6848 out: 6849 set_sext64_default_val(reg, size); 6850 } 6851 6852 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6853 { 6854 if (size == 1) { 6855 reg->s32_min_value = S8_MIN; 6856 reg->s32_max_value = S8_MAX; 6857 } else { 6858 /* size == 2 */ 6859 reg->s32_min_value = S16_MIN; 6860 reg->s32_max_value = S16_MAX; 6861 } 6862 reg->u32_min_value = 0; 6863 reg->u32_max_value = U32_MAX; 6864 reg->var_off = tnum_subreg(tnum_unknown); 6865 } 6866 6867 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6868 { 6869 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6870 u32 top_smax_value, top_smin_value; 6871 u32 num_bits = size * 8; 6872 6873 if (tnum_is_const(reg->var_off)) { 6874 u32_val = reg->var_off.value; 6875 if (size == 1) 6876 reg->var_off = tnum_const((s8)u32_val); 6877 else 6878 reg->var_off = tnum_const((s16)u32_val); 6879 6880 u32_val = reg->var_off.value; 6881 reg->s32_min_value = reg->s32_max_value = u32_val; 6882 reg->u32_min_value = reg->u32_max_value = u32_val; 6883 return; 6884 } 6885 6886 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6887 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6888 6889 if (top_smax_value != top_smin_value) 6890 goto out; 6891 6892 /* find the s32_min and s32_min after sign extension */ 6893 if (size == 1) { 6894 init_s32_max = (s8)reg->s32_max_value; 6895 init_s32_min = (s8)reg->s32_min_value; 6896 } else { 6897 /* size == 2 */ 6898 init_s32_max = (s16)reg->s32_max_value; 6899 init_s32_min = (s16)reg->s32_min_value; 6900 } 6901 s32_max = max(init_s32_max, init_s32_min); 6902 s32_min = min(init_s32_max, init_s32_min); 6903 6904 if ((s32_min >= 0) == (s32_max >= 0)) { 6905 reg->s32_min_value = s32_min; 6906 reg->s32_max_value = s32_max; 6907 reg->u32_min_value = (u32)s32_min; 6908 reg->u32_max_value = (u32)s32_max; 6909 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 6910 return; 6911 } 6912 6913 out: 6914 set_sext32_default_val(reg, size); 6915 } 6916 6917 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6918 { 6919 /* A map is considered read-only if the following condition are true: 6920 * 6921 * 1) BPF program side cannot change any of the map content. The 6922 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6923 * and was set at map creation time. 6924 * 2) The map value(s) have been initialized from user space by a 6925 * loader and then "frozen", such that no new map update/delete 6926 * operations from syscall side are possible for the rest of 6927 * the map's lifetime from that point onwards. 6928 * 3) Any parallel/pending map update/delete operations from syscall 6929 * side have been completed. Only after that point, it's safe to 6930 * assume that map value(s) are immutable. 6931 */ 6932 return (map->map_flags & BPF_F_RDONLY_PROG) && 6933 READ_ONCE(map->frozen) && 6934 !bpf_map_write_active(map); 6935 } 6936 6937 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6938 bool is_ldsx) 6939 { 6940 void *ptr; 6941 u64 addr; 6942 int err; 6943 6944 err = map->ops->map_direct_value_addr(map, &addr, off); 6945 if (err) 6946 return err; 6947 ptr = (void *)(long)addr + off; 6948 6949 switch (size) { 6950 case sizeof(u8): 6951 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6952 break; 6953 case sizeof(u16): 6954 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6955 break; 6956 case sizeof(u32): 6957 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6958 break; 6959 case sizeof(u64): 6960 *val = *(u64 *)ptr; 6961 break; 6962 default: 6963 return -EINVAL; 6964 } 6965 return 0; 6966 } 6967 6968 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6969 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6970 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6971 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 6972 6973 /* 6974 * Allow list few fields as RCU trusted or full trusted. 6975 * This logic doesn't allow mix tagging and will be removed once GCC supports 6976 * btf_type_tag. 6977 */ 6978 6979 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6980 BTF_TYPE_SAFE_RCU(struct task_struct) { 6981 const cpumask_t *cpus_ptr; 6982 struct css_set __rcu *cgroups; 6983 struct task_struct __rcu *real_parent; 6984 struct task_struct *group_leader; 6985 }; 6986 6987 BTF_TYPE_SAFE_RCU(struct cgroup) { 6988 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6989 struct kernfs_node *kn; 6990 }; 6991 6992 BTF_TYPE_SAFE_RCU(struct css_set) { 6993 struct cgroup *dfl_cgrp; 6994 }; 6995 6996 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6997 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6998 struct file __rcu *exe_file; 6999 }; 7000 7001 /* skb->sk, req->sk are not RCU protected, but we mark them as such 7002 * because bpf prog accessible sockets are SOCK_RCU_FREE. 7003 */ 7004 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 7005 struct sock *sk; 7006 }; 7007 7008 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 7009 struct sock *sk; 7010 }; 7011 7012 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 7013 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 7014 struct seq_file *seq; 7015 }; 7016 7017 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 7018 struct bpf_iter_meta *meta; 7019 struct task_struct *task; 7020 }; 7021 7022 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 7023 struct file *file; 7024 }; 7025 7026 BTF_TYPE_SAFE_TRUSTED(struct file) { 7027 struct inode *f_inode; 7028 }; 7029 7030 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 7031 /* no negative dentry-s in places where bpf can see it */ 7032 struct inode *d_inode; 7033 }; 7034 7035 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 7036 struct sock *sk; 7037 }; 7038 7039 static bool type_is_rcu(struct bpf_verifier_env *env, 7040 struct bpf_reg_state *reg, 7041 const char *field_name, u32 btf_id) 7042 { 7043 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 7044 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 7045 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 7046 7047 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 7048 } 7049 7050 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 7051 struct bpf_reg_state *reg, 7052 const char *field_name, u32 btf_id) 7053 { 7054 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 7055 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 7056 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 7057 7058 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 7059 } 7060 7061 static bool type_is_trusted(struct bpf_verifier_env *env, 7062 struct bpf_reg_state *reg, 7063 const char *field_name, u32 btf_id) 7064 { 7065 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 7066 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 7067 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 7068 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 7069 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 7070 7071 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 7072 } 7073 7074 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 7075 struct bpf_reg_state *reg, 7076 const char *field_name, u32 btf_id) 7077 { 7078 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 7079 7080 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 7081 "__safe_trusted_or_null"); 7082 } 7083 7084 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 7085 struct bpf_reg_state *regs, 7086 int regno, int off, int size, 7087 enum bpf_access_type atype, 7088 int value_regno) 7089 { 7090 struct bpf_reg_state *reg = regs + regno; 7091 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 7092 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 7093 const char *field_name = NULL; 7094 enum bpf_type_flag flag = 0; 7095 u32 btf_id = 0; 7096 int ret; 7097 7098 if (!env->allow_ptr_leaks) { 7099 verbose(env, 7100 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 7101 tname); 7102 return -EPERM; 7103 } 7104 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 7105 verbose(env, 7106 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 7107 tname); 7108 return -EINVAL; 7109 } 7110 if (off < 0) { 7111 verbose(env, 7112 "R%d is ptr_%s invalid negative access: off=%d\n", 7113 regno, tname, off); 7114 return -EACCES; 7115 } 7116 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 7117 char tn_buf[48]; 7118 7119 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7120 verbose(env, 7121 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 7122 regno, tname, off, tn_buf); 7123 return -EACCES; 7124 } 7125 7126 if (reg->type & MEM_USER) { 7127 verbose(env, 7128 "R%d is ptr_%s access user memory: off=%d\n", 7129 regno, tname, off); 7130 return -EACCES; 7131 } 7132 7133 if (reg->type & MEM_PERCPU) { 7134 verbose(env, 7135 "R%d is ptr_%s access percpu memory: off=%d\n", 7136 regno, tname, off); 7137 return -EACCES; 7138 } 7139 7140 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 7141 if (!btf_is_kernel(reg->btf)) { 7142 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 7143 return -EFAULT; 7144 } 7145 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 7146 } else { 7147 /* Writes are permitted with default btf_struct_access for 7148 * program allocated objects (which always have ref_obj_id > 0), 7149 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 7150 */ 7151 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 7152 verbose(env, "only read is supported\n"); 7153 return -EACCES; 7154 } 7155 7156 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 7157 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 7158 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 7159 return -EFAULT; 7160 } 7161 7162 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 7163 } 7164 7165 if (ret < 0) 7166 return ret; 7167 7168 if (ret != PTR_TO_BTF_ID) { 7169 /* just mark; */ 7170 7171 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 7172 /* If this is an untrusted pointer, all pointers formed by walking it 7173 * also inherit the untrusted flag. 7174 */ 7175 flag = PTR_UNTRUSTED; 7176 7177 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 7178 /* By default any pointer obtained from walking a trusted pointer is no 7179 * longer trusted, unless the field being accessed has explicitly been 7180 * marked as inheriting its parent's state of trust (either full or RCU). 7181 * For example: 7182 * 'cgroups' pointer is untrusted if task->cgroups dereference 7183 * happened in a sleepable program outside of bpf_rcu_read_lock() 7184 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 7185 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 7186 * 7187 * A regular RCU-protected pointer with __rcu tag can also be deemed 7188 * trusted if we are in an RCU CS. Such pointer can be NULL. 7189 */ 7190 if (type_is_trusted(env, reg, field_name, btf_id)) { 7191 flag |= PTR_TRUSTED; 7192 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 7193 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 7194 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 7195 if (type_is_rcu(env, reg, field_name, btf_id)) { 7196 /* ignore __rcu tag and mark it MEM_RCU */ 7197 flag |= MEM_RCU; 7198 } else if (flag & MEM_RCU || 7199 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 7200 /* __rcu tagged pointers can be NULL */ 7201 flag |= MEM_RCU | PTR_MAYBE_NULL; 7202 7203 /* We always trust them */ 7204 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 7205 flag & PTR_UNTRUSTED) 7206 flag &= ~PTR_UNTRUSTED; 7207 } else if (flag & (MEM_PERCPU | MEM_USER)) { 7208 /* keep as-is */ 7209 } else { 7210 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 7211 clear_trusted_flags(&flag); 7212 } 7213 } else { 7214 /* 7215 * If not in RCU CS or MEM_RCU pointer can be NULL then 7216 * aggressively mark as untrusted otherwise such 7217 * pointers will be plain PTR_TO_BTF_ID without flags 7218 * and will be allowed to be passed into helpers for 7219 * compat reasons. 7220 */ 7221 flag = PTR_UNTRUSTED; 7222 } 7223 } else { 7224 /* Old compat. Deprecated */ 7225 clear_trusted_flags(&flag); 7226 } 7227 7228 if (atype == BPF_READ && value_regno >= 0) 7229 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 7230 7231 return 0; 7232 } 7233 7234 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 7235 struct bpf_reg_state *regs, 7236 int regno, int off, int size, 7237 enum bpf_access_type atype, 7238 int value_regno) 7239 { 7240 struct bpf_reg_state *reg = regs + regno; 7241 struct bpf_map *map = reg->map_ptr; 7242 struct bpf_reg_state map_reg; 7243 enum bpf_type_flag flag = 0; 7244 const struct btf_type *t; 7245 const char *tname; 7246 u32 btf_id; 7247 int ret; 7248 7249 if (!btf_vmlinux) { 7250 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 7251 return -ENOTSUPP; 7252 } 7253 7254 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 7255 verbose(env, "map_ptr access not supported for map type %d\n", 7256 map->map_type); 7257 return -ENOTSUPP; 7258 } 7259 7260 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 7261 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 7262 7263 if (!env->allow_ptr_leaks) { 7264 verbose(env, 7265 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 7266 tname); 7267 return -EPERM; 7268 } 7269 7270 if (off < 0) { 7271 verbose(env, "R%d is %s invalid negative access: off=%d\n", 7272 regno, tname, off); 7273 return -EACCES; 7274 } 7275 7276 if (atype != BPF_READ) { 7277 verbose(env, "only read from %s is supported\n", tname); 7278 return -EACCES; 7279 } 7280 7281 /* Simulate access to a PTR_TO_BTF_ID */ 7282 memset(&map_reg, 0, sizeof(map_reg)); 7283 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 7284 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 7285 if (ret < 0) 7286 return ret; 7287 7288 if (value_regno >= 0) 7289 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 7290 7291 return 0; 7292 } 7293 7294 /* Check that the stack access at the given offset is within bounds. The 7295 * maximum valid offset is -1. 7296 * 7297 * The minimum valid offset is -MAX_BPF_STACK for writes, and 7298 * -state->allocated_stack for reads. 7299 */ 7300 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 7301 s64 off, 7302 struct bpf_func_state *state, 7303 enum bpf_access_type t) 7304 { 7305 int min_valid_off; 7306 7307 if (t == BPF_WRITE || env->allow_uninit_stack) 7308 min_valid_off = -MAX_BPF_STACK; 7309 else 7310 min_valid_off = -state->allocated_stack; 7311 7312 if (off < min_valid_off || off > -1) 7313 return -EACCES; 7314 return 0; 7315 } 7316 7317 /* Check that the stack access at 'regno + off' falls within the maximum stack 7318 * bounds. 7319 * 7320 * 'off' includes `regno->offset`, but not its dynamic part (if any). 7321 */ 7322 static int check_stack_access_within_bounds( 7323 struct bpf_verifier_env *env, 7324 int regno, int off, int access_size, 7325 enum bpf_access_type type) 7326 { 7327 struct bpf_reg_state *regs = cur_regs(env); 7328 struct bpf_reg_state *reg = regs + regno; 7329 struct bpf_func_state *state = func(env, reg); 7330 s64 min_off, max_off; 7331 int err; 7332 char *err_extra; 7333 7334 if (type == BPF_READ) 7335 err_extra = " read from"; 7336 else 7337 err_extra = " write to"; 7338 7339 if (tnum_is_const(reg->var_off)) { 7340 min_off = (s64)reg->var_off.value + off; 7341 max_off = min_off + access_size; 7342 } else { 7343 if (reg->smax_value >= BPF_MAX_VAR_OFF || 7344 reg->smin_value <= -BPF_MAX_VAR_OFF) { 7345 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 7346 err_extra, regno); 7347 return -EACCES; 7348 } 7349 min_off = reg->smin_value + off; 7350 max_off = reg->smax_value + off + access_size; 7351 } 7352 7353 err = check_stack_slot_within_bounds(env, min_off, state, type); 7354 if (!err && max_off > 0) 7355 err = -EINVAL; /* out of stack access into non-negative offsets */ 7356 if (!err && access_size < 0) 7357 /* access_size should not be negative (or overflow an int); others checks 7358 * along the way should have prevented such an access. 7359 */ 7360 err = -EFAULT; /* invalid negative access size; integer overflow? */ 7361 7362 if (err) { 7363 if (tnum_is_const(reg->var_off)) { 7364 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 7365 err_extra, regno, off, access_size); 7366 } else { 7367 char tn_buf[48]; 7368 7369 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7370 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 7371 err_extra, regno, tn_buf, off, access_size); 7372 } 7373 return err; 7374 } 7375 7376 /* Note that there is no stack access with offset zero, so the needed stack 7377 * size is -min_off, not -min_off+1. 7378 */ 7379 return grow_stack_state(env, state, -min_off /* size */); 7380 } 7381 7382 static bool get_func_retval_range(struct bpf_prog *prog, 7383 struct bpf_retval_range *range) 7384 { 7385 if (prog->type == BPF_PROG_TYPE_LSM && 7386 prog->expected_attach_type == BPF_LSM_MAC && 7387 !bpf_lsm_get_retval_range(prog, range)) { 7388 return true; 7389 } 7390 return false; 7391 } 7392 7393 /* check whether memory at (regno + off) is accessible for t = (read | write) 7394 * if t==write, value_regno is a register which value is stored into memory 7395 * if t==read, value_regno is a register which will receive the value from memory 7396 * if t==write && value_regno==-1, some unknown value is stored into memory 7397 * if t==read && value_regno==-1, don't care what we read from memory 7398 */ 7399 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 7400 int off, int bpf_size, enum bpf_access_type t, 7401 int value_regno, bool strict_alignment_once, bool is_ldsx) 7402 { 7403 struct bpf_reg_state *regs = cur_regs(env); 7404 struct bpf_reg_state *reg = regs + regno; 7405 int size, err = 0; 7406 7407 size = bpf_size_to_bytes(bpf_size); 7408 if (size < 0) 7409 return size; 7410 7411 /* alignment checks will add in reg->off themselves */ 7412 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 7413 if (err) 7414 return err; 7415 7416 /* for access checks, reg->off is just part of off */ 7417 off += reg->off; 7418 7419 if (reg->type == PTR_TO_MAP_KEY) { 7420 if (t == BPF_WRITE) { 7421 verbose(env, "write to change key R%d not allowed\n", regno); 7422 return -EACCES; 7423 } 7424 7425 err = check_mem_region_access(env, regno, off, size, 7426 reg->map_ptr->key_size, false); 7427 if (err) 7428 return err; 7429 if (value_regno >= 0) 7430 mark_reg_unknown(env, regs, value_regno); 7431 } else if (reg->type == PTR_TO_MAP_VALUE) { 7432 struct btf_field *kptr_field = NULL; 7433 7434 if (t == BPF_WRITE && value_regno >= 0 && 7435 is_pointer_value(env, value_regno)) { 7436 verbose(env, "R%d leaks addr into map\n", value_regno); 7437 return -EACCES; 7438 } 7439 err = check_map_access_type(env, regno, off, size, t); 7440 if (err) 7441 return err; 7442 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 7443 if (err) 7444 return err; 7445 if (tnum_is_const(reg->var_off)) 7446 kptr_field = btf_record_find(reg->map_ptr->record, 7447 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 7448 if (kptr_field) { 7449 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 7450 } else if (t == BPF_READ && value_regno >= 0) { 7451 struct bpf_map *map = reg->map_ptr; 7452 7453 /* if map is read-only, track its contents as scalars */ 7454 if (tnum_is_const(reg->var_off) && 7455 bpf_map_is_rdonly(map) && 7456 map->ops->map_direct_value_addr) { 7457 int map_off = off + reg->var_off.value; 7458 u64 val = 0; 7459 7460 err = bpf_map_direct_read(map, map_off, size, 7461 &val, is_ldsx); 7462 if (err) 7463 return err; 7464 7465 regs[value_regno].type = SCALAR_VALUE; 7466 __mark_reg_known(®s[value_regno], val); 7467 } else { 7468 mark_reg_unknown(env, regs, value_regno); 7469 } 7470 } 7471 } else if (base_type(reg->type) == PTR_TO_MEM) { 7472 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7473 7474 if (type_may_be_null(reg->type)) { 7475 verbose(env, "R%d invalid mem access '%s'\n", regno, 7476 reg_type_str(env, reg->type)); 7477 return -EACCES; 7478 } 7479 7480 if (t == BPF_WRITE && rdonly_mem) { 7481 verbose(env, "R%d cannot write into %s\n", 7482 regno, reg_type_str(env, reg->type)); 7483 return -EACCES; 7484 } 7485 7486 if (t == BPF_WRITE && value_regno >= 0 && 7487 is_pointer_value(env, value_regno)) { 7488 verbose(env, "R%d leaks addr into mem\n", value_regno); 7489 return -EACCES; 7490 } 7491 7492 err = check_mem_region_access(env, regno, off, size, 7493 reg->mem_size, false); 7494 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 7495 mark_reg_unknown(env, regs, value_regno); 7496 } else if (reg->type == PTR_TO_CTX) { 7497 struct bpf_retval_range range; 7498 struct bpf_insn_access_aux info = { 7499 .reg_type = SCALAR_VALUE, 7500 .is_ldsx = is_ldsx, 7501 .log = &env->log, 7502 }; 7503 7504 if (t == BPF_WRITE && value_regno >= 0 && 7505 is_pointer_value(env, value_regno)) { 7506 verbose(env, "R%d leaks addr into ctx\n", value_regno); 7507 return -EACCES; 7508 } 7509 7510 err = check_ptr_off_reg(env, reg, regno); 7511 if (err < 0) 7512 return err; 7513 7514 err = check_ctx_access(env, insn_idx, off, size, t, &info); 7515 if (err) 7516 verbose_linfo(env, insn_idx, "; "); 7517 if (!err && t == BPF_READ && value_regno >= 0) { 7518 /* ctx access returns either a scalar, or a 7519 * PTR_TO_PACKET[_META,_END]. In the latter 7520 * case, we know the offset is zero. 7521 */ 7522 if (info.reg_type == SCALAR_VALUE) { 7523 if (info.is_retval && get_func_retval_range(env->prog, &range)) { 7524 err = __mark_reg_s32_range(env, regs, value_regno, 7525 range.minval, range.maxval); 7526 if (err) 7527 return err; 7528 } else { 7529 mark_reg_unknown(env, regs, value_regno); 7530 } 7531 } else { 7532 mark_reg_known_zero(env, regs, 7533 value_regno); 7534 if (type_may_be_null(info.reg_type)) 7535 regs[value_regno].id = ++env->id_gen; 7536 /* A load of ctx field could have different 7537 * actual load size with the one encoded in the 7538 * insn. When the dst is PTR, it is for sure not 7539 * a sub-register. 7540 */ 7541 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 7542 if (base_type(info.reg_type) == PTR_TO_BTF_ID) { 7543 regs[value_regno].btf = info.btf; 7544 regs[value_regno].btf_id = info.btf_id; 7545 regs[value_regno].ref_obj_id = info.ref_obj_id; 7546 } 7547 } 7548 regs[value_regno].type = info.reg_type; 7549 } 7550 7551 } else if (reg->type == PTR_TO_STACK) { 7552 /* Basic bounds checks. */ 7553 err = check_stack_access_within_bounds(env, regno, off, size, t); 7554 if (err) 7555 return err; 7556 7557 if (t == BPF_READ) 7558 err = check_stack_read(env, regno, off, size, 7559 value_regno); 7560 else 7561 err = check_stack_write(env, regno, off, size, 7562 value_regno, insn_idx); 7563 } else if (reg_is_pkt_pointer(reg)) { 7564 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 7565 verbose(env, "cannot write into packet\n"); 7566 return -EACCES; 7567 } 7568 if (t == BPF_WRITE && value_regno >= 0 && 7569 is_pointer_value(env, value_regno)) { 7570 verbose(env, "R%d leaks addr into packet\n", 7571 value_regno); 7572 return -EACCES; 7573 } 7574 err = check_packet_access(env, regno, off, size, false); 7575 if (!err && t == BPF_READ && value_regno >= 0) 7576 mark_reg_unknown(env, regs, value_regno); 7577 } else if (reg->type == PTR_TO_FLOW_KEYS) { 7578 if (t == BPF_WRITE && value_regno >= 0 && 7579 is_pointer_value(env, value_regno)) { 7580 verbose(env, "R%d leaks addr into flow keys\n", 7581 value_regno); 7582 return -EACCES; 7583 } 7584 7585 err = check_flow_keys_access(env, off, size); 7586 if (!err && t == BPF_READ && value_regno >= 0) 7587 mark_reg_unknown(env, regs, value_regno); 7588 } else if (type_is_sk_pointer(reg->type)) { 7589 if (t == BPF_WRITE) { 7590 verbose(env, "R%d cannot write into %s\n", 7591 regno, reg_type_str(env, reg->type)); 7592 return -EACCES; 7593 } 7594 err = check_sock_access(env, insn_idx, regno, off, size, t); 7595 if (!err && value_regno >= 0) 7596 mark_reg_unknown(env, regs, value_regno); 7597 } else if (reg->type == PTR_TO_TP_BUFFER) { 7598 err = check_tp_buffer_access(env, reg, regno, off, size); 7599 if (!err && t == BPF_READ && value_regno >= 0) 7600 mark_reg_unknown(env, regs, value_regno); 7601 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 7602 !type_may_be_null(reg->type)) { 7603 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 7604 value_regno); 7605 } else if (reg->type == CONST_PTR_TO_MAP) { 7606 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 7607 value_regno); 7608 } else if (base_type(reg->type) == PTR_TO_BUF) { 7609 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7610 u32 *max_access; 7611 7612 if (rdonly_mem) { 7613 if (t == BPF_WRITE) { 7614 verbose(env, "R%d cannot write into %s\n", 7615 regno, reg_type_str(env, reg->type)); 7616 return -EACCES; 7617 } 7618 max_access = &env->prog->aux->max_rdonly_access; 7619 } else { 7620 max_access = &env->prog->aux->max_rdwr_access; 7621 } 7622 7623 err = check_buffer_access(env, reg, regno, off, size, false, 7624 max_access); 7625 7626 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 7627 mark_reg_unknown(env, regs, value_regno); 7628 } else if (reg->type == PTR_TO_ARENA) { 7629 if (t == BPF_READ && value_regno >= 0) 7630 mark_reg_unknown(env, regs, value_regno); 7631 } else { 7632 verbose(env, "R%d invalid mem access '%s'\n", regno, 7633 reg_type_str(env, reg->type)); 7634 return -EACCES; 7635 } 7636 7637 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 7638 regs[value_regno].type == SCALAR_VALUE) { 7639 if (!is_ldsx) 7640 /* b/h/w load zero-extends, mark upper bits as known 0 */ 7641 coerce_reg_to_size(®s[value_regno], size); 7642 else 7643 coerce_reg_to_size_sx(®s[value_regno], size); 7644 } 7645 return err; 7646 } 7647 7648 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 7649 bool allow_trust_mismatch); 7650 7651 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn, 7652 bool strict_alignment_once, bool is_ldsx, 7653 bool allow_trust_mismatch, const char *ctx) 7654 { 7655 struct bpf_reg_state *regs = cur_regs(env); 7656 enum bpf_reg_type src_reg_type; 7657 int err; 7658 7659 /* check src operand */ 7660 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7661 if (err) 7662 return err; 7663 7664 /* check dst operand */ 7665 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 7666 if (err) 7667 return err; 7668 7669 src_reg_type = regs[insn->src_reg].type; 7670 7671 /* Check if (src_reg + off) is readable. The state of dst_reg will be 7672 * updated by this call. 7673 */ 7674 err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off, 7675 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg, 7676 strict_alignment_once, is_ldsx); 7677 err = err ?: save_aux_ptr_type(env, src_reg_type, 7678 allow_trust_mismatch); 7679 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx); 7680 7681 return err; 7682 } 7683 7684 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn, 7685 bool strict_alignment_once) 7686 { 7687 struct bpf_reg_state *regs = cur_regs(env); 7688 enum bpf_reg_type dst_reg_type; 7689 int err; 7690 7691 /* check src1 operand */ 7692 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7693 if (err) 7694 return err; 7695 7696 /* check src2 operand */ 7697 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7698 if (err) 7699 return err; 7700 7701 dst_reg_type = regs[insn->dst_reg].type; 7702 7703 /* Check if (dst_reg + off) is writeable. */ 7704 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 7705 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg, 7706 strict_alignment_once, false); 7707 err = err ?: save_aux_ptr_type(env, dst_reg_type, false); 7708 7709 return err; 7710 } 7711 7712 static int check_atomic_rmw(struct bpf_verifier_env *env, 7713 struct bpf_insn *insn) 7714 { 7715 int load_reg; 7716 int err; 7717 7718 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7719 verbose(env, "invalid atomic operand size\n"); 7720 return -EINVAL; 7721 } 7722 7723 /* check src1 operand */ 7724 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7725 if (err) 7726 return err; 7727 7728 /* check src2 operand */ 7729 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7730 if (err) 7731 return err; 7732 7733 if (insn->imm == BPF_CMPXCHG) { 7734 /* Check comparison of R0 with memory location */ 7735 const u32 aux_reg = BPF_REG_0; 7736 7737 err = check_reg_arg(env, aux_reg, SRC_OP); 7738 if (err) 7739 return err; 7740 7741 if (is_pointer_value(env, aux_reg)) { 7742 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7743 return -EACCES; 7744 } 7745 } 7746 7747 if (is_pointer_value(env, insn->src_reg)) { 7748 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7749 return -EACCES; 7750 } 7751 7752 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 7753 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7754 insn->dst_reg, 7755 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7756 return -EACCES; 7757 } 7758 7759 if (insn->imm & BPF_FETCH) { 7760 if (insn->imm == BPF_CMPXCHG) 7761 load_reg = BPF_REG_0; 7762 else 7763 load_reg = insn->src_reg; 7764 7765 /* check and record load of old value */ 7766 err = check_reg_arg(env, load_reg, DST_OP); 7767 if (err) 7768 return err; 7769 } else { 7770 /* This instruction accesses a memory location but doesn't 7771 * actually load it into a register. 7772 */ 7773 load_reg = -1; 7774 } 7775 7776 /* Check whether we can read the memory, with second call for fetch 7777 * case to simulate the register fill. 7778 */ 7779 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 7780 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7781 if (!err && load_reg >= 0) 7782 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 7783 insn->off, BPF_SIZE(insn->code), 7784 BPF_READ, load_reg, true, false); 7785 if (err) 7786 return err; 7787 7788 if (is_arena_reg(env, insn->dst_reg)) { 7789 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 7790 if (err) 7791 return err; 7792 } 7793 /* Check whether we can write into the same memory. */ 7794 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 7795 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7796 if (err) 7797 return err; 7798 return 0; 7799 } 7800 7801 static int check_atomic_load(struct bpf_verifier_env *env, 7802 struct bpf_insn *insn) 7803 { 7804 int err; 7805 7806 err = check_load_mem(env, insn, true, false, false, "atomic_load"); 7807 if (err) 7808 return err; 7809 7810 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) { 7811 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n", 7812 insn->src_reg, 7813 reg_type_str(env, reg_state(env, insn->src_reg)->type)); 7814 return -EACCES; 7815 } 7816 7817 return 0; 7818 } 7819 7820 static int check_atomic_store(struct bpf_verifier_env *env, 7821 struct bpf_insn *insn) 7822 { 7823 int err; 7824 7825 err = check_store_reg(env, insn, true); 7826 if (err) 7827 return err; 7828 7829 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 7830 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7831 insn->dst_reg, 7832 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7833 return -EACCES; 7834 } 7835 7836 return 0; 7837 } 7838 7839 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn) 7840 { 7841 switch (insn->imm) { 7842 case BPF_ADD: 7843 case BPF_ADD | BPF_FETCH: 7844 case BPF_AND: 7845 case BPF_AND | BPF_FETCH: 7846 case BPF_OR: 7847 case BPF_OR | BPF_FETCH: 7848 case BPF_XOR: 7849 case BPF_XOR | BPF_FETCH: 7850 case BPF_XCHG: 7851 case BPF_CMPXCHG: 7852 return check_atomic_rmw(env, insn); 7853 case BPF_LOAD_ACQ: 7854 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 7855 verbose(env, 7856 "64-bit load-acquires are only supported on 64-bit arches\n"); 7857 return -EOPNOTSUPP; 7858 } 7859 return check_atomic_load(env, insn); 7860 case BPF_STORE_REL: 7861 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 7862 verbose(env, 7863 "64-bit store-releases are only supported on 64-bit arches\n"); 7864 return -EOPNOTSUPP; 7865 } 7866 return check_atomic_store(env, insn); 7867 default: 7868 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", 7869 insn->imm); 7870 return -EINVAL; 7871 } 7872 } 7873 7874 /* When register 'regno' is used to read the stack (either directly or through 7875 * a helper function) make sure that it's within stack boundary and, depending 7876 * on the access type and privileges, that all elements of the stack are 7877 * initialized. 7878 * 7879 * 'off' includes 'regno->off', but not its dynamic part (if any). 7880 * 7881 * All registers that have been spilled on the stack in the slots within the 7882 * read offsets are marked as read. 7883 */ 7884 static int check_stack_range_initialized( 7885 struct bpf_verifier_env *env, int regno, int off, 7886 int access_size, bool zero_size_allowed, 7887 enum bpf_access_type type, struct bpf_call_arg_meta *meta) 7888 { 7889 struct bpf_reg_state *reg = reg_state(env, regno); 7890 struct bpf_func_state *state = func(env, reg); 7891 int err, min_off, max_off, i, j, slot, spi; 7892 /* Some accesses can write anything into the stack, others are 7893 * read-only. 7894 */ 7895 bool clobber = false; 7896 7897 if (access_size == 0 && !zero_size_allowed) { 7898 verbose(env, "invalid zero-sized read\n"); 7899 return -EACCES; 7900 } 7901 7902 if (type == BPF_WRITE) 7903 clobber = true; 7904 7905 err = check_stack_access_within_bounds(env, regno, off, access_size, type); 7906 if (err) 7907 return err; 7908 7909 7910 if (tnum_is_const(reg->var_off)) { 7911 min_off = max_off = reg->var_off.value + off; 7912 } else { 7913 /* Variable offset is prohibited for unprivileged mode for 7914 * simplicity since it requires corresponding support in 7915 * Spectre masking for stack ALU. 7916 * See also retrieve_ptr_limit(). 7917 */ 7918 if (!env->bypass_spec_v1) { 7919 char tn_buf[48]; 7920 7921 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7922 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 7923 regno, tn_buf); 7924 return -EACCES; 7925 } 7926 /* Only initialized buffer on stack is allowed to be accessed 7927 * with variable offset. With uninitialized buffer it's hard to 7928 * guarantee that whole memory is marked as initialized on 7929 * helper return since specific bounds are unknown what may 7930 * cause uninitialized stack leaking. 7931 */ 7932 if (meta && meta->raw_mode) 7933 meta = NULL; 7934 7935 min_off = reg->smin_value + off; 7936 max_off = reg->smax_value + off; 7937 } 7938 7939 if (meta && meta->raw_mode) { 7940 /* Ensure we won't be overwriting dynptrs when simulating byte 7941 * by byte access in check_helper_call using meta.access_size. 7942 * This would be a problem if we have a helper in the future 7943 * which takes: 7944 * 7945 * helper(uninit_mem, len, dynptr) 7946 * 7947 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7948 * may end up writing to dynptr itself when touching memory from 7949 * arg 1. This can be relaxed on a case by case basis for known 7950 * safe cases, but reject due to the possibilitiy of aliasing by 7951 * default. 7952 */ 7953 for (i = min_off; i < max_off + access_size; i++) { 7954 int stack_off = -i - 1; 7955 7956 spi = __get_spi(i); 7957 /* raw_mode may write past allocated_stack */ 7958 if (state->allocated_stack <= stack_off) 7959 continue; 7960 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7961 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7962 return -EACCES; 7963 } 7964 } 7965 meta->access_size = access_size; 7966 meta->regno = regno; 7967 return 0; 7968 } 7969 7970 for (i = min_off; i < max_off + access_size; i++) { 7971 u8 *stype; 7972 7973 slot = -i - 1; 7974 spi = slot / BPF_REG_SIZE; 7975 if (state->allocated_stack <= slot) { 7976 verbose(env, "allocated_stack too small\n"); 7977 return -EFAULT; 7978 } 7979 7980 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7981 if (*stype == STACK_MISC) 7982 goto mark; 7983 if ((*stype == STACK_ZERO) || 7984 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7985 if (clobber) { 7986 /* helper can write anything into the stack */ 7987 *stype = STACK_MISC; 7988 } 7989 goto mark; 7990 } 7991 7992 if (is_spilled_reg(&state->stack[spi]) && 7993 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7994 env->allow_ptr_leaks)) { 7995 if (clobber) { 7996 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7997 for (j = 0; j < BPF_REG_SIZE; j++) 7998 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7999 } 8000 goto mark; 8001 } 8002 8003 if (tnum_is_const(reg->var_off)) { 8004 verbose(env, "invalid read from stack R%d off %d+%d size %d\n", 8005 regno, min_off, i - min_off, access_size); 8006 } else { 8007 char tn_buf[48]; 8008 8009 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 8010 verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n", 8011 regno, tn_buf, i - min_off, access_size); 8012 } 8013 return -EACCES; 8014 mark: 8015 /* reading any byte out of 8-byte 'spill_slot' will cause 8016 * the whole slot to be marked as 'read' 8017 */ 8018 mark_reg_read(env, &state->stack[spi].spilled_ptr, 8019 state->stack[spi].spilled_ptr.parent, 8020 REG_LIVE_READ64); 8021 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 8022 * be sure that whether stack slot is written to or not. Hence, 8023 * we must still conservatively propagate reads upwards even if 8024 * helper may write to the entire memory range. 8025 */ 8026 } 8027 return 0; 8028 } 8029 8030 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 8031 int access_size, enum bpf_access_type access_type, 8032 bool zero_size_allowed, 8033 struct bpf_call_arg_meta *meta) 8034 { 8035 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8036 u32 *max_access; 8037 8038 switch (base_type(reg->type)) { 8039 case PTR_TO_PACKET: 8040 case PTR_TO_PACKET_META: 8041 return check_packet_access(env, regno, reg->off, access_size, 8042 zero_size_allowed); 8043 case PTR_TO_MAP_KEY: 8044 if (access_type == BPF_WRITE) { 8045 verbose(env, "R%d cannot write into %s\n", regno, 8046 reg_type_str(env, reg->type)); 8047 return -EACCES; 8048 } 8049 return check_mem_region_access(env, regno, reg->off, access_size, 8050 reg->map_ptr->key_size, false); 8051 case PTR_TO_MAP_VALUE: 8052 if (check_map_access_type(env, regno, reg->off, access_size, access_type)) 8053 return -EACCES; 8054 return check_map_access(env, regno, reg->off, access_size, 8055 zero_size_allowed, ACCESS_HELPER); 8056 case PTR_TO_MEM: 8057 if (type_is_rdonly_mem(reg->type)) { 8058 if (access_type == BPF_WRITE) { 8059 verbose(env, "R%d cannot write into %s\n", regno, 8060 reg_type_str(env, reg->type)); 8061 return -EACCES; 8062 } 8063 } 8064 return check_mem_region_access(env, regno, reg->off, 8065 access_size, reg->mem_size, 8066 zero_size_allowed); 8067 case PTR_TO_BUF: 8068 if (type_is_rdonly_mem(reg->type)) { 8069 if (access_type == BPF_WRITE) { 8070 verbose(env, "R%d cannot write into %s\n", regno, 8071 reg_type_str(env, reg->type)); 8072 return -EACCES; 8073 } 8074 8075 max_access = &env->prog->aux->max_rdonly_access; 8076 } else { 8077 max_access = &env->prog->aux->max_rdwr_access; 8078 } 8079 return check_buffer_access(env, reg, regno, reg->off, 8080 access_size, zero_size_allowed, 8081 max_access); 8082 case PTR_TO_STACK: 8083 return check_stack_range_initialized( 8084 env, 8085 regno, reg->off, access_size, 8086 zero_size_allowed, access_type, meta); 8087 case PTR_TO_BTF_ID: 8088 return check_ptr_to_btf_access(env, regs, regno, reg->off, 8089 access_size, BPF_READ, -1); 8090 case PTR_TO_CTX: 8091 /* in case the function doesn't know how to access the context, 8092 * (because we are in a program of type SYSCALL for example), we 8093 * can not statically check its size. 8094 * Dynamically check it now. 8095 */ 8096 if (!env->ops->convert_ctx_access) { 8097 int offset = access_size - 1; 8098 8099 /* Allow zero-byte read from PTR_TO_CTX */ 8100 if (access_size == 0) 8101 return zero_size_allowed ? 0 : -EACCES; 8102 8103 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 8104 access_type, -1, false, false); 8105 } 8106 8107 fallthrough; 8108 default: /* scalar_value or invalid ptr */ 8109 /* Allow zero-byte read from NULL, regardless of pointer type */ 8110 if (zero_size_allowed && access_size == 0 && 8111 register_is_null(reg)) 8112 return 0; 8113 8114 verbose(env, "R%d type=%s ", regno, 8115 reg_type_str(env, reg->type)); 8116 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 8117 return -EACCES; 8118 } 8119 } 8120 8121 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 8122 * size. 8123 * 8124 * @regno is the register containing the access size. regno-1 is the register 8125 * containing the pointer. 8126 */ 8127 static int check_mem_size_reg(struct bpf_verifier_env *env, 8128 struct bpf_reg_state *reg, u32 regno, 8129 enum bpf_access_type access_type, 8130 bool zero_size_allowed, 8131 struct bpf_call_arg_meta *meta) 8132 { 8133 int err; 8134 8135 /* This is used to refine r0 return value bounds for helpers 8136 * that enforce this value as an upper bound on return values. 8137 * See do_refine_retval_range() for helpers that can refine 8138 * the return value. C type of helper is u32 so we pull register 8139 * bound from umax_value however, if negative verifier errors 8140 * out. Only upper bounds can be learned because retval is an 8141 * int type and negative retvals are allowed. 8142 */ 8143 meta->msize_max_value = reg->umax_value; 8144 8145 /* The register is SCALAR_VALUE; the access check happens using 8146 * its boundaries. For unprivileged variable accesses, disable 8147 * raw mode so that the program is required to initialize all 8148 * the memory that the helper could just partially fill up. 8149 */ 8150 if (!tnum_is_const(reg->var_off)) 8151 meta = NULL; 8152 8153 if (reg->smin_value < 0) { 8154 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 8155 regno); 8156 return -EACCES; 8157 } 8158 8159 if (reg->umin_value == 0 && !zero_size_allowed) { 8160 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 8161 regno, reg->umin_value, reg->umax_value); 8162 return -EACCES; 8163 } 8164 8165 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 8166 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 8167 regno); 8168 return -EACCES; 8169 } 8170 err = check_helper_mem_access(env, regno - 1, reg->umax_value, 8171 access_type, zero_size_allowed, meta); 8172 if (!err) 8173 err = mark_chain_precision(env, regno); 8174 return err; 8175 } 8176 8177 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8178 u32 regno, u32 mem_size) 8179 { 8180 bool may_be_null = type_may_be_null(reg->type); 8181 struct bpf_reg_state saved_reg; 8182 int err; 8183 8184 if (register_is_null(reg)) 8185 return 0; 8186 8187 /* Assuming that the register contains a value check if the memory 8188 * access is safe. Temporarily save and restore the register's state as 8189 * the conversion shouldn't be visible to a caller. 8190 */ 8191 if (may_be_null) { 8192 saved_reg = *reg; 8193 mark_ptr_not_null_reg(reg); 8194 } 8195 8196 err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL); 8197 err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL); 8198 8199 if (may_be_null) 8200 *reg = saved_reg; 8201 8202 return err; 8203 } 8204 8205 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8206 u32 regno) 8207 { 8208 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 8209 bool may_be_null = type_may_be_null(mem_reg->type); 8210 struct bpf_reg_state saved_reg; 8211 struct bpf_call_arg_meta meta; 8212 int err; 8213 8214 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 8215 8216 memset(&meta, 0, sizeof(meta)); 8217 8218 if (may_be_null) { 8219 saved_reg = *mem_reg; 8220 mark_ptr_not_null_reg(mem_reg); 8221 } 8222 8223 err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta); 8224 err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta); 8225 8226 if (may_be_null) 8227 *mem_reg = saved_reg; 8228 8229 return err; 8230 } 8231 8232 enum { 8233 PROCESS_SPIN_LOCK = (1 << 0), 8234 PROCESS_RES_LOCK = (1 << 1), 8235 PROCESS_LOCK_IRQ = (1 << 2), 8236 }; 8237 8238 /* Implementation details: 8239 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 8240 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 8241 * Two bpf_map_lookups (even with the same key) will have different reg->id. 8242 * Two separate bpf_obj_new will also have different reg->id. 8243 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 8244 * clears reg->id after value_or_null->value transition, since the verifier only 8245 * cares about the range of access to valid map value pointer and doesn't care 8246 * about actual address of the map element. 8247 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 8248 * reg->id > 0 after value_or_null->value transition. By doing so 8249 * two bpf_map_lookups will be considered two different pointers that 8250 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 8251 * returned from bpf_obj_new. 8252 * The verifier allows taking only one bpf_spin_lock at a time to avoid 8253 * dead-locks. 8254 * Since only one bpf_spin_lock is allowed the checks are simpler than 8255 * reg_is_refcounted() logic. The verifier needs to remember only 8256 * one spin_lock instead of array of acquired_refs. 8257 * env->cur_state->active_locks remembers which map value element or allocated 8258 * object got locked and clears it after bpf_spin_unlock. 8259 */ 8260 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags) 8261 { 8262 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK; 8263 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin"; 8264 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8265 struct bpf_verifier_state *cur = env->cur_state; 8266 bool is_const = tnum_is_const(reg->var_off); 8267 bool is_irq = flags & PROCESS_LOCK_IRQ; 8268 u64 val = reg->var_off.value; 8269 struct bpf_map *map = NULL; 8270 struct btf *btf = NULL; 8271 struct btf_record *rec; 8272 u32 spin_lock_off; 8273 int err; 8274 8275 if (!is_const) { 8276 verbose(env, 8277 "R%d doesn't have constant offset. %s_lock has to be at the constant offset\n", 8278 regno, lock_str); 8279 return -EINVAL; 8280 } 8281 if (reg->type == PTR_TO_MAP_VALUE) { 8282 map = reg->map_ptr; 8283 if (!map->btf) { 8284 verbose(env, 8285 "map '%s' has to have BTF in order to use %s_lock\n", 8286 map->name, lock_str); 8287 return -EINVAL; 8288 } 8289 } else { 8290 btf = reg->btf; 8291 } 8292 8293 rec = reg_btf_record(reg); 8294 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) { 8295 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local", 8296 map ? map->name : "kptr", lock_str); 8297 return -EINVAL; 8298 } 8299 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off; 8300 if (spin_lock_off != val + reg->off) { 8301 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n", 8302 val + reg->off, lock_str, spin_lock_off); 8303 return -EINVAL; 8304 } 8305 if (is_lock) { 8306 void *ptr; 8307 int type; 8308 8309 if (map) 8310 ptr = map; 8311 else 8312 ptr = btf; 8313 8314 if (!is_res_lock && cur->active_locks) { 8315 if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) { 8316 verbose(env, 8317 "Locking two bpf_spin_locks are not allowed\n"); 8318 return -EINVAL; 8319 } 8320 } else if (is_res_lock && cur->active_locks) { 8321 if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) { 8322 verbose(env, "Acquiring the same lock again, AA deadlock detected\n"); 8323 return -EINVAL; 8324 } 8325 } 8326 8327 if (is_res_lock && is_irq) 8328 type = REF_TYPE_RES_LOCK_IRQ; 8329 else if (is_res_lock) 8330 type = REF_TYPE_RES_LOCK; 8331 else 8332 type = REF_TYPE_LOCK; 8333 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr); 8334 if (err < 0) { 8335 verbose(env, "Failed to acquire lock state\n"); 8336 return err; 8337 } 8338 } else { 8339 void *ptr; 8340 int type; 8341 8342 if (map) 8343 ptr = map; 8344 else 8345 ptr = btf; 8346 8347 if (!cur->active_locks) { 8348 verbose(env, "%s_unlock without taking a lock\n", lock_str); 8349 return -EINVAL; 8350 } 8351 8352 if (is_res_lock && is_irq) 8353 type = REF_TYPE_RES_LOCK_IRQ; 8354 else if (is_res_lock) 8355 type = REF_TYPE_RES_LOCK; 8356 else 8357 type = REF_TYPE_LOCK; 8358 if (!find_lock_state(cur, type, reg->id, ptr)) { 8359 verbose(env, "%s_unlock of different lock\n", lock_str); 8360 return -EINVAL; 8361 } 8362 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) { 8363 verbose(env, "%s_unlock cannot be out of order\n", lock_str); 8364 return -EINVAL; 8365 } 8366 if (release_lock_state(cur, type, reg->id, ptr)) { 8367 verbose(env, "%s_unlock of different lock\n", lock_str); 8368 return -EINVAL; 8369 } 8370 8371 invalidate_non_owning_refs(env); 8372 } 8373 return 0; 8374 } 8375 8376 static int process_timer_func(struct bpf_verifier_env *env, int regno, 8377 struct bpf_call_arg_meta *meta) 8378 { 8379 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8380 bool is_const = tnum_is_const(reg->var_off); 8381 struct bpf_map *map = reg->map_ptr; 8382 u64 val = reg->var_off.value; 8383 8384 if (!is_const) { 8385 verbose(env, 8386 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 8387 regno); 8388 return -EINVAL; 8389 } 8390 if (!map->btf) { 8391 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 8392 map->name); 8393 return -EINVAL; 8394 } 8395 if (!btf_record_has_field(map->record, BPF_TIMER)) { 8396 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 8397 return -EINVAL; 8398 } 8399 if (map->record->timer_off != val + reg->off) { 8400 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 8401 val + reg->off, map->record->timer_off); 8402 return -EINVAL; 8403 } 8404 if (meta->map_ptr) { 8405 verifier_bug(env, "Two map pointers in a timer helper"); 8406 return -EFAULT; 8407 } 8408 meta->map_uid = reg->map_uid; 8409 meta->map_ptr = map; 8410 return 0; 8411 } 8412 8413 static int process_wq_func(struct bpf_verifier_env *env, int regno, 8414 struct bpf_kfunc_call_arg_meta *meta) 8415 { 8416 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8417 struct bpf_map *map = reg->map_ptr; 8418 u64 val = reg->var_off.value; 8419 8420 if (map->record->wq_off != val + reg->off) { 8421 verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n", 8422 val + reg->off, map->record->wq_off); 8423 return -EINVAL; 8424 } 8425 meta->map.uid = reg->map_uid; 8426 meta->map.ptr = map; 8427 return 0; 8428 } 8429 8430 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 8431 struct bpf_call_arg_meta *meta) 8432 { 8433 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8434 struct btf_field *kptr_field; 8435 struct bpf_map *map_ptr; 8436 struct btf_record *rec; 8437 u32 kptr_off; 8438 8439 if (type_is_ptr_alloc_obj(reg->type)) { 8440 rec = reg_btf_record(reg); 8441 } else { /* PTR_TO_MAP_VALUE */ 8442 map_ptr = reg->map_ptr; 8443 if (!map_ptr->btf) { 8444 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 8445 map_ptr->name); 8446 return -EINVAL; 8447 } 8448 rec = map_ptr->record; 8449 meta->map_ptr = map_ptr; 8450 } 8451 8452 if (!tnum_is_const(reg->var_off)) { 8453 verbose(env, 8454 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 8455 regno); 8456 return -EINVAL; 8457 } 8458 8459 if (!btf_record_has_field(rec, BPF_KPTR)) { 8460 verbose(env, "R%d has no valid kptr\n", regno); 8461 return -EINVAL; 8462 } 8463 8464 kptr_off = reg->off + reg->var_off.value; 8465 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 8466 if (!kptr_field) { 8467 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 8468 return -EACCES; 8469 } 8470 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 8471 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 8472 return -EACCES; 8473 } 8474 meta->kptr_field = kptr_field; 8475 return 0; 8476 } 8477 8478 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 8479 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 8480 * 8481 * In both cases we deal with the first 8 bytes, but need to mark the next 8 8482 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 8483 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 8484 * 8485 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 8486 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 8487 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 8488 * mutate the view of the dynptr and also possibly destroy it. In the latter 8489 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 8490 * memory that dynptr points to. 8491 * 8492 * The verifier will keep track both levels of mutation (bpf_dynptr's in 8493 * reg->type and the memory's in reg->dynptr.type), but there is no support for 8494 * readonly dynptr view yet, hence only the first case is tracked and checked. 8495 * 8496 * This is consistent with how C applies the const modifier to a struct object, 8497 * where the pointer itself inside bpf_dynptr becomes const but not what it 8498 * points to. 8499 * 8500 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 8501 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 8502 */ 8503 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 8504 enum bpf_arg_type arg_type, int clone_ref_obj_id) 8505 { 8506 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8507 int err; 8508 8509 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 8510 verbose(env, 8511 "arg#%d expected pointer to stack or const struct bpf_dynptr\n", 8512 regno - 1); 8513 return -EINVAL; 8514 } 8515 8516 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 8517 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 8518 */ 8519 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 8520 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 8521 return -EFAULT; 8522 } 8523 8524 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 8525 * constructing a mutable bpf_dynptr object. 8526 * 8527 * Currently, this is only possible with PTR_TO_STACK 8528 * pointing to a region of at least 16 bytes which doesn't 8529 * contain an existing bpf_dynptr. 8530 * 8531 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 8532 * mutated or destroyed. However, the memory it points to 8533 * may be mutated. 8534 * 8535 * None - Points to a initialized dynptr that can be mutated and 8536 * destroyed, including mutation of the memory it points 8537 * to. 8538 */ 8539 if (arg_type & MEM_UNINIT) { 8540 int i; 8541 8542 if (!is_dynptr_reg_valid_uninit(env, reg)) { 8543 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 8544 return -EINVAL; 8545 } 8546 8547 /* we write BPF_DW bits (8 bytes) at a time */ 8548 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 8549 err = check_mem_access(env, insn_idx, regno, 8550 i, BPF_DW, BPF_WRITE, -1, false, false); 8551 if (err) 8552 return err; 8553 } 8554 8555 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 8556 } else /* MEM_RDONLY and None case from above */ { 8557 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 8558 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 8559 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 8560 return -EINVAL; 8561 } 8562 8563 if (!is_dynptr_reg_valid_init(env, reg)) { 8564 verbose(env, 8565 "Expected an initialized dynptr as arg #%d\n", 8566 regno - 1); 8567 return -EINVAL; 8568 } 8569 8570 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 8571 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 8572 verbose(env, 8573 "Expected a dynptr of type %s as arg #%d\n", 8574 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1); 8575 return -EINVAL; 8576 } 8577 8578 err = mark_dynptr_read(env, reg); 8579 } 8580 return err; 8581 } 8582 8583 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 8584 { 8585 struct bpf_func_state *state = func(env, reg); 8586 8587 return state->stack[spi].spilled_ptr.ref_obj_id; 8588 } 8589 8590 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8591 { 8592 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 8593 } 8594 8595 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8596 { 8597 return meta->kfunc_flags & KF_ITER_NEW; 8598 } 8599 8600 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8601 { 8602 return meta->kfunc_flags & KF_ITER_NEXT; 8603 } 8604 8605 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8606 { 8607 return meta->kfunc_flags & KF_ITER_DESTROY; 8608 } 8609 8610 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 8611 const struct btf_param *arg) 8612 { 8613 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 8614 * kfunc is iter state pointer 8615 */ 8616 if (is_iter_kfunc(meta)) 8617 return arg_idx == 0; 8618 8619 /* iter passed as an argument to a generic kfunc */ 8620 return btf_param_match_suffix(meta->btf, arg, "__iter"); 8621 } 8622 8623 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 8624 struct bpf_kfunc_call_arg_meta *meta) 8625 { 8626 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8627 const struct btf_type *t; 8628 int spi, err, i, nr_slots, btf_id; 8629 8630 if (reg->type != PTR_TO_STACK) { 8631 verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1); 8632 return -EINVAL; 8633 } 8634 8635 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 8636 * ensures struct convention, so we wouldn't need to do any BTF 8637 * validation here. But given iter state can be passed as a parameter 8638 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 8639 * conservative here. 8640 */ 8641 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1); 8642 if (btf_id < 0) { 8643 verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1); 8644 return -EINVAL; 8645 } 8646 t = btf_type_by_id(meta->btf, btf_id); 8647 nr_slots = t->size / BPF_REG_SIZE; 8648 8649 if (is_iter_new_kfunc(meta)) { 8650 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 8651 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 8652 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 8653 iter_type_str(meta->btf, btf_id), regno - 1); 8654 return -EINVAL; 8655 } 8656 8657 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 8658 err = check_mem_access(env, insn_idx, regno, 8659 i, BPF_DW, BPF_WRITE, -1, false, false); 8660 if (err) 8661 return err; 8662 } 8663 8664 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 8665 if (err) 8666 return err; 8667 } else { 8668 /* iter_next() or iter_destroy(), as well as any kfunc 8669 * accepting iter argument, expect initialized iter state 8670 */ 8671 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 8672 switch (err) { 8673 case 0: 8674 break; 8675 case -EINVAL: 8676 verbose(env, "expected an initialized iter_%s as arg #%d\n", 8677 iter_type_str(meta->btf, btf_id), regno - 1); 8678 return err; 8679 case -EPROTO: 8680 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 8681 return err; 8682 default: 8683 return err; 8684 } 8685 8686 spi = iter_get_spi(env, reg, nr_slots); 8687 if (spi < 0) 8688 return spi; 8689 8690 err = mark_iter_read(env, reg, spi, nr_slots); 8691 if (err) 8692 return err; 8693 8694 /* remember meta->iter info for process_iter_next_call() */ 8695 meta->iter.spi = spi; 8696 meta->iter.frameno = reg->frameno; 8697 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 8698 8699 if (is_iter_destroy_kfunc(meta)) { 8700 err = unmark_stack_slots_iter(env, reg, nr_slots); 8701 if (err) 8702 return err; 8703 } 8704 } 8705 8706 return 0; 8707 } 8708 8709 /* Look for a previous loop entry at insn_idx: nearest parent state 8710 * stopped at insn_idx with callsites matching those in cur->frame. 8711 */ 8712 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 8713 struct bpf_verifier_state *cur, 8714 int insn_idx) 8715 { 8716 struct bpf_verifier_state_list *sl; 8717 struct bpf_verifier_state *st; 8718 struct list_head *pos, *head; 8719 8720 /* Explored states are pushed in stack order, most recent states come first */ 8721 head = explored_state(env, insn_idx); 8722 list_for_each(pos, head) { 8723 sl = container_of(pos, struct bpf_verifier_state_list, node); 8724 /* If st->branches != 0 state is a part of current DFS verification path, 8725 * hence cur & st for a loop. 8726 */ 8727 st = &sl->state; 8728 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 8729 st->dfs_depth < cur->dfs_depth) 8730 return st; 8731 } 8732 8733 return NULL; 8734 } 8735 8736 static void reset_idmap_scratch(struct bpf_verifier_env *env); 8737 static bool regs_exact(const struct bpf_reg_state *rold, 8738 const struct bpf_reg_state *rcur, 8739 struct bpf_idmap *idmap); 8740 8741 static void maybe_widen_reg(struct bpf_verifier_env *env, 8742 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 8743 struct bpf_idmap *idmap) 8744 { 8745 if (rold->type != SCALAR_VALUE) 8746 return; 8747 if (rold->type != rcur->type) 8748 return; 8749 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 8750 return; 8751 __mark_reg_unknown(env, rcur); 8752 } 8753 8754 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 8755 struct bpf_verifier_state *old, 8756 struct bpf_verifier_state *cur) 8757 { 8758 struct bpf_func_state *fold, *fcur; 8759 int i, fr; 8760 8761 reset_idmap_scratch(env); 8762 for (fr = old->curframe; fr >= 0; fr--) { 8763 fold = old->frame[fr]; 8764 fcur = cur->frame[fr]; 8765 8766 for (i = 0; i < MAX_BPF_REG; i++) 8767 maybe_widen_reg(env, 8768 &fold->regs[i], 8769 &fcur->regs[i], 8770 &env->idmap_scratch); 8771 8772 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 8773 if (!is_spilled_reg(&fold->stack[i]) || 8774 !is_spilled_reg(&fcur->stack[i])) 8775 continue; 8776 8777 maybe_widen_reg(env, 8778 &fold->stack[i].spilled_ptr, 8779 &fcur->stack[i].spilled_ptr, 8780 &env->idmap_scratch); 8781 } 8782 } 8783 return 0; 8784 } 8785 8786 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 8787 struct bpf_kfunc_call_arg_meta *meta) 8788 { 8789 int iter_frameno = meta->iter.frameno; 8790 int iter_spi = meta->iter.spi; 8791 8792 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8793 } 8794 8795 /* process_iter_next_call() is called when verifier gets to iterator's next 8796 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 8797 * to it as just "iter_next()" in comments below. 8798 * 8799 * BPF verifier relies on a crucial contract for any iter_next() 8800 * implementation: it should *eventually* return NULL, and once that happens 8801 * it should keep returning NULL. That is, once iterator exhausts elements to 8802 * iterate, it should never reset or spuriously return new elements. 8803 * 8804 * With the assumption of such contract, process_iter_next_call() simulates 8805 * a fork in the verifier state to validate loop logic correctness and safety 8806 * without having to simulate infinite amount of iterations. 8807 * 8808 * In current state, we first assume that iter_next() returned NULL and 8809 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 8810 * conditions we should not form an infinite loop and should eventually reach 8811 * exit. 8812 * 8813 * Besides that, we also fork current state and enqueue it for later 8814 * verification. In a forked state we keep iterator state as ACTIVE 8815 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 8816 * also bump iteration depth to prevent erroneous infinite loop detection 8817 * later on (see iter_active_depths_differ() comment for details). In this 8818 * state we assume that we'll eventually loop back to another iter_next() 8819 * calls (it could be in exactly same location or in some other instruction, 8820 * it doesn't matter, we don't make any unnecessary assumptions about this, 8821 * everything revolves around iterator state in a stack slot, not which 8822 * instruction is calling iter_next()). When that happens, we either will come 8823 * to iter_next() with equivalent state and can conclude that next iteration 8824 * will proceed in exactly the same way as we just verified, so it's safe to 8825 * assume that loop converges. If not, we'll go on another iteration 8826 * simulation with a different input state, until all possible starting states 8827 * are validated or we reach maximum number of instructions limit. 8828 * 8829 * This way, we will either exhaustively discover all possible input states 8830 * that iterator loop can start with and eventually will converge, or we'll 8831 * effectively regress into bounded loop simulation logic and either reach 8832 * maximum number of instructions if loop is not provably convergent, or there 8833 * is some statically known limit on number of iterations (e.g., if there is 8834 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8835 * 8836 * Iteration convergence logic in is_state_visited() relies on exact 8837 * states comparison, which ignores read and precision marks. 8838 * This is necessary because read and precision marks are not finalized 8839 * while in the loop. Exact comparison might preclude convergence for 8840 * simple programs like below: 8841 * 8842 * i = 0; 8843 * while(iter_next(&it)) 8844 * i++; 8845 * 8846 * At each iteration step i++ would produce a new distinct state and 8847 * eventually instruction processing limit would be reached. 8848 * 8849 * To avoid such behavior speculatively forget (widen) range for 8850 * imprecise scalar registers, if those registers were not precise at the 8851 * end of the previous iteration and do not match exactly. 8852 * 8853 * This is a conservative heuristic that allows to verify wide range of programs, 8854 * however it precludes verification of programs that conjure an 8855 * imprecise value on the first loop iteration and use it as precise on a second. 8856 * For example, the following safe program would fail to verify: 8857 * 8858 * struct bpf_num_iter it; 8859 * int arr[10]; 8860 * int i = 0, a = 0; 8861 * bpf_iter_num_new(&it, 0, 10); 8862 * while (bpf_iter_num_next(&it)) { 8863 * if (a == 0) { 8864 * a = 1; 8865 * i = 7; // Because i changed verifier would forget 8866 * // it's range on second loop entry. 8867 * } else { 8868 * arr[i] = 42; // This would fail to verify. 8869 * } 8870 * } 8871 * bpf_iter_num_destroy(&it); 8872 */ 8873 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 8874 struct bpf_kfunc_call_arg_meta *meta) 8875 { 8876 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 8877 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 8878 struct bpf_reg_state *cur_iter, *queued_iter; 8879 8880 BTF_TYPE_EMIT(struct bpf_iter); 8881 8882 cur_iter = get_iter_from_state(cur_st, meta); 8883 8884 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 8885 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 8886 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 8887 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 8888 return -EFAULT; 8889 } 8890 8891 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 8892 /* Because iter_next() call is a checkpoint is_state_visitied() 8893 * should guarantee parent state with same call sites and insn_idx. 8894 */ 8895 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 8896 !same_callsites(cur_st->parent, cur_st)) { 8897 verbose(env, "bug: bad parent state for iter next call"); 8898 return -EFAULT; 8899 } 8900 /* Note cur_st->parent in the call below, it is necessary to skip 8901 * checkpoint created for cur_st by is_state_visited() 8902 * right at this instruction. 8903 */ 8904 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 8905 /* branch out active iter state */ 8906 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 8907 if (!queued_st) 8908 return -ENOMEM; 8909 8910 queued_iter = get_iter_from_state(queued_st, meta); 8911 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 8912 queued_iter->iter.depth++; 8913 if (prev_st) 8914 widen_imprecise_scalars(env, prev_st, queued_st); 8915 8916 queued_fr = queued_st->frame[queued_st->curframe]; 8917 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8918 } 8919 8920 /* switch to DRAINED state, but keep the depth unchanged */ 8921 /* mark current iter state as drained and assume returned NULL */ 8922 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8923 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 8924 8925 return 0; 8926 } 8927 8928 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8929 { 8930 return type == ARG_CONST_SIZE || 8931 type == ARG_CONST_SIZE_OR_ZERO; 8932 } 8933 8934 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 8935 { 8936 return base_type(type) == ARG_PTR_TO_MEM && 8937 type & MEM_UNINIT; 8938 } 8939 8940 static bool arg_type_is_release(enum bpf_arg_type type) 8941 { 8942 return type & OBJ_RELEASE; 8943 } 8944 8945 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8946 { 8947 return base_type(type) == ARG_PTR_TO_DYNPTR; 8948 } 8949 8950 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8951 const struct bpf_call_arg_meta *meta, 8952 enum bpf_arg_type *arg_type) 8953 { 8954 if (!meta->map_ptr) { 8955 /* kernel subsystem misconfigured verifier */ 8956 verbose(env, "invalid map_ptr to access map->type\n"); 8957 return -EACCES; 8958 } 8959 8960 switch (meta->map_ptr->map_type) { 8961 case BPF_MAP_TYPE_SOCKMAP: 8962 case BPF_MAP_TYPE_SOCKHASH: 8963 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8964 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8965 } else { 8966 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8967 return -EINVAL; 8968 } 8969 break; 8970 case BPF_MAP_TYPE_BLOOM_FILTER: 8971 if (meta->func_id == BPF_FUNC_map_peek_elem) 8972 *arg_type = ARG_PTR_TO_MAP_VALUE; 8973 break; 8974 default: 8975 break; 8976 } 8977 return 0; 8978 } 8979 8980 struct bpf_reg_types { 8981 const enum bpf_reg_type types[10]; 8982 u32 *btf_id; 8983 }; 8984 8985 static const struct bpf_reg_types sock_types = { 8986 .types = { 8987 PTR_TO_SOCK_COMMON, 8988 PTR_TO_SOCKET, 8989 PTR_TO_TCP_SOCK, 8990 PTR_TO_XDP_SOCK, 8991 }, 8992 }; 8993 8994 #ifdef CONFIG_NET 8995 static const struct bpf_reg_types btf_id_sock_common_types = { 8996 .types = { 8997 PTR_TO_SOCK_COMMON, 8998 PTR_TO_SOCKET, 8999 PTR_TO_TCP_SOCK, 9000 PTR_TO_XDP_SOCK, 9001 PTR_TO_BTF_ID, 9002 PTR_TO_BTF_ID | PTR_TRUSTED, 9003 }, 9004 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 9005 }; 9006 #endif 9007 9008 static const struct bpf_reg_types mem_types = { 9009 .types = { 9010 PTR_TO_STACK, 9011 PTR_TO_PACKET, 9012 PTR_TO_PACKET_META, 9013 PTR_TO_MAP_KEY, 9014 PTR_TO_MAP_VALUE, 9015 PTR_TO_MEM, 9016 PTR_TO_MEM | MEM_RINGBUF, 9017 PTR_TO_BUF, 9018 PTR_TO_BTF_ID | PTR_TRUSTED, 9019 }, 9020 }; 9021 9022 static const struct bpf_reg_types spin_lock_types = { 9023 .types = { 9024 PTR_TO_MAP_VALUE, 9025 PTR_TO_BTF_ID | MEM_ALLOC, 9026 } 9027 }; 9028 9029 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 9030 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 9031 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 9032 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 9033 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 9034 static const struct bpf_reg_types btf_ptr_types = { 9035 .types = { 9036 PTR_TO_BTF_ID, 9037 PTR_TO_BTF_ID | PTR_TRUSTED, 9038 PTR_TO_BTF_ID | MEM_RCU, 9039 }, 9040 }; 9041 static const struct bpf_reg_types percpu_btf_ptr_types = { 9042 .types = { 9043 PTR_TO_BTF_ID | MEM_PERCPU, 9044 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 9045 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 9046 } 9047 }; 9048 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 9049 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 9050 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 9051 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 9052 static const struct bpf_reg_types kptr_xchg_dest_types = { 9053 .types = { 9054 PTR_TO_MAP_VALUE, 9055 PTR_TO_BTF_ID | MEM_ALLOC 9056 } 9057 }; 9058 static const struct bpf_reg_types dynptr_types = { 9059 .types = { 9060 PTR_TO_STACK, 9061 CONST_PTR_TO_DYNPTR, 9062 } 9063 }; 9064 9065 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 9066 [ARG_PTR_TO_MAP_KEY] = &mem_types, 9067 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 9068 [ARG_CONST_SIZE] = &scalar_types, 9069 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 9070 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 9071 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 9072 [ARG_PTR_TO_CTX] = &context_types, 9073 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 9074 #ifdef CONFIG_NET 9075 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 9076 #endif 9077 [ARG_PTR_TO_SOCKET] = &fullsock_types, 9078 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 9079 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 9080 [ARG_PTR_TO_MEM] = &mem_types, 9081 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 9082 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 9083 [ARG_PTR_TO_FUNC] = &func_ptr_types, 9084 [ARG_PTR_TO_STACK] = &stack_ptr_types, 9085 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 9086 [ARG_PTR_TO_TIMER] = &timer_types, 9087 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 9088 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 9089 }; 9090 9091 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 9092 enum bpf_arg_type arg_type, 9093 const u32 *arg_btf_id, 9094 struct bpf_call_arg_meta *meta) 9095 { 9096 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 9097 enum bpf_reg_type expected, type = reg->type; 9098 const struct bpf_reg_types *compatible; 9099 int i, j; 9100 9101 compatible = compatible_reg_types[base_type(arg_type)]; 9102 if (!compatible) { 9103 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 9104 return -EFAULT; 9105 } 9106 9107 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 9108 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 9109 * 9110 * Same for MAYBE_NULL: 9111 * 9112 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 9113 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 9114 * 9115 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 9116 * 9117 * Therefore we fold these flags depending on the arg_type before comparison. 9118 */ 9119 if (arg_type & MEM_RDONLY) 9120 type &= ~MEM_RDONLY; 9121 if (arg_type & PTR_MAYBE_NULL) 9122 type &= ~PTR_MAYBE_NULL; 9123 if (base_type(arg_type) == ARG_PTR_TO_MEM) 9124 type &= ~DYNPTR_TYPE_FLAG_MASK; 9125 9126 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 9127 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) { 9128 type &= ~MEM_ALLOC; 9129 type &= ~MEM_PERCPU; 9130 } 9131 9132 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 9133 expected = compatible->types[i]; 9134 if (expected == NOT_INIT) 9135 break; 9136 9137 if (type == expected) 9138 goto found; 9139 } 9140 9141 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 9142 for (j = 0; j + 1 < i; j++) 9143 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 9144 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 9145 return -EACCES; 9146 9147 found: 9148 if (base_type(reg->type) != PTR_TO_BTF_ID) 9149 return 0; 9150 9151 if (compatible == &mem_types) { 9152 if (!(arg_type & MEM_RDONLY)) { 9153 verbose(env, 9154 "%s() may write into memory pointed by R%d type=%s\n", 9155 func_id_name(meta->func_id), 9156 regno, reg_type_str(env, reg->type)); 9157 return -EACCES; 9158 } 9159 return 0; 9160 } 9161 9162 switch ((int)reg->type) { 9163 case PTR_TO_BTF_ID: 9164 case PTR_TO_BTF_ID | PTR_TRUSTED: 9165 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 9166 case PTR_TO_BTF_ID | MEM_RCU: 9167 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 9168 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 9169 { 9170 /* For bpf_sk_release, it needs to match against first member 9171 * 'struct sock_common', hence make an exception for it. This 9172 * allows bpf_sk_release to work for multiple socket types. 9173 */ 9174 bool strict_type_match = arg_type_is_release(arg_type) && 9175 meta->func_id != BPF_FUNC_sk_release; 9176 9177 if (type_may_be_null(reg->type) && 9178 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 9179 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 9180 return -EACCES; 9181 } 9182 9183 if (!arg_btf_id) { 9184 if (!compatible->btf_id) { 9185 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 9186 return -EFAULT; 9187 } 9188 arg_btf_id = compatible->btf_id; 9189 } 9190 9191 if (meta->func_id == BPF_FUNC_kptr_xchg) { 9192 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 9193 return -EACCES; 9194 } else { 9195 if (arg_btf_id == BPF_PTR_POISON) { 9196 verbose(env, "verifier internal error:"); 9197 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 9198 regno); 9199 return -EACCES; 9200 } 9201 9202 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 9203 btf_vmlinux, *arg_btf_id, 9204 strict_type_match)) { 9205 verbose(env, "R%d is of type %s but %s is expected\n", 9206 regno, btf_type_name(reg->btf, reg->btf_id), 9207 btf_type_name(btf_vmlinux, *arg_btf_id)); 9208 return -EACCES; 9209 } 9210 } 9211 break; 9212 } 9213 case PTR_TO_BTF_ID | MEM_ALLOC: 9214 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 9215 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 9216 meta->func_id != BPF_FUNC_kptr_xchg) { 9217 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 9218 return -EFAULT; 9219 } 9220 /* Check if local kptr in src arg matches kptr in dst arg */ 9221 if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) { 9222 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 9223 return -EACCES; 9224 } 9225 break; 9226 case PTR_TO_BTF_ID | MEM_PERCPU: 9227 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 9228 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 9229 /* Handled by helper specific checks */ 9230 break; 9231 default: 9232 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 9233 return -EFAULT; 9234 } 9235 return 0; 9236 } 9237 9238 static struct btf_field * 9239 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 9240 { 9241 struct btf_field *field; 9242 struct btf_record *rec; 9243 9244 rec = reg_btf_record(reg); 9245 if (!rec) 9246 return NULL; 9247 9248 field = btf_record_find(rec, off, fields); 9249 if (!field) 9250 return NULL; 9251 9252 return field; 9253 } 9254 9255 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 9256 const struct bpf_reg_state *reg, int regno, 9257 enum bpf_arg_type arg_type) 9258 { 9259 u32 type = reg->type; 9260 9261 /* When referenced register is passed to release function, its fixed 9262 * offset must be 0. 9263 * 9264 * We will check arg_type_is_release reg has ref_obj_id when storing 9265 * meta->release_regno. 9266 */ 9267 if (arg_type_is_release(arg_type)) { 9268 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 9269 * may not directly point to the object being released, but to 9270 * dynptr pointing to such object, which might be at some offset 9271 * on the stack. In that case, we simply to fallback to the 9272 * default handling. 9273 */ 9274 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 9275 return 0; 9276 9277 /* Doing check_ptr_off_reg check for the offset will catch this 9278 * because fixed_off_ok is false, but checking here allows us 9279 * to give the user a better error message. 9280 */ 9281 if (reg->off) { 9282 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 9283 regno); 9284 return -EINVAL; 9285 } 9286 return __check_ptr_off_reg(env, reg, regno, false); 9287 } 9288 9289 switch (type) { 9290 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 9291 case PTR_TO_STACK: 9292 case PTR_TO_PACKET: 9293 case PTR_TO_PACKET_META: 9294 case PTR_TO_MAP_KEY: 9295 case PTR_TO_MAP_VALUE: 9296 case PTR_TO_MEM: 9297 case PTR_TO_MEM | MEM_RDONLY: 9298 case PTR_TO_MEM | MEM_RINGBUF: 9299 case PTR_TO_BUF: 9300 case PTR_TO_BUF | MEM_RDONLY: 9301 case PTR_TO_ARENA: 9302 case SCALAR_VALUE: 9303 return 0; 9304 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 9305 * fixed offset. 9306 */ 9307 case PTR_TO_BTF_ID: 9308 case PTR_TO_BTF_ID | MEM_ALLOC: 9309 case PTR_TO_BTF_ID | PTR_TRUSTED: 9310 case PTR_TO_BTF_ID | MEM_RCU: 9311 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 9312 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 9313 /* When referenced PTR_TO_BTF_ID is passed to release function, 9314 * its fixed offset must be 0. In the other cases, fixed offset 9315 * can be non-zero. This was already checked above. So pass 9316 * fixed_off_ok as true to allow fixed offset for all other 9317 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 9318 * still need to do checks instead of returning. 9319 */ 9320 return __check_ptr_off_reg(env, reg, regno, true); 9321 default: 9322 return __check_ptr_off_reg(env, reg, regno, false); 9323 } 9324 } 9325 9326 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 9327 const struct bpf_func_proto *fn, 9328 struct bpf_reg_state *regs) 9329 { 9330 struct bpf_reg_state *state = NULL; 9331 int i; 9332 9333 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 9334 if (arg_type_is_dynptr(fn->arg_type[i])) { 9335 if (state) { 9336 verbose(env, "verifier internal error: multiple dynptr args\n"); 9337 return NULL; 9338 } 9339 state = ®s[BPF_REG_1 + i]; 9340 } 9341 9342 if (!state) 9343 verbose(env, "verifier internal error: no dynptr arg found\n"); 9344 9345 return state; 9346 } 9347 9348 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 9349 { 9350 struct bpf_func_state *state = func(env, reg); 9351 int spi; 9352 9353 if (reg->type == CONST_PTR_TO_DYNPTR) 9354 return reg->id; 9355 spi = dynptr_get_spi(env, reg); 9356 if (spi < 0) 9357 return spi; 9358 return state->stack[spi].spilled_ptr.id; 9359 } 9360 9361 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 9362 { 9363 struct bpf_func_state *state = func(env, reg); 9364 int spi; 9365 9366 if (reg->type == CONST_PTR_TO_DYNPTR) 9367 return reg->ref_obj_id; 9368 spi = dynptr_get_spi(env, reg); 9369 if (spi < 0) 9370 return spi; 9371 return state->stack[spi].spilled_ptr.ref_obj_id; 9372 } 9373 9374 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 9375 struct bpf_reg_state *reg) 9376 { 9377 struct bpf_func_state *state = func(env, reg); 9378 int spi; 9379 9380 if (reg->type == CONST_PTR_TO_DYNPTR) 9381 return reg->dynptr.type; 9382 9383 spi = __get_spi(reg->off); 9384 if (spi < 0) { 9385 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 9386 return BPF_DYNPTR_TYPE_INVALID; 9387 } 9388 9389 return state->stack[spi].spilled_ptr.dynptr.type; 9390 } 9391 9392 static int check_reg_const_str(struct bpf_verifier_env *env, 9393 struct bpf_reg_state *reg, u32 regno) 9394 { 9395 struct bpf_map *map = reg->map_ptr; 9396 int err; 9397 int map_off; 9398 u64 map_addr; 9399 char *str_ptr; 9400 9401 if (reg->type != PTR_TO_MAP_VALUE) 9402 return -EINVAL; 9403 9404 if (!bpf_map_is_rdonly(map)) { 9405 verbose(env, "R%d does not point to a readonly map'\n", regno); 9406 return -EACCES; 9407 } 9408 9409 if (!tnum_is_const(reg->var_off)) { 9410 verbose(env, "R%d is not a constant address'\n", regno); 9411 return -EACCES; 9412 } 9413 9414 if (!map->ops->map_direct_value_addr) { 9415 verbose(env, "no direct value access support for this map type\n"); 9416 return -EACCES; 9417 } 9418 9419 err = check_map_access(env, regno, reg->off, 9420 map->value_size - reg->off, false, 9421 ACCESS_HELPER); 9422 if (err) 9423 return err; 9424 9425 map_off = reg->off + reg->var_off.value; 9426 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 9427 if (err) { 9428 verbose(env, "direct value access on string failed\n"); 9429 return err; 9430 } 9431 9432 str_ptr = (char *)(long)(map_addr); 9433 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 9434 verbose(env, "string is not zero-terminated\n"); 9435 return -EINVAL; 9436 } 9437 return 0; 9438 } 9439 9440 /* Returns constant key value in `value` if possible, else negative error */ 9441 static int get_constant_map_key(struct bpf_verifier_env *env, 9442 struct bpf_reg_state *key, 9443 u32 key_size, 9444 s64 *value) 9445 { 9446 struct bpf_func_state *state = func(env, key); 9447 struct bpf_reg_state *reg; 9448 int slot, spi, off; 9449 int spill_size = 0; 9450 int zero_size = 0; 9451 int stack_off; 9452 int i, err; 9453 u8 *stype; 9454 9455 if (!env->bpf_capable) 9456 return -EOPNOTSUPP; 9457 if (key->type != PTR_TO_STACK) 9458 return -EOPNOTSUPP; 9459 if (!tnum_is_const(key->var_off)) 9460 return -EOPNOTSUPP; 9461 9462 stack_off = key->off + key->var_off.value; 9463 slot = -stack_off - 1; 9464 spi = slot / BPF_REG_SIZE; 9465 off = slot % BPF_REG_SIZE; 9466 stype = state->stack[spi].slot_type; 9467 9468 /* First handle precisely tracked STACK_ZERO */ 9469 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) 9470 zero_size++; 9471 if (zero_size >= key_size) { 9472 *value = 0; 9473 return 0; 9474 } 9475 9476 /* Check that stack contains a scalar spill of expected size */ 9477 if (!is_spilled_scalar_reg(&state->stack[spi])) 9478 return -EOPNOTSUPP; 9479 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) 9480 spill_size++; 9481 if (spill_size != key_size) 9482 return -EOPNOTSUPP; 9483 9484 reg = &state->stack[spi].spilled_ptr; 9485 if (!tnum_is_const(reg->var_off)) 9486 /* Stack value not statically known */ 9487 return -EOPNOTSUPP; 9488 9489 /* We are relying on a constant value. So mark as precise 9490 * to prevent pruning on it. 9491 */ 9492 bt_set_frame_slot(&env->bt, key->frameno, spi); 9493 err = mark_chain_precision_batch(env); 9494 if (err < 0) 9495 return err; 9496 9497 *value = reg->var_off.value; 9498 return 0; 9499 } 9500 9501 static bool can_elide_value_nullness(enum bpf_map_type type); 9502 9503 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 9504 struct bpf_call_arg_meta *meta, 9505 const struct bpf_func_proto *fn, 9506 int insn_idx) 9507 { 9508 u32 regno = BPF_REG_1 + arg; 9509 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 9510 enum bpf_arg_type arg_type = fn->arg_type[arg]; 9511 enum bpf_reg_type type = reg->type; 9512 u32 *arg_btf_id = NULL; 9513 u32 key_size; 9514 int err = 0; 9515 9516 if (arg_type == ARG_DONTCARE) 9517 return 0; 9518 9519 err = check_reg_arg(env, regno, SRC_OP); 9520 if (err) 9521 return err; 9522 9523 if (arg_type == ARG_ANYTHING) { 9524 if (is_pointer_value(env, regno)) { 9525 verbose(env, "R%d leaks addr into helper function\n", 9526 regno); 9527 return -EACCES; 9528 } 9529 return 0; 9530 } 9531 9532 if (type_is_pkt_pointer(type) && 9533 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 9534 verbose(env, "helper access to the packet is not allowed\n"); 9535 return -EACCES; 9536 } 9537 9538 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 9539 err = resolve_map_arg_type(env, meta, &arg_type); 9540 if (err) 9541 return err; 9542 } 9543 9544 if (register_is_null(reg) && type_may_be_null(arg_type)) 9545 /* A NULL register has a SCALAR_VALUE type, so skip 9546 * type checking. 9547 */ 9548 goto skip_type_check; 9549 9550 /* arg_btf_id and arg_size are in a union. */ 9551 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 9552 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 9553 arg_btf_id = fn->arg_btf_id[arg]; 9554 9555 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 9556 if (err) 9557 return err; 9558 9559 err = check_func_arg_reg_off(env, reg, regno, arg_type); 9560 if (err) 9561 return err; 9562 9563 skip_type_check: 9564 if (arg_type_is_release(arg_type)) { 9565 if (arg_type_is_dynptr(arg_type)) { 9566 struct bpf_func_state *state = func(env, reg); 9567 int spi; 9568 9569 /* Only dynptr created on stack can be released, thus 9570 * the get_spi and stack state checks for spilled_ptr 9571 * should only be done before process_dynptr_func for 9572 * PTR_TO_STACK. 9573 */ 9574 if (reg->type == PTR_TO_STACK) { 9575 spi = dynptr_get_spi(env, reg); 9576 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 9577 verbose(env, "arg %d is an unacquired reference\n", regno); 9578 return -EINVAL; 9579 } 9580 } else { 9581 verbose(env, "cannot release unowned const bpf_dynptr\n"); 9582 return -EINVAL; 9583 } 9584 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 9585 verbose(env, "R%d must be referenced when passed to release function\n", 9586 regno); 9587 return -EINVAL; 9588 } 9589 if (meta->release_regno) { 9590 verbose(env, "verifier internal error: more than one release argument\n"); 9591 return -EFAULT; 9592 } 9593 meta->release_regno = regno; 9594 } 9595 9596 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) { 9597 if (meta->ref_obj_id) { 9598 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 9599 regno, reg->ref_obj_id, 9600 meta->ref_obj_id); 9601 return -EFAULT; 9602 } 9603 meta->ref_obj_id = reg->ref_obj_id; 9604 } 9605 9606 switch (base_type(arg_type)) { 9607 case ARG_CONST_MAP_PTR: 9608 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 9609 if (meta->map_ptr) { 9610 /* Use map_uid (which is unique id of inner map) to reject: 9611 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 9612 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 9613 * if (inner_map1 && inner_map2) { 9614 * timer = bpf_map_lookup_elem(inner_map1); 9615 * if (timer) 9616 * // mismatch would have been allowed 9617 * bpf_timer_init(timer, inner_map2); 9618 * } 9619 * 9620 * Comparing map_ptr is enough to distinguish normal and outer maps. 9621 */ 9622 if (meta->map_ptr != reg->map_ptr || 9623 meta->map_uid != reg->map_uid) { 9624 verbose(env, 9625 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 9626 meta->map_uid, reg->map_uid); 9627 return -EINVAL; 9628 } 9629 } 9630 meta->map_ptr = reg->map_ptr; 9631 meta->map_uid = reg->map_uid; 9632 break; 9633 case ARG_PTR_TO_MAP_KEY: 9634 /* bpf_map_xxx(..., map_ptr, ..., key) call: 9635 * check that [key, key + map->key_size) are within 9636 * stack limits and initialized 9637 */ 9638 if (!meta->map_ptr) { 9639 /* in function declaration map_ptr must come before 9640 * map_key, so that it's verified and known before 9641 * we have to check map_key here. Otherwise it means 9642 * that kernel subsystem misconfigured verifier 9643 */ 9644 verbose(env, "invalid map_ptr to access map->key\n"); 9645 return -EACCES; 9646 } 9647 key_size = meta->map_ptr->key_size; 9648 err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL); 9649 if (err) 9650 return err; 9651 if (can_elide_value_nullness(meta->map_ptr->map_type)) { 9652 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key); 9653 if (err < 0) { 9654 meta->const_map_key = -1; 9655 if (err == -EOPNOTSUPP) 9656 err = 0; 9657 else 9658 return err; 9659 } 9660 } 9661 break; 9662 case ARG_PTR_TO_MAP_VALUE: 9663 if (type_may_be_null(arg_type) && register_is_null(reg)) 9664 return 0; 9665 9666 /* bpf_map_xxx(..., map_ptr, ..., value) call: 9667 * check [value, value + map->value_size) validity 9668 */ 9669 if (!meta->map_ptr) { 9670 /* kernel subsystem misconfigured verifier */ 9671 verbose(env, "invalid map_ptr to access map->value\n"); 9672 return -EACCES; 9673 } 9674 meta->raw_mode = arg_type & MEM_UNINIT; 9675 err = check_helper_mem_access(env, regno, meta->map_ptr->value_size, 9676 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 9677 false, meta); 9678 break; 9679 case ARG_PTR_TO_PERCPU_BTF_ID: 9680 if (!reg->btf_id) { 9681 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 9682 return -EACCES; 9683 } 9684 meta->ret_btf = reg->btf; 9685 meta->ret_btf_id = reg->btf_id; 9686 break; 9687 case ARG_PTR_TO_SPIN_LOCK: 9688 if (in_rbtree_lock_required_cb(env)) { 9689 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 9690 return -EACCES; 9691 } 9692 if (meta->func_id == BPF_FUNC_spin_lock) { 9693 err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK); 9694 if (err) 9695 return err; 9696 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 9697 err = process_spin_lock(env, regno, 0); 9698 if (err) 9699 return err; 9700 } else { 9701 verbose(env, "verifier internal error\n"); 9702 return -EFAULT; 9703 } 9704 break; 9705 case ARG_PTR_TO_TIMER: 9706 err = process_timer_func(env, regno, meta); 9707 if (err) 9708 return err; 9709 break; 9710 case ARG_PTR_TO_FUNC: 9711 meta->subprogno = reg->subprogno; 9712 break; 9713 case ARG_PTR_TO_MEM: 9714 /* The access to this pointer is only checked when we hit the 9715 * next is_mem_size argument below. 9716 */ 9717 meta->raw_mode = arg_type & MEM_UNINIT; 9718 if (arg_type & MEM_FIXED_SIZE) { 9719 err = check_helper_mem_access(env, regno, fn->arg_size[arg], 9720 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 9721 false, meta); 9722 if (err) 9723 return err; 9724 if (arg_type & MEM_ALIGNED) 9725 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 9726 } 9727 break; 9728 case ARG_CONST_SIZE: 9729 err = check_mem_size_reg(env, reg, regno, 9730 fn->arg_type[arg - 1] & MEM_WRITE ? 9731 BPF_WRITE : BPF_READ, 9732 false, meta); 9733 break; 9734 case ARG_CONST_SIZE_OR_ZERO: 9735 err = check_mem_size_reg(env, reg, regno, 9736 fn->arg_type[arg - 1] & MEM_WRITE ? 9737 BPF_WRITE : BPF_READ, 9738 true, meta); 9739 break; 9740 case ARG_PTR_TO_DYNPTR: 9741 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 9742 if (err) 9743 return err; 9744 break; 9745 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 9746 if (!tnum_is_const(reg->var_off)) { 9747 verbose(env, "R%d is not a known constant'\n", 9748 regno); 9749 return -EACCES; 9750 } 9751 meta->mem_size = reg->var_off.value; 9752 err = mark_chain_precision(env, regno); 9753 if (err) 9754 return err; 9755 break; 9756 case ARG_PTR_TO_CONST_STR: 9757 { 9758 err = check_reg_const_str(env, reg, regno); 9759 if (err) 9760 return err; 9761 break; 9762 } 9763 case ARG_KPTR_XCHG_DEST: 9764 err = process_kptr_func(env, regno, meta); 9765 if (err) 9766 return err; 9767 break; 9768 } 9769 9770 return err; 9771 } 9772 9773 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 9774 { 9775 enum bpf_attach_type eatype = env->prog->expected_attach_type; 9776 enum bpf_prog_type type = resolve_prog_type(env->prog); 9777 9778 if (func_id != BPF_FUNC_map_update_elem && 9779 func_id != BPF_FUNC_map_delete_elem) 9780 return false; 9781 9782 /* It's not possible to get access to a locked struct sock in these 9783 * contexts, so updating is safe. 9784 */ 9785 switch (type) { 9786 case BPF_PROG_TYPE_TRACING: 9787 if (eatype == BPF_TRACE_ITER) 9788 return true; 9789 break; 9790 case BPF_PROG_TYPE_SOCK_OPS: 9791 /* map_update allowed only via dedicated helpers with event type checks */ 9792 if (func_id == BPF_FUNC_map_delete_elem) 9793 return true; 9794 break; 9795 case BPF_PROG_TYPE_SOCKET_FILTER: 9796 case BPF_PROG_TYPE_SCHED_CLS: 9797 case BPF_PROG_TYPE_SCHED_ACT: 9798 case BPF_PROG_TYPE_XDP: 9799 case BPF_PROG_TYPE_SK_REUSEPORT: 9800 case BPF_PROG_TYPE_FLOW_DISSECTOR: 9801 case BPF_PROG_TYPE_SK_LOOKUP: 9802 return true; 9803 default: 9804 break; 9805 } 9806 9807 verbose(env, "cannot update sockmap in this context\n"); 9808 return false; 9809 } 9810 9811 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 9812 { 9813 return env->prog->jit_requested && 9814 bpf_jit_supports_subprog_tailcalls(); 9815 } 9816 9817 static int check_map_func_compatibility(struct bpf_verifier_env *env, 9818 struct bpf_map *map, int func_id) 9819 { 9820 if (!map) 9821 return 0; 9822 9823 /* We need a two way check, first is from map perspective ... */ 9824 switch (map->map_type) { 9825 case BPF_MAP_TYPE_PROG_ARRAY: 9826 if (func_id != BPF_FUNC_tail_call) 9827 goto error; 9828 break; 9829 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 9830 if (func_id != BPF_FUNC_perf_event_read && 9831 func_id != BPF_FUNC_perf_event_output && 9832 func_id != BPF_FUNC_skb_output && 9833 func_id != BPF_FUNC_perf_event_read_value && 9834 func_id != BPF_FUNC_xdp_output) 9835 goto error; 9836 break; 9837 case BPF_MAP_TYPE_RINGBUF: 9838 if (func_id != BPF_FUNC_ringbuf_output && 9839 func_id != BPF_FUNC_ringbuf_reserve && 9840 func_id != BPF_FUNC_ringbuf_query && 9841 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 9842 func_id != BPF_FUNC_ringbuf_submit_dynptr && 9843 func_id != BPF_FUNC_ringbuf_discard_dynptr) 9844 goto error; 9845 break; 9846 case BPF_MAP_TYPE_USER_RINGBUF: 9847 if (func_id != BPF_FUNC_user_ringbuf_drain) 9848 goto error; 9849 break; 9850 case BPF_MAP_TYPE_STACK_TRACE: 9851 if (func_id != BPF_FUNC_get_stackid) 9852 goto error; 9853 break; 9854 case BPF_MAP_TYPE_CGROUP_ARRAY: 9855 if (func_id != BPF_FUNC_skb_under_cgroup && 9856 func_id != BPF_FUNC_current_task_under_cgroup) 9857 goto error; 9858 break; 9859 case BPF_MAP_TYPE_CGROUP_STORAGE: 9860 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 9861 if (func_id != BPF_FUNC_get_local_storage) 9862 goto error; 9863 break; 9864 case BPF_MAP_TYPE_DEVMAP: 9865 case BPF_MAP_TYPE_DEVMAP_HASH: 9866 if (func_id != BPF_FUNC_redirect_map && 9867 func_id != BPF_FUNC_map_lookup_elem) 9868 goto error; 9869 break; 9870 /* Restrict bpf side of cpumap and xskmap, open when use-cases 9871 * appear. 9872 */ 9873 case BPF_MAP_TYPE_CPUMAP: 9874 if (func_id != BPF_FUNC_redirect_map) 9875 goto error; 9876 break; 9877 case BPF_MAP_TYPE_XSKMAP: 9878 if (func_id != BPF_FUNC_redirect_map && 9879 func_id != BPF_FUNC_map_lookup_elem) 9880 goto error; 9881 break; 9882 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 9883 case BPF_MAP_TYPE_HASH_OF_MAPS: 9884 if (func_id != BPF_FUNC_map_lookup_elem) 9885 goto error; 9886 break; 9887 case BPF_MAP_TYPE_SOCKMAP: 9888 if (func_id != BPF_FUNC_sk_redirect_map && 9889 func_id != BPF_FUNC_sock_map_update && 9890 func_id != BPF_FUNC_msg_redirect_map && 9891 func_id != BPF_FUNC_sk_select_reuseport && 9892 func_id != BPF_FUNC_map_lookup_elem && 9893 !may_update_sockmap(env, func_id)) 9894 goto error; 9895 break; 9896 case BPF_MAP_TYPE_SOCKHASH: 9897 if (func_id != BPF_FUNC_sk_redirect_hash && 9898 func_id != BPF_FUNC_sock_hash_update && 9899 func_id != BPF_FUNC_msg_redirect_hash && 9900 func_id != BPF_FUNC_sk_select_reuseport && 9901 func_id != BPF_FUNC_map_lookup_elem && 9902 !may_update_sockmap(env, func_id)) 9903 goto error; 9904 break; 9905 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 9906 if (func_id != BPF_FUNC_sk_select_reuseport) 9907 goto error; 9908 break; 9909 case BPF_MAP_TYPE_QUEUE: 9910 case BPF_MAP_TYPE_STACK: 9911 if (func_id != BPF_FUNC_map_peek_elem && 9912 func_id != BPF_FUNC_map_pop_elem && 9913 func_id != BPF_FUNC_map_push_elem) 9914 goto error; 9915 break; 9916 case BPF_MAP_TYPE_SK_STORAGE: 9917 if (func_id != BPF_FUNC_sk_storage_get && 9918 func_id != BPF_FUNC_sk_storage_delete && 9919 func_id != BPF_FUNC_kptr_xchg) 9920 goto error; 9921 break; 9922 case BPF_MAP_TYPE_INODE_STORAGE: 9923 if (func_id != BPF_FUNC_inode_storage_get && 9924 func_id != BPF_FUNC_inode_storage_delete && 9925 func_id != BPF_FUNC_kptr_xchg) 9926 goto error; 9927 break; 9928 case BPF_MAP_TYPE_TASK_STORAGE: 9929 if (func_id != BPF_FUNC_task_storage_get && 9930 func_id != BPF_FUNC_task_storage_delete && 9931 func_id != BPF_FUNC_kptr_xchg) 9932 goto error; 9933 break; 9934 case BPF_MAP_TYPE_CGRP_STORAGE: 9935 if (func_id != BPF_FUNC_cgrp_storage_get && 9936 func_id != BPF_FUNC_cgrp_storage_delete && 9937 func_id != BPF_FUNC_kptr_xchg) 9938 goto error; 9939 break; 9940 case BPF_MAP_TYPE_BLOOM_FILTER: 9941 if (func_id != BPF_FUNC_map_peek_elem && 9942 func_id != BPF_FUNC_map_push_elem) 9943 goto error; 9944 break; 9945 default: 9946 break; 9947 } 9948 9949 /* ... and second from the function itself. */ 9950 switch (func_id) { 9951 case BPF_FUNC_tail_call: 9952 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 9953 goto error; 9954 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 9955 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n"); 9956 return -EINVAL; 9957 } 9958 break; 9959 case BPF_FUNC_perf_event_read: 9960 case BPF_FUNC_perf_event_output: 9961 case BPF_FUNC_perf_event_read_value: 9962 case BPF_FUNC_skb_output: 9963 case BPF_FUNC_xdp_output: 9964 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 9965 goto error; 9966 break; 9967 case BPF_FUNC_ringbuf_output: 9968 case BPF_FUNC_ringbuf_reserve: 9969 case BPF_FUNC_ringbuf_query: 9970 case BPF_FUNC_ringbuf_reserve_dynptr: 9971 case BPF_FUNC_ringbuf_submit_dynptr: 9972 case BPF_FUNC_ringbuf_discard_dynptr: 9973 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 9974 goto error; 9975 break; 9976 case BPF_FUNC_user_ringbuf_drain: 9977 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 9978 goto error; 9979 break; 9980 case BPF_FUNC_get_stackid: 9981 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 9982 goto error; 9983 break; 9984 case BPF_FUNC_current_task_under_cgroup: 9985 case BPF_FUNC_skb_under_cgroup: 9986 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 9987 goto error; 9988 break; 9989 case BPF_FUNC_redirect_map: 9990 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 9991 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 9992 map->map_type != BPF_MAP_TYPE_CPUMAP && 9993 map->map_type != BPF_MAP_TYPE_XSKMAP) 9994 goto error; 9995 break; 9996 case BPF_FUNC_sk_redirect_map: 9997 case BPF_FUNC_msg_redirect_map: 9998 case BPF_FUNC_sock_map_update: 9999 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 10000 goto error; 10001 break; 10002 case BPF_FUNC_sk_redirect_hash: 10003 case BPF_FUNC_msg_redirect_hash: 10004 case BPF_FUNC_sock_hash_update: 10005 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 10006 goto error; 10007 break; 10008 case BPF_FUNC_get_local_storage: 10009 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 10010 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 10011 goto error; 10012 break; 10013 case BPF_FUNC_sk_select_reuseport: 10014 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 10015 map->map_type != BPF_MAP_TYPE_SOCKMAP && 10016 map->map_type != BPF_MAP_TYPE_SOCKHASH) 10017 goto error; 10018 break; 10019 case BPF_FUNC_map_pop_elem: 10020 if (map->map_type != BPF_MAP_TYPE_QUEUE && 10021 map->map_type != BPF_MAP_TYPE_STACK) 10022 goto error; 10023 break; 10024 case BPF_FUNC_map_peek_elem: 10025 case BPF_FUNC_map_push_elem: 10026 if (map->map_type != BPF_MAP_TYPE_QUEUE && 10027 map->map_type != BPF_MAP_TYPE_STACK && 10028 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 10029 goto error; 10030 break; 10031 case BPF_FUNC_map_lookup_percpu_elem: 10032 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 10033 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 10034 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 10035 goto error; 10036 break; 10037 case BPF_FUNC_sk_storage_get: 10038 case BPF_FUNC_sk_storage_delete: 10039 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 10040 goto error; 10041 break; 10042 case BPF_FUNC_inode_storage_get: 10043 case BPF_FUNC_inode_storage_delete: 10044 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 10045 goto error; 10046 break; 10047 case BPF_FUNC_task_storage_get: 10048 case BPF_FUNC_task_storage_delete: 10049 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 10050 goto error; 10051 break; 10052 case BPF_FUNC_cgrp_storage_get: 10053 case BPF_FUNC_cgrp_storage_delete: 10054 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 10055 goto error; 10056 break; 10057 default: 10058 break; 10059 } 10060 10061 return 0; 10062 error: 10063 verbose(env, "cannot pass map_type %d into func %s#%d\n", 10064 map->map_type, func_id_name(func_id), func_id); 10065 return -EINVAL; 10066 } 10067 10068 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 10069 { 10070 int count = 0; 10071 10072 if (arg_type_is_raw_mem(fn->arg1_type)) 10073 count++; 10074 if (arg_type_is_raw_mem(fn->arg2_type)) 10075 count++; 10076 if (arg_type_is_raw_mem(fn->arg3_type)) 10077 count++; 10078 if (arg_type_is_raw_mem(fn->arg4_type)) 10079 count++; 10080 if (arg_type_is_raw_mem(fn->arg5_type)) 10081 count++; 10082 10083 /* We only support one arg being in raw mode at the moment, 10084 * which is sufficient for the helper functions we have 10085 * right now. 10086 */ 10087 return count <= 1; 10088 } 10089 10090 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 10091 { 10092 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 10093 bool has_size = fn->arg_size[arg] != 0; 10094 bool is_next_size = false; 10095 10096 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 10097 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 10098 10099 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 10100 return is_next_size; 10101 10102 return has_size == is_next_size || is_next_size == is_fixed; 10103 } 10104 10105 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 10106 { 10107 /* bpf_xxx(..., buf, len) call will access 'len' 10108 * bytes from memory 'buf'. Both arg types need 10109 * to be paired, so make sure there's no buggy 10110 * helper function specification. 10111 */ 10112 if (arg_type_is_mem_size(fn->arg1_type) || 10113 check_args_pair_invalid(fn, 0) || 10114 check_args_pair_invalid(fn, 1) || 10115 check_args_pair_invalid(fn, 2) || 10116 check_args_pair_invalid(fn, 3) || 10117 check_args_pair_invalid(fn, 4)) 10118 return false; 10119 10120 return true; 10121 } 10122 10123 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 10124 { 10125 int i; 10126 10127 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 10128 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 10129 return !!fn->arg_btf_id[i]; 10130 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 10131 return fn->arg_btf_id[i] == BPF_PTR_POISON; 10132 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 10133 /* arg_btf_id and arg_size are in a union. */ 10134 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 10135 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 10136 return false; 10137 } 10138 10139 return true; 10140 } 10141 10142 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 10143 { 10144 return check_raw_mode_ok(fn) && 10145 check_arg_pair_ok(fn) && 10146 check_btf_id_ok(fn) ? 0 : -EINVAL; 10147 } 10148 10149 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 10150 * are now invalid, so turn them into unknown SCALAR_VALUE. 10151 * 10152 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 10153 * since these slices point to packet data. 10154 */ 10155 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 10156 { 10157 struct bpf_func_state *state; 10158 struct bpf_reg_state *reg; 10159 10160 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10161 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 10162 mark_reg_invalid(env, reg); 10163 })); 10164 } 10165 10166 enum { 10167 AT_PKT_END = -1, 10168 BEYOND_PKT_END = -2, 10169 }; 10170 10171 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 10172 { 10173 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 10174 struct bpf_reg_state *reg = &state->regs[regn]; 10175 10176 if (reg->type != PTR_TO_PACKET) 10177 /* PTR_TO_PACKET_META is not supported yet */ 10178 return; 10179 10180 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 10181 * How far beyond pkt_end it goes is unknown. 10182 * if (!range_open) it's the case of pkt >= pkt_end 10183 * if (range_open) it's the case of pkt > pkt_end 10184 * hence this pointer is at least 1 byte bigger than pkt_end 10185 */ 10186 if (range_open) 10187 reg->range = BEYOND_PKT_END; 10188 else 10189 reg->range = AT_PKT_END; 10190 } 10191 10192 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id) 10193 { 10194 int i; 10195 10196 for (i = 0; i < state->acquired_refs; i++) { 10197 if (state->refs[i].type != REF_TYPE_PTR) 10198 continue; 10199 if (state->refs[i].id == ref_obj_id) { 10200 release_reference_state(state, i); 10201 return 0; 10202 } 10203 } 10204 return -EINVAL; 10205 } 10206 10207 /* The pointer with the specified id has released its reference to kernel 10208 * resources. Identify all copies of the same pointer and clear the reference. 10209 * 10210 * This is the release function corresponding to acquire_reference(). Idempotent. 10211 */ 10212 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id) 10213 { 10214 struct bpf_verifier_state *vstate = env->cur_state; 10215 struct bpf_func_state *state; 10216 struct bpf_reg_state *reg; 10217 int err; 10218 10219 err = release_reference_nomark(vstate, ref_obj_id); 10220 if (err) 10221 return err; 10222 10223 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 10224 if (reg->ref_obj_id == ref_obj_id) 10225 mark_reg_invalid(env, reg); 10226 })); 10227 10228 return 0; 10229 } 10230 10231 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 10232 { 10233 struct bpf_func_state *unused; 10234 struct bpf_reg_state *reg; 10235 10236 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10237 if (type_is_non_owning_ref(reg->type)) 10238 mark_reg_invalid(env, reg); 10239 })); 10240 } 10241 10242 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 10243 struct bpf_reg_state *regs) 10244 { 10245 int i; 10246 10247 /* after the call registers r0 - r5 were scratched */ 10248 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10249 mark_reg_not_init(env, regs, caller_saved[i]); 10250 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 10251 } 10252 } 10253 10254 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 10255 struct bpf_func_state *caller, 10256 struct bpf_func_state *callee, 10257 int insn_idx); 10258 10259 static int set_callee_state(struct bpf_verifier_env *env, 10260 struct bpf_func_state *caller, 10261 struct bpf_func_state *callee, int insn_idx); 10262 10263 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 10264 set_callee_state_fn set_callee_state_cb, 10265 struct bpf_verifier_state *state) 10266 { 10267 struct bpf_func_state *caller, *callee; 10268 int err; 10269 10270 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 10271 verbose(env, "the call stack of %d frames is too deep\n", 10272 state->curframe + 2); 10273 return -E2BIG; 10274 } 10275 10276 if (state->frame[state->curframe + 1]) { 10277 verifier_bug(env, "Frame %d already allocated", state->curframe + 1); 10278 return -EFAULT; 10279 } 10280 10281 caller = state->frame[state->curframe]; 10282 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 10283 if (!callee) 10284 return -ENOMEM; 10285 state->frame[state->curframe + 1] = callee; 10286 10287 /* callee cannot access r0, r6 - r9 for reading and has to write 10288 * into its own stack before reading from it. 10289 * callee can read/write into caller's stack 10290 */ 10291 init_func_state(env, callee, 10292 /* remember the callsite, it will be used by bpf_exit */ 10293 callsite, 10294 state->curframe + 1 /* frameno within this callchain */, 10295 subprog /* subprog number within this prog */); 10296 err = set_callee_state_cb(env, caller, callee, callsite); 10297 if (err) 10298 goto err_out; 10299 10300 /* only increment it after check_reg_arg() finished */ 10301 state->curframe++; 10302 10303 return 0; 10304 10305 err_out: 10306 free_func_state(callee); 10307 state->frame[state->curframe + 1] = NULL; 10308 return err; 10309 } 10310 10311 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 10312 const struct btf *btf, 10313 struct bpf_reg_state *regs) 10314 { 10315 struct bpf_subprog_info *sub = subprog_info(env, subprog); 10316 struct bpf_verifier_log *log = &env->log; 10317 u32 i; 10318 int ret; 10319 10320 ret = btf_prepare_func_args(env, subprog); 10321 if (ret) 10322 return ret; 10323 10324 /* check that BTF function arguments match actual types that the 10325 * verifier sees. 10326 */ 10327 for (i = 0; i < sub->arg_cnt; i++) { 10328 u32 regno = i + 1; 10329 struct bpf_reg_state *reg = ®s[regno]; 10330 struct bpf_subprog_arg_info *arg = &sub->args[i]; 10331 10332 if (arg->arg_type == ARG_ANYTHING) { 10333 if (reg->type != SCALAR_VALUE) { 10334 bpf_log(log, "R%d is not a scalar\n", regno); 10335 return -EINVAL; 10336 } 10337 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 10338 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 10339 if (ret < 0) 10340 return ret; 10341 /* If function expects ctx type in BTF check that caller 10342 * is passing PTR_TO_CTX. 10343 */ 10344 if (reg->type != PTR_TO_CTX) { 10345 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 10346 return -EINVAL; 10347 } 10348 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 10349 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 10350 if (ret < 0) 10351 return ret; 10352 if (check_mem_reg(env, reg, regno, arg->mem_size)) 10353 return -EINVAL; 10354 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 10355 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 10356 return -EINVAL; 10357 } 10358 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 10359 /* 10360 * Can pass any value and the kernel won't crash, but 10361 * only PTR_TO_ARENA or SCALAR make sense. Everything 10362 * else is a bug in the bpf program. Point it out to 10363 * the user at the verification time instead of 10364 * run-time debug nightmare. 10365 */ 10366 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 10367 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 10368 return -EINVAL; 10369 } 10370 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 10371 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR); 10372 if (ret) 10373 return ret; 10374 10375 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 10376 if (ret) 10377 return ret; 10378 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 10379 struct bpf_call_arg_meta meta; 10380 int err; 10381 10382 if (register_is_null(reg) && type_may_be_null(arg->arg_type)) 10383 continue; 10384 10385 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 10386 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 10387 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 10388 if (err) 10389 return err; 10390 } else { 10391 verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type); 10392 return -EFAULT; 10393 } 10394 } 10395 10396 return 0; 10397 } 10398 10399 /* Compare BTF of a function call with given bpf_reg_state. 10400 * Returns: 10401 * EFAULT - there is a verifier bug. Abort verification. 10402 * EINVAL - there is a type mismatch or BTF is not available. 10403 * 0 - BTF matches with what bpf_reg_state expects. 10404 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 10405 */ 10406 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 10407 struct bpf_reg_state *regs) 10408 { 10409 struct bpf_prog *prog = env->prog; 10410 struct btf *btf = prog->aux->btf; 10411 u32 btf_id; 10412 int err; 10413 10414 if (!prog->aux->func_info) 10415 return -EINVAL; 10416 10417 btf_id = prog->aux->func_info[subprog].type_id; 10418 if (!btf_id) 10419 return -EFAULT; 10420 10421 if (prog->aux->func_info_aux[subprog].unreliable) 10422 return -EINVAL; 10423 10424 err = btf_check_func_arg_match(env, subprog, btf, regs); 10425 /* Compiler optimizations can remove arguments from static functions 10426 * or mismatched type can be passed into a global function. 10427 * In such cases mark the function as unreliable from BTF point of view. 10428 */ 10429 if (err) 10430 prog->aux->func_info_aux[subprog].unreliable = true; 10431 return err; 10432 } 10433 10434 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10435 int insn_idx, int subprog, 10436 set_callee_state_fn set_callee_state_cb) 10437 { 10438 struct bpf_verifier_state *state = env->cur_state, *callback_state; 10439 struct bpf_func_state *caller, *callee; 10440 int err; 10441 10442 caller = state->frame[state->curframe]; 10443 err = btf_check_subprog_call(env, subprog, caller->regs); 10444 if (err == -EFAULT) 10445 return err; 10446 10447 /* set_callee_state is used for direct subprog calls, but we are 10448 * interested in validating only BPF helpers that can call subprogs as 10449 * callbacks 10450 */ 10451 env->subprog_info[subprog].is_cb = true; 10452 if (bpf_pseudo_kfunc_call(insn) && 10453 !is_callback_calling_kfunc(insn->imm)) { 10454 verifier_bug(env, "kfunc %s#%d not marked as callback-calling", 10455 func_id_name(insn->imm), insn->imm); 10456 return -EFAULT; 10457 } else if (!bpf_pseudo_kfunc_call(insn) && 10458 !is_callback_calling_function(insn->imm)) { /* helper */ 10459 verifier_bug(env, "helper %s#%d not marked as callback-calling", 10460 func_id_name(insn->imm), insn->imm); 10461 return -EFAULT; 10462 } 10463 10464 if (is_async_callback_calling_insn(insn)) { 10465 struct bpf_verifier_state *async_cb; 10466 10467 /* there is no real recursion here. timer and workqueue callbacks are async */ 10468 env->subprog_info[subprog].is_async_cb = true; 10469 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 10470 insn_idx, subprog, 10471 is_bpf_wq_set_callback_impl_kfunc(insn->imm)); 10472 if (!async_cb) 10473 return -EFAULT; 10474 callee = async_cb->frame[0]; 10475 callee->async_entry_cnt = caller->async_entry_cnt + 1; 10476 10477 /* Convert bpf_timer_set_callback() args into timer callback args */ 10478 err = set_callee_state_cb(env, caller, callee, insn_idx); 10479 if (err) 10480 return err; 10481 10482 return 0; 10483 } 10484 10485 /* for callback functions enqueue entry to callback and 10486 * proceed with next instruction within current frame. 10487 */ 10488 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 10489 if (!callback_state) 10490 return -ENOMEM; 10491 10492 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 10493 callback_state); 10494 if (err) 10495 return err; 10496 10497 callback_state->callback_unroll_depth++; 10498 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 10499 caller->callback_depth = 0; 10500 return 0; 10501 } 10502 10503 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10504 int *insn_idx) 10505 { 10506 struct bpf_verifier_state *state = env->cur_state; 10507 struct bpf_func_state *caller; 10508 int err, subprog, target_insn; 10509 10510 target_insn = *insn_idx + insn->imm + 1; 10511 subprog = find_subprog(env, target_insn); 10512 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program", 10513 target_insn)) 10514 return -EFAULT; 10515 10516 caller = state->frame[state->curframe]; 10517 err = btf_check_subprog_call(env, subprog, caller->regs); 10518 if (err == -EFAULT) 10519 return err; 10520 if (subprog_is_global(env, subprog)) { 10521 const char *sub_name = subprog_name(env, subprog); 10522 10523 if (env->cur_state->active_locks) { 10524 verbose(env, "global function calls are not allowed while holding a lock,\n" 10525 "use static function instead\n"); 10526 return -EINVAL; 10527 } 10528 10529 if (env->subprog_info[subprog].might_sleep && 10530 (env->cur_state->active_rcu_lock || env->cur_state->active_preempt_locks || 10531 env->cur_state->active_irq_id || !in_sleepable(env))) { 10532 verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n" 10533 "i.e., in a RCU/IRQ/preempt-disabled section, or in\n" 10534 "a non-sleepable BPF program context\n"); 10535 return -EINVAL; 10536 } 10537 10538 if (err) { 10539 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 10540 subprog, sub_name); 10541 return err; 10542 } 10543 10544 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 10545 subprog, sub_name); 10546 if (env->subprog_info[subprog].changes_pkt_data) 10547 clear_all_pkt_pointers(env); 10548 /* mark global subprog for verifying after main prog */ 10549 subprog_aux(env, subprog)->called = true; 10550 clear_caller_saved_regs(env, caller->regs); 10551 10552 /* All global functions return a 64-bit SCALAR_VALUE */ 10553 mark_reg_unknown(env, caller->regs, BPF_REG_0); 10554 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10555 10556 /* continue with next insn after call */ 10557 return 0; 10558 } 10559 10560 /* for regular function entry setup new frame and continue 10561 * from that frame. 10562 */ 10563 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 10564 if (err) 10565 return err; 10566 10567 clear_caller_saved_regs(env, caller->regs); 10568 10569 /* and go analyze first insn of the callee */ 10570 *insn_idx = env->subprog_info[subprog].start - 1; 10571 10572 if (env->log.level & BPF_LOG_LEVEL) { 10573 verbose(env, "caller:\n"); 10574 print_verifier_state(env, state, caller->frameno, true); 10575 verbose(env, "callee:\n"); 10576 print_verifier_state(env, state, state->curframe, true); 10577 } 10578 10579 return 0; 10580 } 10581 10582 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 10583 struct bpf_func_state *caller, 10584 struct bpf_func_state *callee) 10585 { 10586 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 10587 * void *callback_ctx, u64 flags); 10588 * callback_fn(struct bpf_map *map, void *key, void *value, 10589 * void *callback_ctx); 10590 */ 10591 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 10592 10593 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 10594 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10595 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 10596 10597 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 10598 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 10599 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 10600 10601 /* pointer to stack or null */ 10602 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 10603 10604 /* unused */ 10605 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10606 return 0; 10607 } 10608 10609 static int set_callee_state(struct bpf_verifier_env *env, 10610 struct bpf_func_state *caller, 10611 struct bpf_func_state *callee, int insn_idx) 10612 { 10613 int i; 10614 10615 /* copy r1 - r5 args that callee can access. The copy includes parent 10616 * pointers, which connects us up to the liveness chain 10617 */ 10618 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 10619 callee->regs[i] = caller->regs[i]; 10620 return 0; 10621 } 10622 10623 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 10624 struct bpf_func_state *caller, 10625 struct bpf_func_state *callee, 10626 int insn_idx) 10627 { 10628 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 10629 struct bpf_map *map; 10630 int err; 10631 10632 /* valid map_ptr and poison value does not matter */ 10633 map = insn_aux->map_ptr_state.map_ptr; 10634 if (!map->ops->map_set_for_each_callback_args || 10635 !map->ops->map_for_each_callback) { 10636 verbose(env, "callback function not allowed for map\n"); 10637 return -ENOTSUPP; 10638 } 10639 10640 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 10641 if (err) 10642 return err; 10643 10644 callee->in_callback_fn = true; 10645 callee->callback_ret_range = retval_range(0, 1); 10646 return 0; 10647 } 10648 10649 static int set_loop_callback_state(struct bpf_verifier_env *env, 10650 struct bpf_func_state *caller, 10651 struct bpf_func_state *callee, 10652 int insn_idx) 10653 { 10654 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 10655 * u64 flags); 10656 * callback_fn(u64 index, void *callback_ctx); 10657 */ 10658 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 10659 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 10660 10661 /* unused */ 10662 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10663 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10664 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10665 10666 callee->in_callback_fn = true; 10667 callee->callback_ret_range = retval_range(0, 1); 10668 return 0; 10669 } 10670 10671 static int set_timer_callback_state(struct bpf_verifier_env *env, 10672 struct bpf_func_state *caller, 10673 struct bpf_func_state *callee, 10674 int insn_idx) 10675 { 10676 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 10677 10678 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 10679 * callback_fn(struct bpf_map *map, void *key, void *value); 10680 */ 10681 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 10682 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 10683 callee->regs[BPF_REG_1].map_ptr = map_ptr; 10684 10685 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 10686 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10687 callee->regs[BPF_REG_2].map_ptr = map_ptr; 10688 10689 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 10690 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 10691 callee->regs[BPF_REG_3].map_ptr = map_ptr; 10692 10693 /* unused */ 10694 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10695 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10696 callee->in_async_callback_fn = true; 10697 callee->callback_ret_range = retval_range(0, 1); 10698 return 0; 10699 } 10700 10701 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 10702 struct bpf_func_state *caller, 10703 struct bpf_func_state *callee, 10704 int insn_idx) 10705 { 10706 /* bpf_find_vma(struct task_struct *task, u64 addr, 10707 * void *callback_fn, void *callback_ctx, u64 flags) 10708 * (callback_fn)(struct task_struct *task, 10709 * struct vm_area_struct *vma, void *callback_ctx); 10710 */ 10711 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 10712 10713 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 10714 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10715 callee->regs[BPF_REG_2].btf = btf_vmlinux; 10716 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 10717 10718 /* pointer to stack or null */ 10719 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 10720 10721 /* unused */ 10722 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10723 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10724 callee->in_callback_fn = true; 10725 callee->callback_ret_range = retval_range(0, 1); 10726 return 0; 10727 } 10728 10729 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 10730 struct bpf_func_state *caller, 10731 struct bpf_func_state *callee, 10732 int insn_idx) 10733 { 10734 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 10735 * callback_ctx, u64 flags); 10736 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 10737 */ 10738 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 10739 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 10740 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 10741 10742 /* unused */ 10743 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10744 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10745 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10746 10747 callee->in_callback_fn = true; 10748 callee->callback_ret_range = retval_range(0, 1); 10749 return 0; 10750 } 10751 10752 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 10753 struct bpf_func_state *caller, 10754 struct bpf_func_state *callee, 10755 int insn_idx) 10756 { 10757 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 10758 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 10759 * 10760 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 10761 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 10762 * by this point, so look at 'root' 10763 */ 10764 struct btf_field *field; 10765 10766 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 10767 BPF_RB_ROOT); 10768 if (!field || !field->graph_root.value_btf_id) 10769 return -EFAULT; 10770 10771 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 10772 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 10773 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 10774 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 10775 10776 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10777 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10778 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10779 callee->in_callback_fn = true; 10780 callee->callback_ret_range = retval_range(0, 1); 10781 return 0; 10782 } 10783 10784 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 10785 10786 /* Are we currently verifying the callback for a rbtree helper that must 10787 * be called with lock held? If so, no need to complain about unreleased 10788 * lock 10789 */ 10790 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 10791 { 10792 struct bpf_verifier_state *state = env->cur_state; 10793 struct bpf_insn *insn = env->prog->insnsi; 10794 struct bpf_func_state *callee; 10795 int kfunc_btf_id; 10796 10797 if (!state->curframe) 10798 return false; 10799 10800 callee = state->frame[state->curframe]; 10801 10802 if (!callee->in_callback_fn) 10803 return false; 10804 10805 kfunc_btf_id = insn[callee->callsite].imm; 10806 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 10807 } 10808 10809 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg, 10810 bool return_32bit) 10811 { 10812 if (return_32bit) 10813 return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval; 10814 else 10815 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 10816 } 10817 10818 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 10819 { 10820 struct bpf_verifier_state *state = env->cur_state, *prev_st; 10821 struct bpf_func_state *caller, *callee; 10822 struct bpf_reg_state *r0; 10823 bool in_callback_fn; 10824 int err; 10825 10826 callee = state->frame[state->curframe]; 10827 r0 = &callee->regs[BPF_REG_0]; 10828 if (r0->type == PTR_TO_STACK) { 10829 /* technically it's ok to return caller's stack pointer 10830 * (or caller's caller's pointer) back to the caller, 10831 * since these pointers are valid. Only current stack 10832 * pointer will be invalid as soon as function exits, 10833 * but let's be conservative 10834 */ 10835 verbose(env, "cannot return stack pointer to the caller\n"); 10836 return -EINVAL; 10837 } 10838 10839 caller = state->frame[state->curframe - 1]; 10840 if (callee->in_callback_fn) { 10841 if (r0->type != SCALAR_VALUE) { 10842 verbose(env, "R0 not a scalar value\n"); 10843 return -EACCES; 10844 } 10845 10846 /* we are going to rely on register's precise value */ 10847 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 10848 err = err ?: mark_chain_precision(env, BPF_REG_0); 10849 if (err) 10850 return err; 10851 10852 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 10853 if (!retval_range_within(callee->callback_ret_range, r0, false)) { 10854 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 10855 "At callback return", "R0"); 10856 return -EINVAL; 10857 } 10858 if (!calls_callback(env, callee->callsite)) { 10859 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 10860 *insn_idx, callee->callsite); 10861 return -EFAULT; 10862 } 10863 } else { 10864 /* return to the caller whatever r0 had in the callee */ 10865 caller->regs[BPF_REG_0] = *r0; 10866 } 10867 10868 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 10869 * there function call logic would reschedule callback visit. If iteration 10870 * converges is_state_visited() would prune that visit eventually. 10871 */ 10872 in_callback_fn = callee->in_callback_fn; 10873 if (in_callback_fn) 10874 *insn_idx = callee->callsite; 10875 else 10876 *insn_idx = callee->callsite + 1; 10877 10878 if (env->log.level & BPF_LOG_LEVEL) { 10879 verbose(env, "returning from callee:\n"); 10880 print_verifier_state(env, state, callee->frameno, true); 10881 verbose(env, "to caller at %d:\n", *insn_idx); 10882 print_verifier_state(env, state, caller->frameno, true); 10883 } 10884 /* clear everything in the callee. In case of exceptional exits using 10885 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 10886 free_func_state(callee); 10887 state->frame[state->curframe--] = NULL; 10888 10889 /* for callbacks widen imprecise scalars to make programs like below verify: 10890 * 10891 * struct ctx { int i; } 10892 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 10893 * ... 10894 * struct ctx = { .i = 0; } 10895 * bpf_loop(100, cb, &ctx, 0); 10896 * 10897 * This is similar to what is done in process_iter_next_call() for open 10898 * coded iterators. 10899 */ 10900 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 10901 if (prev_st) { 10902 err = widen_imprecise_scalars(env, prev_st, state); 10903 if (err) 10904 return err; 10905 } 10906 return 0; 10907 } 10908 10909 static int do_refine_retval_range(struct bpf_verifier_env *env, 10910 struct bpf_reg_state *regs, int ret_type, 10911 int func_id, 10912 struct bpf_call_arg_meta *meta) 10913 { 10914 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 10915 10916 if (ret_type != RET_INTEGER) 10917 return 0; 10918 10919 switch (func_id) { 10920 case BPF_FUNC_get_stack: 10921 case BPF_FUNC_get_task_stack: 10922 case BPF_FUNC_probe_read_str: 10923 case BPF_FUNC_probe_read_kernel_str: 10924 case BPF_FUNC_probe_read_user_str: 10925 ret_reg->smax_value = meta->msize_max_value; 10926 ret_reg->s32_max_value = meta->msize_max_value; 10927 ret_reg->smin_value = -MAX_ERRNO; 10928 ret_reg->s32_min_value = -MAX_ERRNO; 10929 reg_bounds_sync(ret_reg); 10930 break; 10931 case BPF_FUNC_get_smp_processor_id: 10932 ret_reg->umax_value = nr_cpu_ids - 1; 10933 ret_reg->u32_max_value = nr_cpu_ids - 1; 10934 ret_reg->smax_value = nr_cpu_ids - 1; 10935 ret_reg->s32_max_value = nr_cpu_ids - 1; 10936 ret_reg->umin_value = 0; 10937 ret_reg->u32_min_value = 0; 10938 ret_reg->smin_value = 0; 10939 ret_reg->s32_min_value = 0; 10940 reg_bounds_sync(ret_reg); 10941 break; 10942 } 10943 10944 return reg_bounds_sanity_check(env, ret_reg, "retval"); 10945 } 10946 10947 static int 10948 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10949 int func_id, int insn_idx) 10950 { 10951 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10952 struct bpf_map *map = meta->map_ptr; 10953 10954 if (func_id != BPF_FUNC_tail_call && 10955 func_id != BPF_FUNC_map_lookup_elem && 10956 func_id != BPF_FUNC_map_update_elem && 10957 func_id != BPF_FUNC_map_delete_elem && 10958 func_id != BPF_FUNC_map_push_elem && 10959 func_id != BPF_FUNC_map_pop_elem && 10960 func_id != BPF_FUNC_map_peek_elem && 10961 func_id != BPF_FUNC_for_each_map_elem && 10962 func_id != BPF_FUNC_redirect_map && 10963 func_id != BPF_FUNC_map_lookup_percpu_elem) 10964 return 0; 10965 10966 if (map == NULL) { 10967 verbose(env, "kernel subsystem misconfigured verifier\n"); 10968 return -EINVAL; 10969 } 10970 10971 /* In case of read-only, some additional restrictions 10972 * need to be applied in order to prevent altering the 10973 * state of the map from program side. 10974 */ 10975 if ((map->map_flags & BPF_F_RDONLY_PROG) && 10976 (func_id == BPF_FUNC_map_delete_elem || 10977 func_id == BPF_FUNC_map_update_elem || 10978 func_id == BPF_FUNC_map_push_elem || 10979 func_id == BPF_FUNC_map_pop_elem)) { 10980 verbose(env, "write into map forbidden\n"); 10981 return -EACCES; 10982 } 10983 10984 if (!aux->map_ptr_state.map_ptr) 10985 bpf_map_ptr_store(aux, meta->map_ptr, 10986 !meta->map_ptr->bypass_spec_v1, false); 10987 else if (aux->map_ptr_state.map_ptr != meta->map_ptr) 10988 bpf_map_ptr_store(aux, meta->map_ptr, 10989 !meta->map_ptr->bypass_spec_v1, true); 10990 return 0; 10991 } 10992 10993 static int 10994 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10995 int func_id, int insn_idx) 10996 { 10997 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10998 struct bpf_reg_state *regs = cur_regs(env), *reg; 10999 struct bpf_map *map = meta->map_ptr; 11000 u64 val, max; 11001 int err; 11002 11003 if (func_id != BPF_FUNC_tail_call) 11004 return 0; 11005 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 11006 verbose(env, "kernel subsystem misconfigured verifier\n"); 11007 return -EINVAL; 11008 } 11009 11010 reg = ®s[BPF_REG_3]; 11011 val = reg->var_off.value; 11012 max = map->max_entries; 11013 11014 if (!(is_reg_const(reg, false) && val < max)) { 11015 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 11016 return 0; 11017 } 11018 11019 err = mark_chain_precision(env, BPF_REG_3); 11020 if (err) 11021 return err; 11022 if (bpf_map_key_unseen(aux)) 11023 bpf_map_key_store(aux, val); 11024 else if (!bpf_map_key_poisoned(aux) && 11025 bpf_map_key_immediate(aux) != val) 11026 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 11027 return 0; 11028 } 11029 11030 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 11031 { 11032 struct bpf_verifier_state *state = env->cur_state; 11033 enum bpf_prog_type type = resolve_prog_type(env->prog); 11034 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 11035 bool refs_lingering = false; 11036 int i; 11037 11038 if (!exception_exit && cur_func(env)->frameno) 11039 return 0; 11040 11041 for (i = 0; i < state->acquired_refs; i++) { 11042 if (state->refs[i].type != REF_TYPE_PTR) 11043 continue; 11044 /* Allow struct_ops programs to return a referenced kptr back to 11045 * kernel. Type checks are performed later in check_return_code. 11046 */ 11047 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && 11048 reg->ref_obj_id == state->refs[i].id) 11049 continue; 11050 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 11051 state->refs[i].id, state->refs[i].insn_idx); 11052 refs_lingering = true; 11053 } 11054 return refs_lingering ? -EINVAL : 0; 11055 } 11056 11057 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 11058 { 11059 int err; 11060 11061 if (check_lock && env->cur_state->active_locks) { 11062 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 11063 return -EINVAL; 11064 } 11065 11066 err = check_reference_leak(env, exception_exit); 11067 if (err) { 11068 verbose(env, "%s would lead to reference leak\n", prefix); 11069 return err; 11070 } 11071 11072 if (check_lock && env->cur_state->active_irq_id) { 11073 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix); 11074 return -EINVAL; 11075 } 11076 11077 if (check_lock && env->cur_state->active_rcu_lock) { 11078 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 11079 return -EINVAL; 11080 } 11081 11082 if (check_lock && env->cur_state->active_preempt_locks) { 11083 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 11084 return -EINVAL; 11085 } 11086 11087 return 0; 11088 } 11089 11090 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 11091 struct bpf_reg_state *regs) 11092 { 11093 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 11094 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 11095 struct bpf_map *fmt_map = fmt_reg->map_ptr; 11096 struct bpf_bprintf_data data = {}; 11097 int err, fmt_map_off, num_args; 11098 u64 fmt_addr; 11099 char *fmt; 11100 11101 /* data must be an array of u64 */ 11102 if (data_len_reg->var_off.value % 8) 11103 return -EINVAL; 11104 num_args = data_len_reg->var_off.value / 8; 11105 11106 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 11107 * and map_direct_value_addr is set. 11108 */ 11109 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 11110 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 11111 fmt_map_off); 11112 if (err) { 11113 verbose(env, "failed to retrieve map value address\n"); 11114 return -EFAULT; 11115 } 11116 fmt = (char *)(long)fmt_addr + fmt_map_off; 11117 11118 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 11119 * can focus on validating the format specifiers. 11120 */ 11121 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 11122 if (err < 0) 11123 verbose(env, "Invalid format string\n"); 11124 11125 return err; 11126 } 11127 11128 static int check_get_func_ip(struct bpf_verifier_env *env) 11129 { 11130 enum bpf_prog_type type = resolve_prog_type(env->prog); 11131 int func_id = BPF_FUNC_get_func_ip; 11132 11133 if (type == BPF_PROG_TYPE_TRACING) { 11134 if (!bpf_prog_has_trampoline(env->prog)) { 11135 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 11136 func_id_name(func_id), func_id); 11137 return -ENOTSUPP; 11138 } 11139 return 0; 11140 } else if (type == BPF_PROG_TYPE_KPROBE) { 11141 return 0; 11142 } 11143 11144 verbose(env, "func %s#%d not supported for program type %d\n", 11145 func_id_name(func_id), func_id, type); 11146 return -ENOTSUPP; 11147 } 11148 11149 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 11150 { 11151 return &env->insn_aux_data[env->insn_idx]; 11152 } 11153 11154 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 11155 { 11156 struct bpf_reg_state *regs = cur_regs(env); 11157 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 11158 bool reg_is_null = register_is_null(reg); 11159 11160 if (reg_is_null) 11161 mark_chain_precision(env, BPF_REG_4); 11162 11163 return reg_is_null; 11164 } 11165 11166 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 11167 { 11168 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 11169 11170 if (!state->initialized) { 11171 state->initialized = 1; 11172 state->fit_for_inline = loop_flag_is_zero(env); 11173 state->callback_subprogno = subprogno; 11174 return; 11175 } 11176 11177 if (!state->fit_for_inline) 11178 return; 11179 11180 state->fit_for_inline = (loop_flag_is_zero(env) && 11181 state->callback_subprogno == subprogno); 11182 } 11183 11184 /* Returns whether or not the given map type can potentially elide 11185 * lookup return value nullness check. This is possible if the key 11186 * is statically known. 11187 */ 11188 static bool can_elide_value_nullness(enum bpf_map_type type) 11189 { 11190 switch (type) { 11191 case BPF_MAP_TYPE_ARRAY: 11192 case BPF_MAP_TYPE_PERCPU_ARRAY: 11193 return true; 11194 default: 11195 return false; 11196 } 11197 } 11198 11199 static int get_helper_proto(struct bpf_verifier_env *env, int func_id, 11200 const struct bpf_func_proto **ptr) 11201 { 11202 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 11203 return -ERANGE; 11204 11205 if (!env->ops->get_func_proto) 11206 return -EINVAL; 11207 11208 *ptr = env->ops->get_func_proto(func_id, env->prog); 11209 return *ptr ? 0 : -EINVAL; 11210 } 11211 11212 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11213 int *insn_idx_p) 11214 { 11215 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11216 bool returns_cpu_specific_alloc_ptr = false; 11217 const struct bpf_func_proto *fn = NULL; 11218 enum bpf_return_type ret_type; 11219 enum bpf_type_flag ret_flag; 11220 struct bpf_reg_state *regs; 11221 struct bpf_call_arg_meta meta; 11222 int insn_idx = *insn_idx_p; 11223 bool changes_data; 11224 int i, err, func_id; 11225 11226 /* find function prototype */ 11227 func_id = insn->imm; 11228 err = get_helper_proto(env, insn->imm, &fn); 11229 if (err == -ERANGE) { 11230 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 11231 return -EINVAL; 11232 } 11233 11234 if (err) { 11235 verbose(env, "program of this type cannot use helper %s#%d\n", 11236 func_id_name(func_id), func_id); 11237 return err; 11238 } 11239 11240 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 11241 if (!env->prog->gpl_compatible && fn->gpl_only) { 11242 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 11243 return -EINVAL; 11244 } 11245 11246 if (fn->allowed && !fn->allowed(env->prog)) { 11247 verbose(env, "helper call is not allowed in probe\n"); 11248 return -EINVAL; 11249 } 11250 11251 if (!in_sleepable(env) && fn->might_sleep) { 11252 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 11253 return -EINVAL; 11254 } 11255 11256 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 11257 changes_data = bpf_helper_changes_pkt_data(func_id); 11258 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 11259 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 11260 func_id_name(func_id), func_id); 11261 return -EINVAL; 11262 } 11263 11264 memset(&meta, 0, sizeof(meta)); 11265 meta.pkt_access = fn->pkt_access; 11266 11267 err = check_func_proto(fn, func_id); 11268 if (err) { 11269 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 11270 func_id_name(func_id), func_id); 11271 return err; 11272 } 11273 11274 if (env->cur_state->active_rcu_lock) { 11275 if (fn->might_sleep) { 11276 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 11277 func_id_name(func_id), func_id); 11278 return -EINVAL; 11279 } 11280 11281 if (in_sleepable(env) && is_storage_get_function(func_id)) 11282 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 11283 } 11284 11285 if (env->cur_state->active_preempt_locks) { 11286 if (fn->might_sleep) { 11287 verbose(env, "sleepable helper %s#%d in non-preemptible region\n", 11288 func_id_name(func_id), func_id); 11289 return -EINVAL; 11290 } 11291 11292 if (in_sleepable(env) && is_storage_get_function(func_id)) 11293 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 11294 } 11295 11296 if (env->cur_state->active_irq_id) { 11297 if (fn->might_sleep) { 11298 verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n", 11299 func_id_name(func_id), func_id); 11300 return -EINVAL; 11301 } 11302 11303 if (in_sleepable(env) && is_storage_get_function(func_id)) 11304 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 11305 } 11306 11307 meta.func_id = func_id; 11308 /* check args */ 11309 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 11310 err = check_func_arg(env, i, &meta, fn, insn_idx); 11311 if (err) 11312 return err; 11313 } 11314 11315 err = record_func_map(env, &meta, func_id, insn_idx); 11316 if (err) 11317 return err; 11318 11319 err = record_func_key(env, &meta, func_id, insn_idx); 11320 if (err) 11321 return err; 11322 11323 /* Mark slots with STACK_MISC in case of raw mode, stack offset 11324 * is inferred from register state. 11325 */ 11326 for (i = 0; i < meta.access_size; i++) { 11327 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 11328 BPF_WRITE, -1, false, false); 11329 if (err) 11330 return err; 11331 } 11332 11333 regs = cur_regs(env); 11334 11335 if (meta.release_regno) { 11336 err = -EINVAL; 11337 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 11338 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 11339 * is safe to do directly. 11340 */ 11341 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 11342 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 11343 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 11344 return -EFAULT; 11345 } 11346 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 11347 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 11348 u32 ref_obj_id = meta.ref_obj_id; 11349 bool in_rcu = in_rcu_cs(env); 11350 struct bpf_func_state *state; 11351 struct bpf_reg_state *reg; 11352 11353 err = release_reference_nomark(env->cur_state, ref_obj_id); 11354 if (!err) { 11355 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 11356 if (reg->ref_obj_id == ref_obj_id) { 11357 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 11358 reg->ref_obj_id = 0; 11359 reg->type &= ~MEM_ALLOC; 11360 reg->type |= MEM_RCU; 11361 } else { 11362 mark_reg_invalid(env, reg); 11363 } 11364 } 11365 })); 11366 } 11367 } else if (meta.ref_obj_id) { 11368 err = release_reference(env, meta.ref_obj_id); 11369 } else if (register_is_null(®s[meta.release_regno])) { 11370 /* meta.ref_obj_id can only be 0 if register that is meant to be 11371 * released is NULL, which must be > R0. 11372 */ 11373 err = 0; 11374 } 11375 if (err) { 11376 verbose(env, "func %s#%d reference has not been acquired before\n", 11377 func_id_name(func_id), func_id); 11378 return err; 11379 } 11380 } 11381 11382 switch (func_id) { 11383 case BPF_FUNC_tail_call: 11384 err = check_resource_leak(env, false, true, "tail_call"); 11385 if (err) 11386 return err; 11387 break; 11388 case BPF_FUNC_get_local_storage: 11389 /* check that flags argument in get_local_storage(map, flags) is 0, 11390 * this is required because get_local_storage() can't return an error. 11391 */ 11392 if (!register_is_null(®s[BPF_REG_2])) { 11393 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 11394 return -EINVAL; 11395 } 11396 break; 11397 case BPF_FUNC_for_each_map_elem: 11398 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11399 set_map_elem_callback_state); 11400 break; 11401 case BPF_FUNC_timer_set_callback: 11402 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11403 set_timer_callback_state); 11404 break; 11405 case BPF_FUNC_find_vma: 11406 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11407 set_find_vma_callback_state); 11408 break; 11409 case BPF_FUNC_snprintf: 11410 err = check_bpf_snprintf_call(env, regs); 11411 break; 11412 case BPF_FUNC_loop: 11413 update_loop_inline_state(env, meta.subprogno); 11414 /* Verifier relies on R1 value to determine if bpf_loop() iteration 11415 * is finished, thus mark it precise. 11416 */ 11417 err = mark_chain_precision(env, BPF_REG_1); 11418 if (err) 11419 return err; 11420 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 11421 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11422 set_loop_callback_state); 11423 } else { 11424 cur_func(env)->callback_depth = 0; 11425 if (env->log.level & BPF_LOG_LEVEL2) 11426 verbose(env, "frame%d bpf_loop iteration limit reached\n", 11427 env->cur_state->curframe); 11428 } 11429 break; 11430 case BPF_FUNC_dynptr_from_mem: 11431 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 11432 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 11433 reg_type_str(env, regs[BPF_REG_1].type)); 11434 return -EACCES; 11435 } 11436 break; 11437 case BPF_FUNC_set_retval: 11438 if (prog_type == BPF_PROG_TYPE_LSM && 11439 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 11440 if (!env->prog->aux->attach_func_proto->type) { 11441 /* Make sure programs that attach to void 11442 * hooks don't try to modify return value. 11443 */ 11444 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 11445 return -EINVAL; 11446 } 11447 } 11448 break; 11449 case BPF_FUNC_dynptr_data: 11450 { 11451 struct bpf_reg_state *reg; 11452 int id, ref_obj_id; 11453 11454 reg = get_dynptr_arg_reg(env, fn, regs); 11455 if (!reg) 11456 return -EFAULT; 11457 11458 11459 if (meta.dynptr_id) { 11460 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 11461 return -EFAULT; 11462 } 11463 if (meta.ref_obj_id) { 11464 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 11465 return -EFAULT; 11466 } 11467 11468 id = dynptr_id(env, reg); 11469 if (id < 0) { 11470 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11471 return id; 11472 } 11473 11474 ref_obj_id = dynptr_ref_obj_id(env, reg); 11475 if (ref_obj_id < 0) { 11476 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 11477 return ref_obj_id; 11478 } 11479 11480 meta.dynptr_id = id; 11481 meta.ref_obj_id = ref_obj_id; 11482 11483 break; 11484 } 11485 case BPF_FUNC_dynptr_write: 11486 { 11487 enum bpf_dynptr_type dynptr_type; 11488 struct bpf_reg_state *reg; 11489 11490 reg = get_dynptr_arg_reg(env, fn, regs); 11491 if (!reg) 11492 return -EFAULT; 11493 11494 dynptr_type = dynptr_get_type(env, reg); 11495 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 11496 return -EFAULT; 11497 11498 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 11499 /* this will trigger clear_all_pkt_pointers(), which will 11500 * invalidate all dynptr slices associated with the skb 11501 */ 11502 changes_data = true; 11503 11504 break; 11505 } 11506 case BPF_FUNC_per_cpu_ptr: 11507 case BPF_FUNC_this_cpu_ptr: 11508 { 11509 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 11510 const struct btf_type *type; 11511 11512 if (reg->type & MEM_RCU) { 11513 type = btf_type_by_id(reg->btf, reg->btf_id); 11514 if (!type || !btf_type_is_struct(type)) { 11515 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 11516 return -EFAULT; 11517 } 11518 returns_cpu_specific_alloc_ptr = true; 11519 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 11520 } 11521 break; 11522 } 11523 case BPF_FUNC_user_ringbuf_drain: 11524 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11525 set_user_ringbuf_callback_state); 11526 break; 11527 } 11528 11529 if (err) 11530 return err; 11531 11532 /* reset caller saved regs */ 11533 for (i = 0; i < CALLER_SAVED_REGS; i++) { 11534 mark_reg_not_init(env, regs, caller_saved[i]); 11535 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 11536 } 11537 11538 /* helper call returns 64-bit value. */ 11539 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 11540 11541 /* update return register (already marked as written above) */ 11542 ret_type = fn->ret_type; 11543 ret_flag = type_flag(ret_type); 11544 11545 switch (base_type(ret_type)) { 11546 case RET_INTEGER: 11547 /* sets type to SCALAR_VALUE */ 11548 mark_reg_unknown(env, regs, BPF_REG_0); 11549 break; 11550 case RET_VOID: 11551 regs[BPF_REG_0].type = NOT_INIT; 11552 break; 11553 case RET_PTR_TO_MAP_VALUE: 11554 /* There is no offset yet applied, variable or fixed */ 11555 mark_reg_known_zero(env, regs, BPF_REG_0); 11556 /* remember map_ptr, so that check_map_access() 11557 * can check 'value_size' boundary of memory access 11558 * to map element returned from bpf_map_lookup_elem() 11559 */ 11560 if (meta.map_ptr == NULL) { 11561 verbose(env, 11562 "kernel subsystem misconfigured verifier\n"); 11563 return -EINVAL; 11564 } 11565 11566 if (func_id == BPF_FUNC_map_lookup_elem && 11567 can_elide_value_nullness(meta.map_ptr->map_type) && 11568 meta.const_map_key >= 0 && 11569 meta.const_map_key < meta.map_ptr->max_entries) 11570 ret_flag &= ~PTR_MAYBE_NULL; 11571 11572 regs[BPF_REG_0].map_ptr = meta.map_ptr; 11573 regs[BPF_REG_0].map_uid = meta.map_uid; 11574 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 11575 if (!type_may_be_null(ret_flag) && 11576 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 11577 regs[BPF_REG_0].id = ++env->id_gen; 11578 } 11579 break; 11580 case RET_PTR_TO_SOCKET: 11581 mark_reg_known_zero(env, regs, BPF_REG_0); 11582 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 11583 break; 11584 case RET_PTR_TO_SOCK_COMMON: 11585 mark_reg_known_zero(env, regs, BPF_REG_0); 11586 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 11587 break; 11588 case RET_PTR_TO_TCP_SOCK: 11589 mark_reg_known_zero(env, regs, BPF_REG_0); 11590 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 11591 break; 11592 case RET_PTR_TO_MEM: 11593 mark_reg_known_zero(env, regs, BPF_REG_0); 11594 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 11595 regs[BPF_REG_0].mem_size = meta.mem_size; 11596 break; 11597 case RET_PTR_TO_MEM_OR_BTF_ID: 11598 { 11599 const struct btf_type *t; 11600 11601 mark_reg_known_zero(env, regs, BPF_REG_0); 11602 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 11603 if (!btf_type_is_struct(t)) { 11604 u32 tsize; 11605 const struct btf_type *ret; 11606 const char *tname; 11607 11608 /* resolve the type size of ksym. */ 11609 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 11610 if (IS_ERR(ret)) { 11611 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 11612 verbose(env, "unable to resolve the size of type '%s': %ld\n", 11613 tname, PTR_ERR(ret)); 11614 return -EINVAL; 11615 } 11616 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 11617 regs[BPF_REG_0].mem_size = tsize; 11618 } else { 11619 if (returns_cpu_specific_alloc_ptr) { 11620 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 11621 } else { 11622 /* MEM_RDONLY may be carried from ret_flag, but it 11623 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 11624 * it will confuse the check of PTR_TO_BTF_ID in 11625 * check_mem_access(). 11626 */ 11627 ret_flag &= ~MEM_RDONLY; 11628 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 11629 } 11630 11631 regs[BPF_REG_0].btf = meta.ret_btf; 11632 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11633 } 11634 break; 11635 } 11636 case RET_PTR_TO_BTF_ID: 11637 { 11638 struct btf *ret_btf; 11639 int ret_btf_id; 11640 11641 mark_reg_known_zero(env, regs, BPF_REG_0); 11642 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 11643 if (func_id == BPF_FUNC_kptr_xchg) { 11644 ret_btf = meta.kptr_field->kptr.btf; 11645 ret_btf_id = meta.kptr_field->kptr.btf_id; 11646 if (!btf_is_kernel(ret_btf)) { 11647 regs[BPF_REG_0].type |= MEM_ALLOC; 11648 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 11649 regs[BPF_REG_0].type |= MEM_PERCPU; 11650 } 11651 } else { 11652 if (fn->ret_btf_id == BPF_PTR_POISON) { 11653 verbose(env, "verifier internal error:"); 11654 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 11655 func_id_name(func_id)); 11656 return -EINVAL; 11657 } 11658 ret_btf = btf_vmlinux; 11659 ret_btf_id = *fn->ret_btf_id; 11660 } 11661 if (ret_btf_id == 0) { 11662 verbose(env, "invalid return type %u of func %s#%d\n", 11663 base_type(ret_type), func_id_name(func_id), 11664 func_id); 11665 return -EINVAL; 11666 } 11667 regs[BPF_REG_0].btf = ret_btf; 11668 regs[BPF_REG_0].btf_id = ret_btf_id; 11669 break; 11670 } 11671 default: 11672 verbose(env, "unknown return type %u of func %s#%d\n", 11673 base_type(ret_type), func_id_name(func_id), func_id); 11674 return -EINVAL; 11675 } 11676 11677 if (type_may_be_null(regs[BPF_REG_0].type)) 11678 regs[BPF_REG_0].id = ++env->id_gen; 11679 11680 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 11681 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 11682 func_id_name(func_id), func_id); 11683 return -EFAULT; 11684 } 11685 11686 if (is_dynptr_ref_function(func_id)) 11687 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 11688 11689 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 11690 /* For release_reference() */ 11691 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 11692 } else if (is_acquire_function(func_id, meta.map_ptr)) { 11693 int id = acquire_reference(env, insn_idx); 11694 11695 if (id < 0) 11696 return id; 11697 /* For mark_ptr_or_null_reg() */ 11698 regs[BPF_REG_0].id = id; 11699 /* For release_reference() */ 11700 regs[BPF_REG_0].ref_obj_id = id; 11701 } 11702 11703 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 11704 if (err) 11705 return err; 11706 11707 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 11708 if (err) 11709 return err; 11710 11711 if ((func_id == BPF_FUNC_get_stack || 11712 func_id == BPF_FUNC_get_task_stack) && 11713 !env->prog->has_callchain_buf) { 11714 const char *err_str; 11715 11716 #ifdef CONFIG_PERF_EVENTS 11717 err = get_callchain_buffers(sysctl_perf_event_max_stack); 11718 err_str = "cannot get callchain buffer for func %s#%d\n"; 11719 #else 11720 err = -ENOTSUPP; 11721 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 11722 #endif 11723 if (err) { 11724 verbose(env, err_str, func_id_name(func_id), func_id); 11725 return err; 11726 } 11727 11728 env->prog->has_callchain_buf = true; 11729 } 11730 11731 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 11732 env->prog->call_get_stack = true; 11733 11734 if (func_id == BPF_FUNC_get_func_ip) { 11735 if (check_get_func_ip(env)) 11736 return -ENOTSUPP; 11737 env->prog->call_get_func_ip = true; 11738 } 11739 11740 if (changes_data) 11741 clear_all_pkt_pointers(env); 11742 return 0; 11743 } 11744 11745 /* mark_btf_func_reg_size() is used when the reg size is determined by 11746 * the BTF func_proto's return value size and argument. 11747 */ 11748 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs, 11749 u32 regno, size_t reg_size) 11750 { 11751 struct bpf_reg_state *reg = ®s[regno]; 11752 11753 if (regno == BPF_REG_0) { 11754 /* Function return value */ 11755 reg->live |= REG_LIVE_WRITTEN; 11756 reg->subreg_def = reg_size == sizeof(u64) ? 11757 DEF_NOT_SUBREG : env->insn_idx + 1; 11758 } else { 11759 /* Function argument */ 11760 if (reg_size == sizeof(u64)) { 11761 mark_insn_zext(env, reg); 11762 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 11763 } else { 11764 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 11765 } 11766 } 11767 } 11768 11769 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 11770 size_t reg_size) 11771 { 11772 return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size); 11773 } 11774 11775 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 11776 { 11777 return meta->kfunc_flags & KF_ACQUIRE; 11778 } 11779 11780 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 11781 { 11782 return meta->kfunc_flags & KF_RELEASE; 11783 } 11784 11785 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 11786 { 11787 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 11788 } 11789 11790 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 11791 { 11792 return meta->kfunc_flags & KF_SLEEPABLE; 11793 } 11794 11795 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 11796 { 11797 return meta->kfunc_flags & KF_DESTRUCTIVE; 11798 } 11799 11800 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 11801 { 11802 return meta->kfunc_flags & KF_RCU; 11803 } 11804 11805 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 11806 { 11807 return meta->kfunc_flags & KF_RCU_PROTECTED; 11808 } 11809 11810 static bool is_kfunc_arg_mem_size(const struct btf *btf, 11811 const struct btf_param *arg, 11812 const struct bpf_reg_state *reg) 11813 { 11814 const struct btf_type *t; 11815 11816 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11817 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11818 return false; 11819 11820 return btf_param_match_suffix(btf, arg, "__sz"); 11821 } 11822 11823 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 11824 const struct btf_param *arg, 11825 const struct bpf_reg_state *reg) 11826 { 11827 const struct btf_type *t; 11828 11829 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11830 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11831 return false; 11832 11833 return btf_param_match_suffix(btf, arg, "__szk"); 11834 } 11835 11836 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 11837 { 11838 return btf_param_match_suffix(btf, arg, "__opt"); 11839 } 11840 11841 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 11842 { 11843 return btf_param_match_suffix(btf, arg, "__k"); 11844 } 11845 11846 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 11847 { 11848 return btf_param_match_suffix(btf, arg, "__ign"); 11849 } 11850 11851 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 11852 { 11853 return btf_param_match_suffix(btf, arg, "__map"); 11854 } 11855 11856 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 11857 { 11858 return btf_param_match_suffix(btf, arg, "__alloc"); 11859 } 11860 11861 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 11862 { 11863 return btf_param_match_suffix(btf, arg, "__uninit"); 11864 } 11865 11866 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 11867 { 11868 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 11869 } 11870 11871 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 11872 { 11873 return btf_param_match_suffix(btf, arg, "__nullable"); 11874 } 11875 11876 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 11877 { 11878 return btf_param_match_suffix(btf, arg, "__str"); 11879 } 11880 11881 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg) 11882 { 11883 return btf_param_match_suffix(btf, arg, "__irq_flag"); 11884 } 11885 11886 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg) 11887 { 11888 return btf_param_match_suffix(btf, arg, "__prog"); 11889 } 11890 11891 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 11892 const struct btf_param *arg, 11893 const char *name) 11894 { 11895 int len, target_len = strlen(name); 11896 const char *param_name; 11897 11898 param_name = btf_name_by_offset(btf, arg->name_off); 11899 if (str_is_empty(param_name)) 11900 return false; 11901 len = strlen(param_name); 11902 if (len != target_len) 11903 return false; 11904 if (strcmp(param_name, name)) 11905 return false; 11906 11907 return true; 11908 } 11909 11910 enum { 11911 KF_ARG_DYNPTR_ID, 11912 KF_ARG_LIST_HEAD_ID, 11913 KF_ARG_LIST_NODE_ID, 11914 KF_ARG_RB_ROOT_ID, 11915 KF_ARG_RB_NODE_ID, 11916 KF_ARG_WORKQUEUE_ID, 11917 KF_ARG_RES_SPIN_LOCK_ID, 11918 }; 11919 11920 BTF_ID_LIST(kf_arg_btf_ids) 11921 BTF_ID(struct, bpf_dynptr) 11922 BTF_ID(struct, bpf_list_head) 11923 BTF_ID(struct, bpf_list_node) 11924 BTF_ID(struct, bpf_rb_root) 11925 BTF_ID(struct, bpf_rb_node) 11926 BTF_ID(struct, bpf_wq) 11927 BTF_ID(struct, bpf_res_spin_lock) 11928 11929 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 11930 const struct btf_param *arg, int type) 11931 { 11932 const struct btf_type *t; 11933 u32 res_id; 11934 11935 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11936 if (!t) 11937 return false; 11938 if (!btf_type_is_ptr(t)) 11939 return false; 11940 t = btf_type_skip_modifiers(btf, t->type, &res_id); 11941 if (!t) 11942 return false; 11943 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 11944 } 11945 11946 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 11947 { 11948 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 11949 } 11950 11951 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 11952 { 11953 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 11954 } 11955 11956 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 11957 { 11958 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 11959 } 11960 11961 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 11962 { 11963 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 11964 } 11965 11966 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 11967 { 11968 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 11969 } 11970 11971 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 11972 { 11973 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 11974 } 11975 11976 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg) 11977 { 11978 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID); 11979 } 11980 11981 static bool is_rbtree_node_type(const struct btf_type *t) 11982 { 11983 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]); 11984 } 11985 11986 static bool is_list_node_type(const struct btf_type *t) 11987 { 11988 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]); 11989 } 11990 11991 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 11992 const struct btf_param *arg) 11993 { 11994 const struct btf_type *t; 11995 11996 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 11997 if (!t) 11998 return false; 11999 12000 return true; 12001 } 12002 12003 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 12004 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 12005 const struct btf *btf, 12006 const struct btf_type *t, int rec) 12007 { 12008 const struct btf_type *member_type; 12009 const struct btf_member *member; 12010 u32 i; 12011 12012 if (!btf_type_is_struct(t)) 12013 return false; 12014 12015 for_each_member(i, t, member) { 12016 const struct btf_array *array; 12017 12018 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 12019 if (btf_type_is_struct(member_type)) { 12020 if (rec >= 3) { 12021 verbose(env, "max struct nesting depth exceeded\n"); 12022 return false; 12023 } 12024 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 12025 return false; 12026 continue; 12027 } 12028 if (btf_type_is_array(member_type)) { 12029 array = btf_array(member_type); 12030 if (!array->nelems) 12031 return false; 12032 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 12033 if (!btf_type_is_scalar(member_type)) 12034 return false; 12035 continue; 12036 } 12037 if (!btf_type_is_scalar(member_type)) 12038 return false; 12039 } 12040 return true; 12041 } 12042 12043 enum kfunc_ptr_arg_type { 12044 KF_ARG_PTR_TO_CTX, 12045 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 12046 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 12047 KF_ARG_PTR_TO_DYNPTR, 12048 KF_ARG_PTR_TO_ITER, 12049 KF_ARG_PTR_TO_LIST_HEAD, 12050 KF_ARG_PTR_TO_LIST_NODE, 12051 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 12052 KF_ARG_PTR_TO_MEM, 12053 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 12054 KF_ARG_PTR_TO_CALLBACK, 12055 KF_ARG_PTR_TO_RB_ROOT, 12056 KF_ARG_PTR_TO_RB_NODE, 12057 KF_ARG_PTR_TO_NULL, 12058 KF_ARG_PTR_TO_CONST_STR, 12059 KF_ARG_PTR_TO_MAP, 12060 KF_ARG_PTR_TO_WORKQUEUE, 12061 KF_ARG_PTR_TO_IRQ_FLAG, 12062 KF_ARG_PTR_TO_RES_SPIN_LOCK, 12063 }; 12064 12065 enum special_kfunc_type { 12066 KF_bpf_obj_new_impl, 12067 KF_bpf_obj_drop_impl, 12068 KF_bpf_refcount_acquire_impl, 12069 KF_bpf_list_push_front_impl, 12070 KF_bpf_list_push_back_impl, 12071 KF_bpf_list_pop_front, 12072 KF_bpf_list_pop_back, 12073 KF_bpf_list_front, 12074 KF_bpf_list_back, 12075 KF_bpf_cast_to_kern_ctx, 12076 KF_bpf_rdonly_cast, 12077 KF_bpf_rcu_read_lock, 12078 KF_bpf_rcu_read_unlock, 12079 KF_bpf_rbtree_remove, 12080 KF_bpf_rbtree_add_impl, 12081 KF_bpf_rbtree_first, 12082 KF_bpf_rbtree_root, 12083 KF_bpf_rbtree_left, 12084 KF_bpf_rbtree_right, 12085 KF_bpf_dynptr_from_skb, 12086 KF_bpf_dynptr_from_xdp, 12087 KF_bpf_dynptr_slice, 12088 KF_bpf_dynptr_slice_rdwr, 12089 KF_bpf_dynptr_clone, 12090 KF_bpf_percpu_obj_new_impl, 12091 KF_bpf_percpu_obj_drop_impl, 12092 KF_bpf_throw, 12093 KF_bpf_wq_set_callback_impl, 12094 KF_bpf_preempt_disable, 12095 KF_bpf_preempt_enable, 12096 KF_bpf_iter_css_task_new, 12097 KF_bpf_session_cookie, 12098 KF_bpf_get_kmem_cache, 12099 KF_bpf_local_irq_save, 12100 KF_bpf_local_irq_restore, 12101 KF_bpf_iter_num_new, 12102 KF_bpf_iter_num_next, 12103 KF_bpf_iter_num_destroy, 12104 KF_bpf_set_dentry_xattr, 12105 KF_bpf_remove_dentry_xattr, 12106 KF_bpf_res_spin_lock, 12107 KF_bpf_res_spin_unlock, 12108 KF_bpf_res_spin_lock_irqsave, 12109 KF_bpf_res_spin_unlock_irqrestore, 12110 KF___bpf_trap, 12111 }; 12112 12113 BTF_ID_LIST(special_kfunc_list) 12114 BTF_ID(func, bpf_obj_new_impl) 12115 BTF_ID(func, bpf_obj_drop_impl) 12116 BTF_ID(func, bpf_refcount_acquire_impl) 12117 BTF_ID(func, bpf_list_push_front_impl) 12118 BTF_ID(func, bpf_list_push_back_impl) 12119 BTF_ID(func, bpf_list_pop_front) 12120 BTF_ID(func, bpf_list_pop_back) 12121 BTF_ID(func, bpf_list_front) 12122 BTF_ID(func, bpf_list_back) 12123 BTF_ID(func, bpf_cast_to_kern_ctx) 12124 BTF_ID(func, bpf_rdonly_cast) 12125 BTF_ID(func, bpf_rcu_read_lock) 12126 BTF_ID(func, bpf_rcu_read_unlock) 12127 BTF_ID(func, bpf_rbtree_remove) 12128 BTF_ID(func, bpf_rbtree_add_impl) 12129 BTF_ID(func, bpf_rbtree_first) 12130 BTF_ID(func, bpf_rbtree_root) 12131 BTF_ID(func, bpf_rbtree_left) 12132 BTF_ID(func, bpf_rbtree_right) 12133 #ifdef CONFIG_NET 12134 BTF_ID(func, bpf_dynptr_from_skb) 12135 BTF_ID(func, bpf_dynptr_from_xdp) 12136 #else 12137 BTF_ID_UNUSED 12138 BTF_ID_UNUSED 12139 #endif 12140 BTF_ID(func, bpf_dynptr_slice) 12141 BTF_ID(func, bpf_dynptr_slice_rdwr) 12142 BTF_ID(func, bpf_dynptr_clone) 12143 BTF_ID(func, bpf_percpu_obj_new_impl) 12144 BTF_ID(func, bpf_percpu_obj_drop_impl) 12145 BTF_ID(func, bpf_throw) 12146 BTF_ID(func, bpf_wq_set_callback_impl) 12147 BTF_ID(func, bpf_preempt_disable) 12148 BTF_ID(func, bpf_preempt_enable) 12149 #ifdef CONFIG_CGROUPS 12150 BTF_ID(func, bpf_iter_css_task_new) 12151 #else 12152 BTF_ID_UNUSED 12153 #endif 12154 #ifdef CONFIG_BPF_EVENTS 12155 BTF_ID(func, bpf_session_cookie) 12156 #else 12157 BTF_ID_UNUSED 12158 #endif 12159 BTF_ID(func, bpf_get_kmem_cache) 12160 BTF_ID(func, bpf_local_irq_save) 12161 BTF_ID(func, bpf_local_irq_restore) 12162 BTF_ID(func, bpf_iter_num_new) 12163 BTF_ID(func, bpf_iter_num_next) 12164 BTF_ID(func, bpf_iter_num_destroy) 12165 #ifdef CONFIG_BPF_LSM 12166 BTF_ID(func, bpf_set_dentry_xattr) 12167 BTF_ID(func, bpf_remove_dentry_xattr) 12168 #else 12169 BTF_ID_UNUSED 12170 BTF_ID_UNUSED 12171 #endif 12172 BTF_ID(func, bpf_res_spin_lock) 12173 BTF_ID(func, bpf_res_spin_unlock) 12174 BTF_ID(func, bpf_res_spin_lock_irqsave) 12175 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 12176 BTF_ID(func, __bpf_trap) 12177 12178 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 12179 { 12180 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 12181 meta->arg_owning_ref) { 12182 return false; 12183 } 12184 12185 return meta->kfunc_flags & KF_RET_NULL; 12186 } 12187 12188 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 12189 { 12190 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 12191 } 12192 12193 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 12194 { 12195 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 12196 } 12197 12198 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 12199 { 12200 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 12201 } 12202 12203 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 12204 { 12205 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 12206 } 12207 12208 static enum kfunc_ptr_arg_type 12209 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 12210 struct bpf_kfunc_call_arg_meta *meta, 12211 const struct btf_type *t, const struct btf_type *ref_t, 12212 const char *ref_tname, const struct btf_param *args, 12213 int argno, int nargs) 12214 { 12215 u32 regno = argno + 1; 12216 struct bpf_reg_state *regs = cur_regs(env); 12217 struct bpf_reg_state *reg = ®s[regno]; 12218 bool arg_mem_size = false; 12219 12220 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 12221 return KF_ARG_PTR_TO_CTX; 12222 12223 /* In this function, we verify the kfunc's BTF as per the argument type, 12224 * leaving the rest of the verification with respect to the register 12225 * type to our caller. When a set of conditions hold in the BTF type of 12226 * arguments, we resolve it to a known kfunc_ptr_arg_type. 12227 */ 12228 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 12229 return KF_ARG_PTR_TO_CTX; 12230 12231 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 12232 return KF_ARG_PTR_TO_NULL; 12233 12234 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 12235 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 12236 12237 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 12238 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 12239 12240 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 12241 return KF_ARG_PTR_TO_DYNPTR; 12242 12243 if (is_kfunc_arg_iter(meta, argno, &args[argno])) 12244 return KF_ARG_PTR_TO_ITER; 12245 12246 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 12247 return KF_ARG_PTR_TO_LIST_HEAD; 12248 12249 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 12250 return KF_ARG_PTR_TO_LIST_NODE; 12251 12252 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 12253 return KF_ARG_PTR_TO_RB_ROOT; 12254 12255 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 12256 return KF_ARG_PTR_TO_RB_NODE; 12257 12258 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 12259 return KF_ARG_PTR_TO_CONST_STR; 12260 12261 if (is_kfunc_arg_map(meta->btf, &args[argno])) 12262 return KF_ARG_PTR_TO_MAP; 12263 12264 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 12265 return KF_ARG_PTR_TO_WORKQUEUE; 12266 12267 if (is_kfunc_arg_irq_flag(meta->btf, &args[argno])) 12268 return KF_ARG_PTR_TO_IRQ_FLAG; 12269 12270 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno])) 12271 return KF_ARG_PTR_TO_RES_SPIN_LOCK; 12272 12273 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 12274 if (!btf_type_is_struct(ref_t)) { 12275 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 12276 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 12277 return -EINVAL; 12278 } 12279 return KF_ARG_PTR_TO_BTF_ID; 12280 } 12281 12282 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 12283 return KF_ARG_PTR_TO_CALLBACK; 12284 12285 if (argno + 1 < nargs && 12286 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 12287 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 12288 arg_mem_size = true; 12289 12290 /* This is the catch all argument type of register types supported by 12291 * check_helper_mem_access. However, we only allow when argument type is 12292 * pointer to scalar, or struct composed (recursively) of scalars. When 12293 * arg_mem_size is true, the pointer can be void *. 12294 */ 12295 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 12296 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 12297 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 12298 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 12299 return -EINVAL; 12300 } 12301 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 12302 } 12303 12304 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 12305 struct bpf_reg_state *reg, 12306 const struct btf_type *ref_t, 12307 const char *ref_tname, u32 ref_id, 12308 struct bpf_kfunc_call_arg_meta *meta, 12309 int argno) 12310 { 12311 const struct btf_type *reg_ref_t; 12312 bool strict_type_match = false; 12313 const struct btf *reg_btf; 12314 const char *reg_ref_tname; 12315 bool taking_projection; 12316 bool struct_same; 12317 u32 reg_ref_id; 12318 12319 if (base_type(reg->type) == PTR_TO_BTF_ID) { 12320 reg_btf = reg->btf; 12321 reg_ref_id = reg->btf_id; 12322 } else { 12323 reg_btf = btf_vmlinux; 12324 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 12325 } 12326 12327 /* Enforce strict type matching for calls to kfuncs that are acquiring 12328 * or releasing a reference, or are no-cast aliases. We do _not_ 12329 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 12330 * as we want to enable BPF programs to pass types that are bitwise 12331 * equivalent without forcing them to explicitly cast with something 12332 * like bpf_cast_to_kern_ctx(). 12333 * 12334 * For example, say we had a type like the following: 12335 * 12336 * struct bpf_cpumask { 12337 * cpumask_t cpumask; 12338 * refcount_t usage; 12339 * }; 12340 * 12341 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 12342 * to a struct cpumask, so it would be safe to pass a struct 12343 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 12344 * 12345 * The philosophy here is similar to how we allow scalars of different 12346 * types to be passed to kfuncs as long as the size is the same. The 12347 * only difference here is that we're simply allowing 12348 * btf_struct_ids_match() to walk the struct at the 0th offset, and 12349 * resolve types. 12350 */ 12351 if ((is_kfunc_release(meta) && reg->ref_obj_id) || 12352 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 12353 strict_type_match = true; 12354 12355 WARN_ON_ONCE(is_kfunc_release(meta) && 12356 (reg->off || !tnum_is_const(reg->var_off) || 12357 reg->var_off.value)); 12358 12359 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 12360 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 12361 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match); 12362 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 12363 * actually use it -- it must cast to the underlying type. So we allow 12364 * caller to pass in the underlying type. 12365 */ 12366 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 12367 if (!taking_projection && !struct_same) { 12368 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 12369 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 12370 btf_type_str(reg_ref_t), reg_ref_tname); 12371 return -EINVAL; 12372 } 12373 return 0; 12374 } 12375 12376 static int process_irq_flag(struct bpf_verifier_env *env, int regno, 12377 struct bpf_kfunc_call_arg_meta *meta) 12378 { 12379 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 12380 int err, kfunc_class = IRQ_NATIVE_KFUNC; 12381 bool irq_save; 12382 12383 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] || 12384 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) { 12385 irq_save = true; 12386 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 12387 kfunc_class = IRQ_LOCK_KFUNC; 12388 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] || 12389 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) { 12390 irq_save = false; 12391 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 12392 kfunc_class = IRQ_LOCK_KFUNC; 12393 } else { 12394 verbose(env, "verifier internal error: unknown irq flags kfunc\n"); 12395 return -EFAULT; 12396 } 12397 12398 if (irq_save) { 12399 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 12400 verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1); 12401 return -EINVAL; 12402 } 12403 12404 err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false); 12405 if (err) 12406 return err; 12407 12408 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 12409 if (err) 12410 return err; 12411 } else { 12412 err = is_irq_flag_reg_valid_init(env, reg); 12413 if (err) { 12414 verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1); 12415 return err; 12416 } 12417 12418 err = mark_irq_flag_read(env, reg); 12419 if (err) 12420 return err; 12421 12422 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 12423 if (err) 12424 return err; 12425 } 12426 return 0; 12427 } 12428 12429 12430 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 12431 { 12432 struct btf_record *rec = reg_btf_record(reg); 12433 12434 if (!env->cur_state->active_locks) { 12435 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 12436 return -EFAULT; 12437 } 12438 12439 if (type_flag(reg->type) & NON_OWN_REF) { 12440 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 12441 return -EFAULT; 12442 } 12443 12444 reg->type |= NON_OWN_REF; 12445 if (rec->refcount_off >= 0) 12446 reg->type |= MEM_RCU; 12447 12448 return 0; 12449 } 12450 12451 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 12452 { 12453 struct bpf_verifier_state *state = env->cur_state; 12454 struct bpf_func_state *unused; 12455 struct bpf_reg_state *reg; 12456 int i; 12457 12458 if (!ref_obj_id) { 12459 verbose(env, "verifier internal error: ref_obj_id is zero for " 12460 "owning -> non-owning conversion\n"); 12461 return -EFAULT; 12462 } 12463 12464 for (i = 0; i < state->acquired_refs; i++) { 12465 if (state->refs[i].id != ref_obj_id) 12466 continue; 12467 12468 /* Clear ref_obj_id here so release_reference doesn't clobber 12469 * the whole reg 12470 */ 12471 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 12472 if (reg->ref_obj_id == ref_obj_id) { 12473 reg->ref_obj_id = 0; 12474 ref_set_non_owning(env, reg); 12475 } 12476 })); 12477 return 0; 12478 } 12479 12480 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 12481 return -EFAULT; 12482 } 12483 12484 /* Implementation details: 12485 * 12486 * Each register points to some region of memory, which we define as an 12487 * allocation. Each allocation may embed a bpf_spin_lock which protects any 12488 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 12489 * allocation. The lock and the data it protects are colocated in the same 12490 * memory region. 12491 * 12492 * Hence, everytime a register holds a pointer value pointing to such 12493 * allocation, the verifier preserves a unique reg->id for it. 12494 * 12495 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 12496 * bpf_spin_lock is called. 12497 * 12498 * To enable this, lock state in the verifier captures two values: 12499 * active_lock.ptr = Register's type specific pointer 12500 * active_lock.id = A unique ID for each register pointer value 12501 * 12502 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 12503 * supported register types. 12504 * 12505 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 12506 * allocated objects is the reg->btf pointer. 12507 * 12508 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 12509 * can establish the provenance of the map value statically for each distinct 12510 * lookup into such maps. They always contain a single map value hence unique 12511 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 12512 * 12513 * So, in case of global variables, they use array maps with max_entries = 1, 12514 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 12515 * into the same map value as max_entries is 1, as described above). 12516 * 12517 * In case of inner map lookups, the inner map pointer has same map_ptr as the 12518 * outer map pointer (in verifier context), but each lookup into an inner map 12519 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 12520 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 12521 * will get different reg->id assigned to each lookup, hence different 12522 * active_lock.id. 12523 * 12524 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 12525 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 12526 * returned from bpf_obj_new. Each allocation receives a new reg->id. 12527 */ 12528 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 12529 { 12530 struct bpf_reference_state *s; 12531 void *ptr; 12532 u32 id; 12533 12534 switch ((int)reg->type) { 12535 case PTR_TO_MAP_VALUE: 12536 ptr = reg->map_ptr; 12537 break; 12538 case PTR_TO_BTF_ID | MEM_ALLOC: 12539 ptr = reg->btf; 12540 break; 12541 default: 12542 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 12543 return -EFAULT; 12544 } 12545 id = reg->id; 12546 12547 if (!env->cur_state->active_locks) 12548 return -EINVAL; 12549 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 12550 if (!s) { 12551 verbose(env, "held lock and object are not in the same allocation\n"); 12552 return -EINVAL; 12553 } 12554 return 0; 12555 } 12556 12557 static bool is_bpf_list_api_kfunc(u32 btf_id) 12558 { 12559 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12560 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12561 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 12562 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 12563 btf_id == special_kfunc_list[KF_bpf_list_front] || 12564 btf_id == special_kfunc_list[KF_bpf_list_back]; 12565 } 12566 12567 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 12568 { 12569 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 12570 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12571 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 12572 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 12573 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 12574 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 12575 } 12576 12577 static bool is_bpf_iter_num_api_kfunc(u32 btf_id) 12578 { 12579 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] || 12580 btf_id == special_kfunc_list[KF_bpf_iter_num_next] || 12581 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy]; 12582 } 12583 12584 static bool is_bpf_graph_api_kfunc(u32 btf_id) 12585 { 12586 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 12587 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 12588 } 12589 12590 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id) 12591 { 12592 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 12593 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 12594 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 12595 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]; 12596 } 12597 12598 static bool kfunc_spin_allowed(u32 btf_id) 12599 { 12600 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) || 12601 is_bpf_res_spin_lock_kfunc(btf_id); 12602 } 12603 12604 static bool is_sync_callback_calling_kfunc(u32 btf_id) 12605 { 12606 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 12607 } 12608 12609 static bool is_async_callback_calling_kfunc(u32 btf_id) 12610 { 12611 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 12612 } 12613 12614 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 12615 { 12616 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 12617 insn->imm == special_kfunc_list[KF_bpf_throw]; 12618 } 12619 12620 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id) 12621 { 12622 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 12623 } 12624 12625 static bool is_callback_calling_kfunc(u32 btf_id) 12626 { 12627 return is_sync_callback_calling_kfunc(btf_id) || 12628 is_async_callback_calling_kfunc(btf_id); 12629 } 12630 12631 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 12632 { 12633 return is_bpf_rbtree_api_kfunc(btf_id); 12634 } 12635 12636 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 12637 enum btf_field_type head_field_type, 12638 u32 kfunc_btf_id) 12639 { 12640 bool ret; 12641 12642 switch (head_field_type) { 12643 case BPF_LIST_HEAD: 12644 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 12645 break; 12646 case BPF_RB_ROOT: 12647 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 12648 break; 12649 default: 12650 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 12651 btf_field_type_name(head_field_type)); 12652 return false; 12653 } 12654 12655 if (!ret) 12656 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 12657 btf_field_type_name(head_field_type)); 12658 return ret; 12659 } 12660 12661 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 12662 enum btf_field_type node_field_type, 12663 u32 kfunc_btf_id) 12664 { 12665 bool ret; 12666 12667 switch (node_field_type) { 12668 case BPF_LIST_NODE: 12669 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12670 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 12671 break; 12672 case BPF_RB_NODE: 12673 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12674 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 12675 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 12676 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 12677 break; 12678 default: 12679 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 12680 btf_field_type_name(node_field_type)); 12681 return false; 12682 } 12683 12684 if (!ret) 12685 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 12686 btf_field_type_name(node_field_type)); 12687 return ret; 12688 } 12689 12690 static int 12691 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 12692 struct bpf_reg_state *reg, u32 regno, 12693 struct bpf_kfunc_call_arg_meta *meta, 12694 enum btf_field_type head_field_type, 12695 struct btf_field **head_field) 12696 { 12697 const char *head_type_name; 12698 struct btf_field *field; 12699 struct btf_record *rec; 12700 u32 head_off; 12701 12702 if (meta->btf != btf_vmlinux) { 12703 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 12704 return -EFAULT; 12705 } 12706 12707 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 12708 return -EFAULT; 12709 12710 head_type_name = btf_field_type_name(head_field_type); 12711 if (!tnum_is_const(reg->var_off)) { 12712 verbose(env, 12713 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 12714 regno, head_type_name); 12715 return -EINVAL; 12716 } 12717 12718 rec = reg_btf_record(reg); 12719 head_off = reg->off + reg->var_off.value; 12720 field = btf_record_find(rec, head_off, head_field_type); 12721 if (!field) { 12722 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 12723 return -EINVAL; 12724 } 12725 12726 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 12727 if (check_reg_allocation_locked(env, reg)) { 12728 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 12729 rec->spin_lock_off, head_type_name); 12730 return -EINVAL; 12731 } 12732 12733 if (*head_field) { 12734 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 12735 return -EFAULT; 12736 } 12737 *head_field = field; 12738 return 0; 12739 } 12740 12741 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 12742 struct bpf_reg_state *reg, u32 regno, 12743 struct bpf_kfunc_call_arg_meta *meta) 12744 { 12745 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 12746 &meta->arg_list_head.field); 12747 } 12748 12749 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 12750 struct bpf_reg_state *reg, u32 regno, 12751 struct bpf_kfunc_call_arg_meta *meta) 12752 { 12753 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 12754 &meta->arg_rbtree_root.field); 12755 } 12756 12757 static int 12758 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 12759 struct bpf_reg_state *reg, u32 regno, 12760 struct bpf_kfunc_call_arg_meta *meta, 12761 enum btf_field_type head_field_type, 12762 enum btf_field_type node_field_type, 12763 struct btf_field **node_field) 12764 { 12765 const char *node_type_name; 12766 const struct btf_type *et, *t; 12767 struct btf_field *field; 12768 u32 node_off; 12769 12770 if (meta->btf != btf_vmlinux) { 12771 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 12772 return -EFAULT; 12773 } 12774 12775 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 12776 return -EFAULT; 12777 12778 node_type_name = btf_field_type_name(node_field_type); 12779 if (!tnum_is_const(reg->var_off)) { 12780 verbose(env, 12781 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 12782 regno, node_type_name); 12783 return -EINVAL; 12784 } 12785 12786 node_off = reg->off + reg->var_off.value; 12787 field = reg_find_field_offset(reg, node_off, node_field_type); 12788 if (!field) { 12789 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 12790 return -EINVAL; 12791 } 12792 12793 field = *node_field; 12794 12795 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 12796 t = btf_type_by_id(reg->btf, reg->btf_id); 12797 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 12798 field->graph_root.value_btf_id, true)) { 12799 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 12800 "in struct %s, but arg is at offset=%d in struct %s\n", 12801 btf_field_type_name(head_field_type), 12802 btf_field_type_name(node_field_type), 12803 field->graph_root.node_offset, 12804 btf_name_by_offset(field->graph_root.btf, et->name_off), 12805 node_off, btf_name_by_offset(reg->btf, t->name_off)); 12806 return -EINVAL; 12807 } 12808 meta->arg_btf = reg->btf; 12809 meta->arg_btf_id = reg->btf_id; 12810 12811 if (node_off != field->graph_root.node_offset) { 12812 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 12813 node_off, btf_field_type_name(node_field_type), 12814 field->graph_root.node_offset, 12815 btf_name_by_offset(field->graph_root.btf, et->name_off)); 12816 return -EINVAL; 12817 } 12818 12819 return 0; 12820 } 12821 12822 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 12823 struct bpf_reg_state *reg, u32 regno, 12824 struct bpf_kfunc_call_arg_meta *meta) 12825 { 12826 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 12827 BPF_LIST_HEAD, BPF_LIST_NODE, 12828 &meta->arg_list_head.field); 12829 } 12830 12831 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 12832 struct bpf_reg_state *reg, u32 regno, 12833 struct bpf_kfunc_call_arg_meta *meta) 12834 { 12835 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 12836 BPF_RB_ROOT, BPF_RB_NODE, 12837 &meta->arg_rbtree_root.field); 12838 } 12839 12840 /* 12841 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 12842 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 12843 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 12844 * them can only be attached to some specific hook points. 12845 */ 12846 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 12847 { 12848 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12849 12850 switch (prog_type) { 12851 case BPF_PROG_TYPE_LSM: 12852 return true; 12853 case BPF_PROG_TYPE_TRACING: 12854 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 12855 return true; 12856 fallthrough; 12857 default: 12858 return in_sleepable(env); 12859 } 12860 } 12861 12862 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 12863 int insn_idx) 12864 { 12865 const char *func_name = meta->func_name, *ref_tname; 12866 const struct btf *btf = meta->btf; 12867 const struct btf_param *args; 12868 struct btf_record *rec; 12869 u32 i, nargs; 12870 int ret; 12871 12872 args = (const struct btf_param *)(meta->func_proto + 1); 12873 nargs = btf_type_vlen(meta->func_proto); 12874 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 12875 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 12876 MAX_BPF_FUNC_REG_ARGS); 12877 return -EINVAL; 12878 } 12879 12880 /* Check that BTF function arguments match actual types that the 12881 * verifier sees. 12882 */ 12883 for (i = 0; i < nargs; i++) { 12884 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 12885 const struct btf_type *t, *ref_t, *resolve_ret; 12886 enum bpf_arg_type arg_type = ARG_DONTCARE; 12887 u32 regno = i + 1, ref_id, type_size; 12888 bool is_ret_buf_sz = false; 12889 int kf_arg_type; 12890 12891 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 12892 12893 if (is_kfunc_arg_ignore(btf, &args[i])) 12894 continue; 12895 12896 if (is_kfunc_arg_prog(btf, &args[i])) { 12897 /* Used to reject repeated use of __prog. */ 12898 if (meta->arg_prog) { 12899 verbose(env, "Only 1 prog->aux argument supported per-kfunc\n"); 12900 return -EFAULT; 12901 } 12902 meta->arg_prog = true; 12903 cur_aux(env)->arg_prog = regno; 12904 continue; 12905 } 12906 12907 if (btf_type_is_scalar(t)) { 12908 if (reg->type != SCALAR_VALUE) { 12909 verbose(env, "R%d is not a scalar\n", regno); 12910 return -EINVAL; 12911 } 12912 12913 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 12914 if (meta->arg_constant.found) { 12915 verbose(env, "verifier internal error: only one constant argument permitted\n"); 12916 return -EFAULT; 12917 } 12918 if (!tnum_is_const(reg->var_off)) { 12919 verbose(env, "R%d must be a known constant\n", regno); 12920 return -EINVAL; 12921 } 12922 ret = mark_chain_precision(env, regno); 12923 if (ret < 0) 12924 return ret; 12925 meta->arg_constant.found = true; 12926 meta->arg_constant.value = reg->var_off.value; 12927 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 12928 meta->r0_rdonly = true; 12929 is_ret_buf_sz = true; 12930 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 12931 is_ret_buf_sz = true; 12932 } 12933 12934 if (is_ret_buf_sz) { 12935 if (meta->r0_size) { 12936 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 12937 return -EINVAL; 12938 } 12939 12940 if (!tnum_is_const(reg->var_off)) { 12941 verbose(env, "R%d is not a const\n", regno); 12942 return -EINVAL; 12943 } 12944 12945 meta->r0_size = reg->var_off.value; 12946 ret = mark_chain_precision(env, regno); 12947 if (ret) 12948 return ret; 12949 } 12950 continue; 12951 } 12952 12953 if (!btf_type_is_ptr(t)) { 12954 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 12955 return -EINVAL; 12956 } 12957 12958 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 12959 (register_is_null(reg) || type_may_be_null(reg->type)) && 12960 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 12961 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 12962 return -EACCES; 12963 } 12964 12965 if (reg->ref_obj_id) { 12966 if (is_kfunc_release(meta) && meta->ref_obj_id) { 12967 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 12968 regno, reg->ref_obj_id, 12969 meta->ref_obj_id); 12970 return -EFAULT; 12971 } 12972 meta->ref_obj_id = reg->ref_obj_id; 12973 if (is_kfunc_release(meta)) 12974 meta->release_regno = regno; 12975 } 12976 12977 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 12978 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12979 12980 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 12981 if (kf_arg_type < 0) 12982 return kf_arg_type; 12983 12984 switch (kf_arg_type) { 12985 case KF_ARG_PTR_TO_NULL: 12986 continue; 12987 case KF_ARG_PTR_TO_MAP: 12988 if (!reg->map_ptr) { 12989 verbose(env, "pointer in R%d isn't map pointer\n", regno); 12990 return -EINVAL; 12991 } 12992 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) { 12993 /* Use map_uid (which is unique id of inner map) to reject: 12994 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 12995 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 12996 * if (inner_map1 && inner_map2) { 12997 * wq = bpf_map_lookup_elem(inner_map1); 12998 * if (wq) 12999 * // mismatch would have been allowed 13000 * bpf_wq_init(wq, inner_map2); 13001 * } 13002 * 13003 * Comparing map_ptr is enough to distinguish normal and outer maps. 13004 */ 13005 if (meta->map.ptr != reg->map_ptr || 13006 meta->map.uid != reg->map_uid) { 13007 verbose(env, 13008 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 13009 meta->map.uid, reg->map_uid); 13010 return -EINVAL; 13011 } 13012 } 13013 meta->map.ptr = reg->map_ptr; 13014 meta->map.uid = reg->map_uid; 13015 fallthrough; 13016 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 13017 case KF_ARG_PTR_TO_BTF_ID: 13018 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 13019 break; 13020 13021 if (!is_trusted_reg(reg)) { 13022 if (!is_kfunc_rcu(meta)) { 13023 verbose(env, "R%d must be referenced or trusted\n", regno); 13024 return -EINVAL; 13025 } 13026 if (!is_rcu_reg(reg)) { 13027 verbose(env, "R%d must be a rcu pointer\n", regno); 13028 return -EINVAL; 13029 } 13030 } 13031 fallthrough; 13032 case KF_ARG_PTR_TO_CTX: 13033 case KF_ARG_PTR_TO_DYNPTR: 13034 case KF_ARG_PTR_TO_ITER: 13035 case KF_ARG_PTR_TO_LIST_HEAD: 13036 case KF_ARG_PTR_TO_LIST_NODE: 13037 case KF_ARG_PTR_TO_RB_ROOT: 13038 case KF_ARG_PTR_TO_RB_NODE: 13039 case KF_ARG_PTR_TO_MEM: 13040 case KF_ARG_PTR_TO_MEM_SIZE: 13041 case KF_ARG_PTR_TO_CALLBACK: 13042 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 13043 case KF_ARG_PTR_TO_CONST_STR: 13044 case KF_ARG_PTR_TO_WORKQUEUE: 13045 case KF_ARG_PTR_TO_IRQ_FLAG: 13046 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 13047 break; 13048 default: 13049 WARN_ON_ONCE(1); 13050 return -EFAULT; 13051 } 13052 13053 if (is_kfunc_release(meta) && reg->ref_obj_id) 13054 arg_type |= OBJ_RELEASE; 13055 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 13056 if (ret < 0) 13057 return ret; 13058 13059 switch (kf_arg_type) { 13060 case KF_ARG_PTR_TO_CTX: 13061 if (reg->type != PTR_TO_CTX) { 13062 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", 13063 i, reg_type_str(env, reg->type)); 13064 return -EINVAL; 13065 } 13066 13067 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 13068 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 13069 if (ret < 0) 13070 return -EINVAL; 13071 meta->ret_btf_id = ret; 13072 } 13073 break; 13074 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 13075 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 13076 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 13077 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 13078 return -EINVAL; 13079 } 13080 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 13081 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 13082 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 13083 return -EINVAL; 13084 } 13085 } else { 13086 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13087 return -EINVAL; 13088 } 13089 if (!reg->ref_obj_id) { 13090 verbose(env, "allocated object must be referenced\n"); 13091 return -EINVAL; 13092 } 13093 if (meta->btf == btf_vmlinux) { 13094 meta->arg_btf = reg->btf; 13095 meta->arg_btf_id = reg->btf_id; 13096 } 13097 break; 13098 case KF_ARG_PTR_TO_DYNPTR: 13099 { 13100 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 13101 int clone_ref_obj_id = 0; 13102 13103 if (reg->type == CONST_PTR_TO_DYNPTR) 13104 dynptr_arg_type |= MEM_RDONLY; 13105 13106 if (is_kfunc_arg_uninit(btf, &args[i])) 13107 dynptr_arg_type |= MEM_UNINIT; 13108 13109 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 13110 dynptr_arg_type |= DYNPTR_TYPE_SKB; 13111 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 13112 dynptr_arg_type |= DYNPTR_TYPE_XDP; 13113 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 13114 (dynptr_arg_type & MEM_UNINIT)) { 13115 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 13116 13117 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 13118 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 13119 return -EFAULT; 13120 } 13121 13122 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 13123 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 13124 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 13125 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 13126 return -EFAULT; 13127 } 13128 } 13129 13130 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 13131 if (ret < 0) 13132 return ret; 13133 13134 if (!(dynptr_arg_type & MEM_UNINIT)) { 13135 int id = dynptr_id(env, reg); 13136 13137 if (id < 0) { 13138 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 13139 return id; 13140 } 13141 meta->initialized_dynptr.id = id; 13142 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 13143 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 13144 } 13145 13146 break; 13147 } 13148 case KF_ARG_PTR_TO_ITER: 13149 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 13150 if (!check_css_task_iter_allowlist(env)) { 13151 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 13152 return -EINVAL; 13153 } 13154 } 13155 ret = process_iter_arg(env, regno, insn_idx, meta); 13156 if (ret < 0) 13157 return ret; 13158 break; 13159 case KF_ARG_PTR_TO_LIST_HEAD: 13160 if (reg->type != PTR_TO_MAP_VALUE && 13161 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13162 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 13163 return -EINVAL; 13164 } 13165 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 13166 verbose(env, "allocated object must be referenced\n"); 13167 return -EINVAL; 13168 } 13169 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 13170 if (ret < 0) 13171 return ret; 13172 break; 13173 case KF_ARG_PTR_TO_RB_ROOT: 13174 if (reg->type != PTR_TO_MAP_VALUE && 13175 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13176 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 13177 return -EINVAL; 13178 } 13179 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 13180 verbose(env, "allocated object must be referenced\n"); 13181 return -EINVAL; 13182 } 13183 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 13184 if (ret < 0) 13185 return ret; 13186 break; 13187 case KF_ARG_PTR_TO_LIST_NODE: 13188 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13189 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13190 return -EINVAL; 13191 } 13192 if (!reg->ref_obj_id) { 13193 verbose(env, "allocated object must be referenced\n"); 13194 return -EINVAL; 13195 } 13196 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 13197 if (ret < 0) 13198 return ret; 13199 break; 13200 case KF_ARG_PTR_TO_RB_NODE: 13201 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13202 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13203 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13204 return -EINVAL; 13205 } 13206 if (!reg->ref_obj_id) { 13207 verbose(env, "allocated object must be referenced\n"); 13208 return -EINVAL; 13209 } 13210 } else { 13211 if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) { 13212 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name); 13213 return -EINVAL; 13214 } 13215 if (in_rbtree_lock_required_cb(env)) { 13216 verbose(env, "%s not allowed in rbtree cb\n", func_name); 13217 return -EINVAL; 13218 } 13219 } 13220 13221 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 13222 if (ret < 0) 13223 return ret; 13224 break; 13225 case KF_ARG_PTR_TO_MAP: 13226 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 13227 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 13228 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 13229 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 13230 fallthrough; 13231 case KF_ARG_PTR_TO_BTF_ID: 13232 /* Only base_type is checked, further checks are done here */ 13233 if ((base_type(reg->type) != PTR_TO_BTF_ID || 13234 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 13235 !reg2btf_ids[base_type(reg->type)]) { 13236 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 13237 verbose(env, "expected %s or socket\n", 13238 reg_type_str(env, base_type(reg->type) | 13239 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 13240 return -EINVAL; 13241 } 13242 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 13243 if (ret < 0) 13244 return ret; 13245 break; 13246 case KF_ARG_PTR_TO_MEM: 13247 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 13248 if (IS_ERR(resolve_ret)) { 13249 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 13250 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 13251 return -EINVAL; 13252 } 13253 ret = check_mem_reg(env, reg, regno, type_size); 13254 if (ret < 0) 13255 return ret; 13256 break; 13257 case KF_ARG_PTR_TO_MEM_SIZE: 13258 { 13259 struct bpf_reg_state *buff_reg = ®s[regno]; 13260 const struct btf_param *buff_arg = &args[i]; 13261 struct bpf_reg_state *size_reg = ®s[regno + 1]; 13262 const struct btf_param *size_arg = &args[i + 1]; 13263 13264 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 13265 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 13266 if (ret < 0) { 13267 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 13268 return ret; 13269 } 13270 } 13271 13272 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 13273 if (meta->arg_constant.found) { 13274 verbose(env, "verifier internal error: only one constant argument permitted\n"); 13275 return -EFAULT; 13276 } 13277 if (!tnum_is_const(size_reg->var_off)) { 13278 verbose(env, "R%d must be a known constant\n", regno + 1); 13279 return -EINVAL; 13280 } 13281 meta->arg_constant.found = true; 13282 meta->arg_constant.value = size_reg->var_off.value; 13283 } 13284 13285 /* Skip next '__sz' or '__szk' argument */ 13286 i++; 13287 break; 13288 } 13289 case KF_ARG_PTR_TO_CALLBACK: 13290 if (reg->type != PTR_TO_FUNC) { 13291 verbose(env, "arg%d expected pointer to func\n", i); 13292 return -EINVAL; 13293 } 13294 meta->subprogno = reg->subprogno; 13295 break; 13296 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 13297 if (!type_is_ptr_alloc_obj(reg->type)) { 13298 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 13299 return -EINVAL; 13300 } 13301 if (!type_is_non_owning_ref(reg->type)) 13302 meta->arg_owning_ref = true; 13303 13304 rec = reg_btf_record(reg); 13305 if (!rec) { 13306 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 13307 return -EFAULT; 13308 } 13309 13310 if (rec->refcount_off < 0) { 13311 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 13312 return -EINVAL; 13313 } 13314 13315 meta->arg_btf = reg->btf; 13316 meta->arg_btf_id = reg->btf_id; 13317 break; 13318 case KF_ARG_PTR_TO_CONST_STR: 13319 if (reg->type != PTR_TO_MAP_VALUE) { 13320 verbose(env, "arg#%d doesn't point to a const string\n", i); 13321 return -EINVAL; 13322 } 13323 ret = check_reg_const_str(env, reg, regno); 13324 if (ret) 13325 return ret; 13326 break; 13327 case KF_ARG_PTR_TO_WORKQUEUE: 13328 if (reg->type != PTR_TO_MAP_VALUE) { 13329 verbose(env, "arg#%d doesn't point to a map value\n", i); 13330 return -EINVAL; 13331 } 13332 ret = process_wq_func(env, regno, meta); 13333 if (ret < 0) 13334 return ret; 13335 break; 13336 case KF_ARG_PTR_TO_IRQ_FLAG: 13337 if (reg->type != PTR_TO_STACK) { 13338 verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i); 13339 return -EINVAL; 13340 } 13341 ret = process_irq_flag(env, regno, meta); 13342 if (ret < 0) 13343 return ret; 13344 break; 13345 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 13346 { 13347 int flags = PROCESS_RES_LOCK; 13348 13349 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13350 verbose(env, "arg#%d doesn't point to map value or allocated object\n", i); 13351 return -EINVAL; 13352 } 13353 13354 if (!is_bpf_res_spin_lock_kfunc(meta->func_id)) 13355 return -EFAULT; 13356 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13357 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 13358 flags |= PROCESS_SPIN_LOCK; 13359 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 13360 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 13361 flags |= PROCESS_LOCK_IRQ; 13362 ret = process_spin_lock(env, regno, flags); 13363 if (ret < 0) 13364 return ret; 13365 break; 13366 } 13367 } 13368 } 13369 13370 if (is_kfunc_release(meta) && !meta->release_regno) { 13371 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 13372 func_name); 13373 return -EINVAL; 13374 } 13375 13376 return 0; 13377 } 13378 13379 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 13380 struct bpf_insn *insn, 13381 struct bpf_kfunc_call_arg_meta *meta, 13382 const char **kfunc_name) 13383 { 13384 const struct btf_type *func, *func_proto; 13385 u32 func_id, *kfunc_flags; 13386 const char *func_name; 13387 struct btf *desc_btf; 13388 13389 if (kfunc_name) 13390 *kfunc_name = NULL; 13391 13392 if (!insn->imm) 13393 return -EINVAL; 13394 13395 desc_btf = find_kfunc_desc_btf(env, insn->off); 13396 if (IS_ERR(desc_btf)) 13397 return PTR_ERR(desc_btf); 13398 13399 func_id = insn->imm; 13400 func = btf_type_by_id(desc_btf, func_id); 13401 func_name = btf_name_by_offset(desc_btf, func->name_off); 13402 if (kfunc_name) 13403 *kfunc_name = func_name; 13404 func_proto = btf_type_by_id(desc_btf, func->type); 13405 13406 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 13407 if (!kfunc_flags) { 13408 return -EACCES; 13409 } 13410 13411 memset(meta, 0, sizeof(*meta)); 13412 meta->btf = desc_btf; 13413 meta->func_id = func_id; 13414 meta->kfunc_flags = *kfunc_flags; 13415 meta->func_proto = func_proto; 13416 meta->func_name = func_name; 13417 13418 return 0; 13419 } 13420 13421 /* check special kfuncs and return: 13422 * 1 - not fall-through to 'else' branch, continue verification 13423 * 0 - fall-through to 'else' branch 13424 * < 0 - not fall-through to 'else' branch, return error 13425 */ 13426 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 13427 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 13428 const struct btf_type *ptr_type, struct btf *desc_btf) 13429 { 13430 const struct btf_type *ret_t; 13431 int err = 0; 13432 13433 if (meta->btf != btf_vmlinux) 13434 return 0; 13435 13436 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 13437 meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13438 struct btf_struct_meta *struct_meta; 13439 struct btf *ret_btf; 13440 u32 ret_btf_id; 13441 13442 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 13443 return -ENOMEM; 13444 13445 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 13446 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 13447 return -EINVAL; 13448 } 13449 13450 ret_btf = env->prog->aux->btf; 13451 ret_btf_id = meta->arg_constant.value; 13452 13453 /* This may be NULL due to user not supplying a BTF */ 13454 if (!ret_btf) { 13455 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 13456 return -EINVAL; 13457 } 13458 13459 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 13460 if (!ret_t || !__btf_type_is_struct(ret_t)) { 13461 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 13462 return -EINVAL; 13463 } 13464 13465 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13466 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 13467 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 13468 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 13469 return -EINVAL; 13470 } 13471 13472 if (!bpf_global_percpu_ma_set) { 13473 mutex_lock(&bpf_percpu_ma_lock); 13474 if (!bpf_global_percpu_ma_set) { 13475 /* Charge memory allocated with bpf_global_percpu_ma to 13476 * root memcg. The obj_cgroup for root memcg is NULL. 13477 */ 13478 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 13479 if (!err) 13480 bpf_global_percpu_ma_set = true; 13481 } 13482 mutex_unlock(&bpf_percpu_ma_lock); 13483 if (err) 13484 return err; 13485 } 13486 13487 mutex_lock(&bpf_percpu_ma_lock); 13488 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 13489 mutex_unlock(&bpf_percpu_ma_lock); 13490 if (err) 13491 return err; 13492 } 13493 13494 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 13495 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13496 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 13497 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 13498 return -EINVAL; 13499 } 13500 13501 if (struct_meta) { 13502 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 13503 return -EINVAL; 13504 } 13505 } 13506 13507 mark_reg_known_zero(env, regs, BPF_REG_0); 13508 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 13509 regs[BPF_REG_0].btf = ret_btf; 13510 regs[BPF_REG_0].btf_id = ret_btf_id; 13511 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 13512 regs[BPF_REG_0].type |= MEM_PERCPU; 13513 13514 insn_aux->obj_new_size = ret_t->size; 13515 insn_aux->kptr_struct_meta = struct_meta; 13516 } else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 13517 mark_reg_known_zero(env, regs, BPF_REG_0); 13518 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 13519 regs[BPF_REG_0].btf = meta->arg_btf; 13520 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 13521 13522 insn_aux->kptr_struct_meta = 13523 btf_find_struct_meta(meta->arg_btf, 13524 meta->arg_btf_id); 13525 } else if (is_list_node_type(ptr_type)) { 13526 struct btf_field *field = meta->arg_list_head.field; 13527 13528 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 13529 } else if (is_rbtree_node_type(ptr_type)) { 13530 struct btf_field *field = meta->arg_rbtree_root.field; 13531 13532 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 13533 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 13534 mark_reg_known_zero(env, regs, BPF_REG_0); 13535 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 13536 regs[BPF_REG_0].btf = desc_btf; 13537 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 13538 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 13539 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 13540 if (!ret_t || !btf_type_is_struct(ret_t)) { 13541 verbose(env, 13542 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 13543 return -EINVAL; 13544 } 13545 13546 mark_reg_known_zero(env, regs, BPF_REG_0); 13547 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 13548 regs[BPF_REG_0].btf = desc_btf; 13549 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 13550 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 13551 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 13552 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type); 13553 13554 mark_reg_known_zero(env, regs, BPF_REG_0); 13555 13556 if (!meta->arg_constant.found) { 13557 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 13558 return -EFAULT; 13559 } 13560 13561 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 13562 13563 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 13564 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 13565 13566 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 13567 regs[BPF_REG_0].type |= MEM_RDONLY; 13568 } else { 13569 /* this will set env->seen_direct_write to true */ 13570 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 13571 verbose(env, "the prog does not allow writes to packet data\n"); 13572 return -EINVAL; 13573 } 13574 } 13575 13576 if (!meta->initialized_dynptr.id) { 13577 verbose(env, "verifier internal error: no dynptr id\n"); 13578 return -EFAULT; 13579 } 13580 regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id; 13581 13582 /* we don't need to set BPF_REG_0's ref obj id 13583 * because packet slices are not refcounted (see 13584 * dynptr_type_refcounted) 13585 */ 13586 } else { 13587 return 0; 13588 } 13589 13590 return 1; 13591 } 13592 13593 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 13594 13595 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 13596 int *insn_idx_p) 13597 { 13598 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 13599 u32 i, nargs, ptr_type_id, release_ref_obj_id; 13600 struct bpf_reg_state *regs = cur_regs(env); 13601 const char *func_name, *ptr_type_name; 13602 const struct btf_type *t, *ptr_type; 13603 struct bpf_kfunc_call_arg_meta meta; 13604 struct bpf_insn_aux_data *insn_aux; 13605 int err, insn_idx = *insn_idx_p; 13606 const struct btf_param *args; 13607 struct btf *desc_btf; 13608 13609 /* skip for now, but return error when we find this in fixup_kfunc_call */ 13610 if (!insn->imm) 13611 return 0; 13612 13613 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 13614 if (err == -EACCES && func_name) 13615 verbose(env, "calling kernel function %s is not allowed\n", func_name); 13616 if (err) 13617 return err; 13618 desc_btf = meta.btf; 13619 insn_aux = &env->insn_aux_data[insn_idx]; 13620 13621 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 13622 13623 if (!insn->off && 13624 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 13625 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 13626 struct bpf_verifier_state *branch; 13627 struct bpf_reg_state *regs; 13628 13629 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 13630 if (!branch) { 13631 verbose(env, "failed to push state for failed lock acquisition\n"); 13632 return -ENOMEM; 13633 } 13634 13635 regs = branch->frame[branch->curframe]->regs; 13636 13637 /* Clear r0-r5 registers in forked state */ 13638 for (i = 0; i < CALLER_SAVED_REGS; i++) 13639 mark_reg_not_init(env, regs, caller_saved[i]); 13640 13641 mark_reg_unknown(env, regs, BPF_REG_0); 13642 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 13643 if (err) { 13644 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 13645 return err; 13646 } 13647 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32)); 13648 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 13649 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 13650 return -EFAULT; 13651 } 13652 13653 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 13654 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 13655 return -EACCES; 13656 } 13657 13658 sleepable = is_kfunc_sleepable(&meta); 13659 if (sleepable && !in_sleepable(env)) { 13660 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 13661 return -EACCES; 13662 } 13663 13664 /* Check the arguments */ 13665 err = check_kfunc_args(env, &meta, insn_idx); 13666 if (err < 0) 13667 return err; 13668 13669 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13670 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13671 set_rbtree_add_callback_state); 13672 if (err) { 13673 verbose(env, "kfunc %s#%d failed callback verification\n", 13674 func_name, meta.func_id); 13675 return err; 13676 } 13677 } 13678 13679 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 13680 meta.r0_size = sizeof(u64); 13681 meta.r0_rdonly = false; 13682 } 13683 13684 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) { 13685 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13686 set_timer_callback_state); 13687 if (err) { 13688 verbose(env, "kfunc %s#%d failed callback verification\n", 13689 func_name, meta.func_id); 13690 return err; 13691 } 13692 } 13693 13694 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 13695 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 13696 13697 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 13698 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 13699 13700 if (env->cur_state->active_rcu_lock) { 13701 struct bpf_func_state *state; 13702 struct bpf_reg_state *reg; 13703 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 13704 13705 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 13706 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 13707 return -EACCES; 13708 } 13709 13710 if (rcu_lock) { 13711 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 13712 return -EINVAL; 13713 } else if (rcu_unlock) { 13714 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 13715 if (reg->type & MEM_RCU) { 13716 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 13717 reg->type |= PTR_UNTRUSTED; 13718 } 13719 })); 13720 env->cur_state->active_rcu_lock = false; 13721 } else if (sleepable) { 13722 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 13723 return -EACCES; 13724 } 13725 } else if (rcu_lock) { 13726 env->cur_state->active_rcu_lock = true; 13727 } else if (rcu_unlock) { 13728 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 13729 return -EINVAL; 13730 } 13731 13732 if (env->cur_state->active_preempt_locks) { 13733 if (preempt_disable) { 13734 env->cur_state->active_preempt_locks++; 13735 } else if (preempt_enable) { 13736 env->cur_state->active_preempt_locks--; 13737 } else if (sleepable) { 13738 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name); 13739 return -EACCES; 13740 } 13741 } else if (preempt_disable) { 13742 env->cur_state->active_preempt_locks++; 13743 } else if (preempt_enable) { 13744 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 13745 return -EINVAL; 13746 } 13747 13748 if (env->cur_state->active_irq_id && sleepable) { 13749 verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name); 13750 return -EACCES; 13751 } 13752 13753 /* In case of release function, we get register number of refcounted 13754 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 13755 */ 13756 if (meta.release_regno) { 13757 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 13758 if (err) { 13759 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13760 func_name, meta.func_id); 13761 return err; 13762 } 13763 } 13764 13765 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 13766 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 13767 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13768 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 13769 insn_aux->insert_off = regs[BPF_REG_2].off; 13770 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13771 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 13772 if (err) { 13773 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 13774 func_name, meta.func_id); 13775 return err; 13776 } 13777 13778 err = release_reference(env, release_ref_obj_id); 13779 if (err) { 13780 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13781 func_name, meta.func_id); 13782 return err; 13783 } 13784 } 13785 13786 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 13787 if (!bpf_jit_supports_exceptions()) { 13788 verbose(env, "JIT does not support calling kfunc %s#%d\n", 13789 func_name, meta.func_id); 13790 return -ENOTSUPP; 13791 } 13792 env->seen_exception = true; 13793 13794 /* In the case of the default callback, the cookie value passed 13795 * to bpf_throw becomes the return value of the program. 13796 */ 13797 if (!env->exception_callback_subprog) { 13798 err = check_return_code(env, BPF_REG_1, "R1"); 13799 if (err < 0) 13800 return err; 13801 } 13802 } 13803 13804 for (i = 0; i < CALLER_SAVED_REGS; i++) 13805 mark_reg_not_init(env, regs, caller_saved[i]); 13806 13807 /* Check return type */ 13808 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13809 13810 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13811 /* Only exception is bpf_obj_new_impl */ 13812 if (meta.btf != btf_vmlinux || 13813 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 13814 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 13815 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 13816 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13817 return -EINVAL; 13818 } 13819 } 13820 13821 if (btf_type_is_scalar(t)) { 13822 mark_reg_unknown(env, regs, BPF_REG_0); 13823 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13824 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13825 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 13826 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 13827 } else if (btf_type_is_ptr(t)) { 13828 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 13829 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 13830 if (err) { 13831 if (err < 0) 13832 return err; 13833 } else if (btf_type_is_void(ptr_type)) { 13834 /* kfunc returning 'void *' is equivalent to returning scalar */ 13835 mark_reg_unknown(env, regs, BPF_REG_0); 13836 } else if (!__btf_type_is_struct(ptr_type)) { 13837 if (!meta.r0_size) { 13838 __u32 sz; 13839 13840 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 13841 meta.r0_size = sz; 13842 meta.r0_rdonly = true; 13843 } 13844 } 13845 if (!meta.r0_size) { 13846 ptr_type_name = btf_name_by_offset(desc_btf, 13847 ptr_type->name_off); 13848 verbose(env, 13849 "kernel function %s returns pointer type %s %s is not supported\n", 13850 func_name, 13851 btf_type_str(ptr_type), 13852 ptr_type_name); 13853 return -EINVAL; 13854 } 13855 13856 mark_reg_known_zero(env, regs, BPF_REG_0); 13857 regs[BPF_REG_0].type = PTR_TO_MEM; 13858 regs[BPF_REG_0].mem_size = meta.r0_size; 13859 13860 if (meta.r0_rdonly) 13861 regs[BPF_REG_0].type |= MEM_RDONLY; 13862 13863 /* Ensures we don't access the memory after a release_reference() */ 13864 if (meta.ref_obj_id) 13865 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 13866 } else { 13867 mark_reg_known_zero(env, regs, BPF_REG_0); 13868 regs[BPF_REG_0].btf = desc_btf; 13869 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 13870 regs[BPF_REG_0].btf_id = ptr_type_id; 13871 13872 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 13873 regs[BPF_REG_0].type |= PTR_UNTRUSTED; 13874 13875 if (is_iter_next_kfunc(&meta)) { 13876 struct bpf_reg_state *cur_iter; 13877 13878 cur_iter = get_iter_from_state(env->cur_state, &meta); 13879 13880 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */ 13881 regs[BPF_REG_0].type |= MEM_RCU; 13882 else 13883 regs[BPF_REG_0].type |= PTR_TRUSTED; 13884 } 13885 } 13886 13887 if (is_kfunc_ret_null(&meta)) { 13888 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 13889 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 13890 regs[BPF_REG_0].id = ++env->id_gen; 13891 } 13892 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 13893 if (is_kfunc_acquire(&meta)) { 13894 int id = acquire_reference(env, insn_idx); 13895 13896 if (id < 0) 13897 return id; 13898 if (is_kfunc_ret_null(&meta)) 13899 regs[BPF_REG_0].id = id; 13900 regs[BPF_REG_0].ref_obj_id = id; 13901 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 13902 ref_set_non_owning(env, ®s[BPF_REG_0]); 13903 } 13904 13905 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 13906 regs[BPF_REG_0].id = ++env->id_gen; 13907 } else if (btf_type_is_void(t)) { 13908 if (meta.btf == btf_vmlinux) { 13909 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 13910 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 13911 insn_aux->kptr_struct_meta = 13912 btf_find_struct_meta(meta.arg_btf, 13913 meta.arg_btf_id); 13914 } 13915 } 13916 } 13917 13918 nargs = btf_type_vlen(meta.func_proto); 13919 args = (const struct btf_param *)(meta.func_proto + 1); 13920 for (i = 0; i < nargs; i++) { 13921 u32 regno = i + 1; 13922 13923 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 13924 if (btf_type_is_ptr(t)) 13925 mark_btf_func_reg_size(env, regno, sizeof(void *)); 13926 else 13927 /* scalar. ensured by btf_check_kfunc_arg_match() */ 13928 mark_btf_func_reg_size(env, regno, t->size); 13929 } 13930 13931 if (is_iter_next_kfunc(&meta)) { 13932 err = process_iter_next_call(env, insn_idx, &meta); 13933 if (err) 13934 return err; 13935 } 13936 13937 return 0; 13938 } 13939 13940 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 13941 const struct bpf_reg_state *reg, 13942 enum bpf_reg_type type) 13943 { 13944 bool known = tnum_is_const(reg->var_off); 13945 s64 val = reg->var_off.value; 13946 s64 smin = reg->smin_value; 13947 13948 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13949 verbose(env, "math between %s pointer and %lld is not allowed\n", 13950 reg_type_str(env, type), val); 13951 return false; 13952 } 13953 13954 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 13955 verbose(env, "%s pointer offset %d is not allowed\n", 13956 reg_type_str(env, type), reg->off); 13957 return false; 13958 } 13959 13960 if (smin == S64_MIN) { 13961 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 13962 reg_type_str(env, type)); 13963 return false; 13964 } 13965 13966 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13967 verbose(env, "value %lld makes %s pointer be out of bounds\n", 13968 smin, reg_type_str(env, type)); 13969 return false; 13970 } 13971 13972 return true; 13973 } 13974 13975 enum { 13976 REASON_BOUNDS = -1, 13977 REASON_TYPE = -2, 13978 REASON_PATHS = -3, 13979 REASON_LIMIT = -4, 13980 REASON_STACK = -5, 13981 }; 13982 13983 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 13984 u32 *alu_limit, bool mask_to_left) 13985 { 13986 u32 max = 0, ptr_limit = 0; 13987 13988 switch (ptr_reg->type) { 13989 case PTR_TO_STACK: 13990 /* Offset 0 is out-of-bounds, but acceptable start for the 13991 * left direction, see BPF_REG_FP. Also, unknown scalar 13992 * offset where we would need to deal with min/max bounds is 13993 * currently prohibited for unprivileged. 13994 */ 13995 max = MAX_BPF_STACK + mask_to_left; 13996 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 13997 break; 13998 case PTR_TO_MAP_VALUE: 13999 max = ptr_reg->map_ptr->value_size; 14000 ptr_limit = (mask_to_left ? 14001 ptr_reg->smin_value : 14002 ptr_reg->umax_value) + ptr_reg->off; 14003 break; 14004 default: 14005 return REASON_TYPE; 14006 } 14007 14008 if (ptr_limit >= max) 14009 return REASON_LIMIT; 14010 *alu_limit = ptr_limit; 14011 return 0; 14012 } 14013 14014 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 14015 const struct bpf_insn *insn) 14016 { 14017 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 14018 } 14019 14020 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 14021 u32 alu_state, u32 alu_limit) 14022 { 14023 /* If we arrived here from different branches with different 14024 * state or limits to sanitize, then this won't work. 14025 */ 14026 if (aux->alu_state && 14027 (aux->alu_state != alu_state || 14028 aux->alu_limit != alu_limit)) 14029 return REASON_PATHS; 14030 14031 /* Corresponding fixup done in do_misc_fixups(). */ 14032 aux->alu_state = alu_state; 14033 aux->alu_limit = alu_limit; 14034 return 0; 14035 } 14036 14037 static int sanitize_val_alu(struct bpf_verifier_env *env, 14038 struct bpf_insn *insn) 14039 { 14040 struct bpf_insn_aux_data *aux = cur_aux(env); 14041 14042 if (can_skip_alu_sanitation(env, insn)) 14043 return 0; 14044 14045 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 14046 } 14047 14048 static bool sanitize_needed(u8 opcode) 14049 { 14050 return opcode == BPF_ADD || opcode == BPF_SUB; 14051 } 14052 14053 struct bpf_sanitize_info { 14054 struct bpf_insn_aux_data aux; 14055 bool mask_to_left; 14056 }; 14057 14058 static struct bpf_verifier_state * 14059 sanitize_speculative_path(struct bpf_verifier_env *env, 14060 const struct bpf_insn *insn, 14061 u32 next_idx, u32 curr_idx) 14062 { 14063 struct bpf_verifier_state *branch; 14064 struct bpf_reg_state *regs; 14065 14066 branch = push_stack(env, next_idx, curr_idx, true); 14067 if (branch && insn) { 14068 regs = branch->frame[branch->curframe]->regs; 14069 if (BPF_SRC(insn->code) == BPF_K) { 14070 mark_reg_unknown(env, regs, insn->dst_reg); 14071 } else if (BPF_SRC(insn->code) == BPF_X) { 14072 mark_reg_unknown(env, regs, insn->dst_reg); 14073 mark_reg_unknown(env, regs, insn->src_reg); 14074 } 14075 } 14076 return branch; 14077 } 14078 14079 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 14080 struct bpf_insn *insn, 14081 const struct bpf_reg_state *ptr_reg, 14082 const struct bpf_reg_state *off_reg, 14083 struct bpf_reg_state *dst_reg, 14084 struct bpf_sanitize_info *info, 14085 const bool commit_window) 14086 { 14087 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 14088 struct bpf_verifier_state *vstate = env->cur_state; 14089 bool off_is_imm = tnum_is_const(off_reg->var_off); 14090 bool off_is_neg = off_reg->smin_value < 0; 14091 bool ptr_is_dst_reg = ptr_reg == dst_reg; 14092 u8 opcode = BPF_OP(insn->code); 14093 u32 alu_state, alu_limit; 14094 struct bpf_reg_state tmp; 14095 bool ret; 14096 int err; 14097 14098 if (can_skip_alu_sanitation(env, insn)) 14099 return 0; 14100 14101 /* We already marked aux for masking from non-speculative 14102 * paths, thus we got here in the first place. We only care 14103 * to explore bad access from here. 14104 */ 14105 if (vstate->speculative) 14106 goto do_sim; 14107 14108 if (!commit_window) { 14109 if (!tnum_is_const(off_reg->var_off) && 14110 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 14111 return REASON_BOUNDS; 14112 14113 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 14114 (opcode == BPF_SUB && !off_is_neg); 14115 } 14116 14117 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 14118 if (err < 0) 14119 return err; 14120 14121 if (commit_window) { 14122 /* In commit phase we narrow the masking window based on 14123 * the observed pointer move after the simulated operation. 14124 */ 14125 alu_state = info->aux.alu_state; 14126 alu_limit = abs(info->aux.alu_limit - alu_limit); 14127 } else { 14128 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 14129 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 14130 alu_state |= ptr_is_dst_reg ? 14131 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 14132 14133 /* Limit pruning on unknown scalars to enable deep search for 14134 * potential masking differences from other program paths. 14135 */ 14136 if (!off_is_imm) 14137 env->explore_alu_limits = true; 14138 } 14139 14140 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 14141 if (err < 0) 14142 return err; 14143 do_sim: 14144 /* If we're in commit phase, we're done here given we already 14145 * pushed the truncated dst_reg into the speculative verification 14146 * stack. 14147 * 14148 * Also, when register is a known constant, we rewrite register-based 14149 * operation to immediate-based, and thus do not need masking (and as 14150 * a consequence, do not need to simulate the zero-truncation either). 14151 */ 14152 if (commit_window || off_is_imm) 14153 return 0; 14154 14155 /* Simulate and find potential out-of-bounds access under 14156 * speculative execution from truncation as a result of 14157 * masking when off was not within expected range. If off 14158 * sits in dst, then we temporarily need to move ptr there 14159 * to simulate dst (== 0) +/-= ptr. Needed, for example, 14160 * for cases where we use K-based arithmetic in one direction 14161 * and truncated reg-based in the other in order to explore 14162 * bad access. 14163 */ 14164 if (!ptr_is_dst_reg) { 14165 tmp = *dst_reg; 14166 copy_register_state(dst_reg, ptr_reg); 14167 } 14168 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 14169 env->insn_idx); 14170 if (!ptr_is_dst_reg && ret) 14171 *dst_reg = tmp; 14172 return !ret ? REASON_STACK : 0; 14173 } 14174 14175 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 14176 { 14177 struct bpf_verifier_state *vstate = env->cur_state; 14178 14179 /* If we simulate paths under speculation, we don't update the 14180 * insn as 'seen' such that when we verify unreachable paths in 14181 * the non-speculative domain, sanitize_dead_code() can still 14182 * rewrite/sanitize them. 14183 */ 14184 if (!vstate->speculative) 14185 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 14186 } 14187 14188 static int sanitize_err(struct bpf_verifier_env *env, 14189 const struct bpf_insn *insn, int reason, 14190 const struct bpf_reg_state *off_reg, 14191 const struct bpf_reg_state *dst_reg) 14192 { 14193 static const char *err = "pointer arithmetic with it prohibited for !root"; 14194 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 14195 u32 dst = insn->dst_reg, src = insn->src_reg; 14196 14197 switch (reason) { 14198 case REASON_BOUNDS: 14199 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 14200 off_reg == dst_reg ? dst : src, err); 14201 break; 14202 case REASON_TYPE: 14203 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 14204 off_reg == dst_reg ? src : dst, err); 14205 break; 14206 case REASON_PATHS: 14207 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 14208 dst, op, err); 14209 break; 14210 case REASON_LIMIT: 14211 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 14212 dst, op, err); 14213 break; 14214 case REASON_STACK: 14215 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 14216 dst, err); 14217 break; 14218 default: 14219 verbose(env, "verifier internal error: unknown reason (%d)\n", 14220 reason); 14221 break; 14222 } 14223 14224 return -EACCES; 14225 } 14226 14227 /* check that stack access falls within stack limits and that 'reg' doesn't 14228 * have a variable offset. 14229 * 14230 * Variable offset is prohibited for unprivileged mode for simplicity since it 14231 * requires corresponding support in Spectre masking for stack ALU. See also 14232 * retrieve_ptr_limit(). 14233 * 14234 * 14235 * 'off' includes 'reg->off'. 14236 */ 14237 static int check_stack_access_for_ptr_arithmetic( 14238 struct bpf_verifier_env *env, 14239 int regno, 14240 const struct bpf_reg_state *reg, 14241 int off) 14242 { 14243 if (!tnum_is_const(reg->var_off)) { 14244 char tn_buf[48]; 14245 14246 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 14247 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 14248 regno, tn_buf, off); 14249 return -EACCES; 14250 } 14251 14252 if (off >= 0 || off < -MAX_BPF_STACK) { 14253 verbose(env, "R%d stack pointer arithmetic goes out of range, " 14254 "prohibited for !root; off=%d\n", regno, off); 14255 return -EACCES; 14256 } 14257 14258 return 0; 14259 } 14260 14261 static int sanitize_check_bounds(struct bpf_verifier_env *env, 14262 const struct bpf_insn *insn, 14263 const struct bpf_reg_state *dst_reg) 14264 { 14265 u32 dst = insn->dst_reg; 14266 14267 /* For unprivileged we require that resulting offset must be in bounds 14268 * in order to be able to sanitize access later on. 14269 */ 14270 if (env->bypass_spec_v1) 14271 return 0; 14272 14273 switch (dst_reg->type) { 14274 case PTR_TO_STACK: 14275 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 14276 dst_reg->off + dst_reg->var_off.value)) 14277 return -EACCES; 14278 break; 14279 case PTR_TO_MAP_VALUE: 14280 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 14281 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 14282 "prohibited for !root\n", dst); 14283 return -EACCES; 14284 } 14285 break; 14286 default: 14287 break; 14288 } 14289 14290 return 0; 14291 } 14292 14293 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 14294 * Caller should also handle BPF_MOV case separately. 14295 * If we return -EACCES, caller may want to try again treating pointer as a 14296 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 14297 */ 14298 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 14299 struct bpf_insn *insn, 14300 const struct bpf_reg_state *ptr_reg, 14301 const struct bpf_reg_state *off_reg) 14302 { 14303 struct bpf_verifier_state *vstate = env->cur_state; 14304 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14305 struct bpf_reg_state *regs = state->regs, *dst_reg; 14306 bool known = tnum_is_const(off_reg->var_off); 14307 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 14308 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 14309 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 14310 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 14311 struct bpf_sanitize_info info = {}; 14312 u8 opcode = BPF_OP(insn->code); 14313 u32 dst = insn->dst_reg; 14314 int ret; 14315 14316 dst_reg = ®s[dst]; 14317 14318 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 14319 smin_val > smax_val || umin_val > umax_val) { 14320 /* Taint dst register if offset had invalid bounds derived from 14321 * e.g. dead branches. 14322 */ 14323 __mark_reg_unknown(env, dst_reg); 14324 return 0; 14325 } 14326 14327 if (BPF_CLASS(insn->code) != BPF_ALU64) { 14328 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 14329 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14330 __mark_reg_unknown(env, dst_reg); 14331 return 0; 14332 } 14333 14334 verbose(env, 14335 "R%d 32-bit pointer arithmetic prohibited\n", 14336 dst); 14337 return -EACCES; 14338 } 14339 14340 if (ptr_reg->type & PTR_MAYBE_NULL) { 14341 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 14342 dst, reg_type_str(env, ptr_reg->type)); 14343 return -EACCES; 14344 } 14345 14346 switch (base_type(ptr_reg->type)) { 14347 case PTR_TO_CTX: 14348 case PTR_TO_MAP_VALUE: 14349 case PTR_TO_MAP_KEY: 14350 case PTR_TO_STACK: 14351 case PTR_TO_PACKET_META: 14352 case PTR_TO_PACKET: 14353 case PTR_TO_TP_BUFFER: 14354 case PTR_TO_BTF_ID: 14355 case PTR_TO_MEM: 14356 case PTR_TO_BUF: 14357 case PTR_TO_FUNC: 14358 case CONST_PTR_TO_DYNPTR: 14359 break; 14360 case PTR_TO_FLOW_KEYS: 14361 if (known) 14362 break; 14363 fallthrough; 14364 case CONST_PTR_TO_MAP: 14365 /* smin_val represents the known value */ 14366 if (known && smin_val == 0 && opcode == BPF_ADD) 14367 break; 14368 fallthrough; 14369 default: 14370 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 14371 dst, reg_type_str(env, ptr_reg->type)); 14372 return -EACCES; 14373 } 14374 14375 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 14376 * The id may be overwritten later if we create a new variable offset. 14377 */ 14378 dst_reg->type = ptr_reg->type; 14379 dst_reg->id = ptr_reg->id; 14380 14381 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 14382 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 14383 return -EINVAL; 14384 14385 /* pointer types do not carry 32-bit bounds at the moment. */ 14386 __mark_reg32_unbounded(dst_reg); 14387 14388 if (sanitize_needed(opcode)) { 14389 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 14390 &info, false); 14391 if (ret < 0) 14392 return sanitize_err(env, insn, ret, off_reg, dst_reg); 14393 } 14394 14395 switch (opcode) { 14396 case BPF_ADD: 14397 /* We can take a fixed offset as long as it doesn't overflow 14398 * the s32 'off' field 14399 */ 14400 if (known && (ptr_reg->off + smin_val == 14401 (s64)(s32)(ptr_reg->off + smin_val))) { 14402 /* pointer += K. Accumulate it into fixed offset */ 14403 dst_reg->smin_value = smin_ptr; 14404 dst_reg->smax_value = smax_ptr; 14405 dst_reg->umin_value = umin_ptr; 14406 dst_reg->umax_value = umax_ptr; 14407 dst_reg->var_off = ptr_reg->var_off; 14408 dst_reg->off = ptr_reg->off + smin_val; 14409 dst_reg->raw = ptr_reg->raw; 14410 break; 14411 } 14412 /* A new variable offset is created. Note that off_reg->off 14413 * == 0, since it's a scalar. 14414 * dst_reg gets the pointer type and since some positive 14415 * integer value was added to the pointer, give it a new 'id' 14416 * if it's a PTR_TO_PACKET. 14417 * this creates a new 'base' pointer, off_reg (variable) gets 14418 * added into the variable offset, and we copy the fixed offset 14419 * from ptr_reg. 14420 */ 14421 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) || 14422 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) { 14423 dst_reg->smin_value = S64_MIN; 14424 dst_reg->smax_value = S64_MAX; 14425 } 14426 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) || 14427 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) { 14428 dst_reg->umin_value = 0; 14429 dst_reg->umax_value = U64_MAX; 14430 } 14431 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 14432 dst_reg->off = ptr_reg->off; 14433 dst_reg->raw = ptr_reg->raw; 14434 if (reg_is_pkt_pointer(ptr_reg)) { 14435 dst_reg->id = ++env->id_gen; 14436 /* something was added to pkt_ptr, set range to zero */ 14437 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 14438 } 14439 break; 14440 case BPF_SUB: 14441 if (dst_reg == off_reg) { 14442 /* scalar -= pointer. Creates an unknown scalar */ 14443 verbose(env, "R%d tried to subtract pointer from scalar\n", 14444 dst); 14445 return -EACCES; 14446 } 14447 /* We don't allow subtraction from FP, because (according to 14448 * test_verifier.c test "invalid fp arithmetic", JITs might not 14449 * be able to deal with it. 14450 */ 14451 if (ptr_reg->type == PTR_TO_STACK) { 14452 verbose(env, "R%d subtraction from stack pointer prohibited\n", 14453 dst); 14454 return -EACCES; 14455 } 14456 if (known && (ptr_reg->off - smin_val == 14457 (s64)(s32)(ptr_reg->off - smin_val))) { 14458 /* pointer -= K. Subtract it from fixed offset */ 14459 dst_reg->smin_value = smin_ptr; 14460 dst_reg->smax_value = smax_ptr; 14461 dst_reg->umin_value = umin_ptr; 14462 dst_reg->umax_value = umax_ptr; 14463 dst_reg->var_off = ptr_reg->var_off; 14464 dst_reg->id = ptr_reg->id; 14465 dst_reg->off = ptr_reg->off - smin_val; 14466 dst_reg->raw = ptr_reg->raw; 14467 break; 14468 } 14469 /* A new variable offset is created. If the subtrahend is known 14470 * nonnegative, then any reg->range we had before is still good. 14471 */ 14472 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) || 14473 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) { 14474 /* Overflow possible, we know nothing */ 14475 dst_reg->smin_value = S64_MIN; 14476 dst_reg->smax_value = S64_MAX; 14477 } 14478 if (umin_ptr < umax_val) { 14479 /* Overflow possible, we know nothing */ 14480 dst_reg->umin_value = 0; 14481 dst_reg->umax_value = U64_MAX; 14482 } else { 14483 /* Cannot overflow (as long as bounds are consistent) */ 14484 dst_reg->umin_value = umin_ptr - umax_val; 14485 dst_reg->umax_value = umax_ptr - umin_val; 14486 } 14487 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 14488 dst_reg->off = ptr_reg->off; 14489 dst_reg->raw = ptr_reg->raw; 14490 if (reg_is_pkt_pointer(ptr_reg)) { 14491 dst_reg->id = ++env->id_gen; 14492 /* something was added to pkt_ptr, set range to zero */ 14493 if (smin_val < 0) 14494 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 14495 } 14496 break; 14497 case BPF_AND: 14498 case BPF_OR: 14499 case BPF_XOR: 14500 /* bitwise ops on pointers are troublesome, prohibit. */ 14501 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 14502 dst, bpf_alu_string[opcode >> 4]); 14503 return -EACCES; 14504 default: 14505 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 14506 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 14507 dst, bpf_alu_string[opcode >> 4]); 14508 return -EACCES; 14509 } 14510 14511 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 14512 return -EINVAL; 14513 reg_bounds_sync(dst_reg); 14514 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 14515 return -EACCES; 14516 if (sanitize_needed(opcode)) { 14517 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 14518 &info, true); 14519 if (ret < 0) 14520 return sanitize_err(env, insn, ret, off_reg, dst_reg); 14521 } 14522 14523 return 0; 14524 } 14525 14526 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 14527 struct bpf_reg_state *src_reg) 14528 { 14529 s32 *dst_smin = &dst_reg->s32_min_value; 14530 s32 *dst_smax = &dst_reg->s32_max_value; 14531 u32 *dst_umin = &dst_reg->u32_min_value; 14532 u32 *dst_umax = &dst_reg->u32_max_value; 14533 14534 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) || 14535 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) { 14536 *dst_smin = S32_MIN; 14537 *dst_smax = S32_MAX; 14538 } 14539 if (check_add_overflow(*dst_umin, src_reg->u32_min_value, dst_umin) || 14540 check_add_overflow(*dst_umax, src_reg->u32_max_value, dst_umax)) { 14541 *dst_umin = 0; 14542 *dst_umax = U32_MAX; 14543 } 14544 } 14545 14546 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 14547 struct bpf_reg_state *src_reg) 14548 { 14549 s64 *dst_smin = &dst_reg->smin_value; 14550 s64 *dst_smax = &dst_reg->smax_value; 14551 u64 *dst_umin = &dst_reg->umin_value; 14552 u64 *dst_umax = &dst_reg->umax_value; 14553 14554 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) || 14555 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) { 14556 *dst_smin = S64_MIN; 14557 *dst_smax = S64_MAX; 14558 } 14559 if (check_add_overflow(*dst_umin, src_reg->umin_value, dst_umin) || 14560 check_add_overflow(*dst_umax, src_reg->umax_value, dst_umax)) { 14561 *dst_umin = 0; 14562 *dst_umax = U64_MAX; 14563 } 14564 } 14565 14566 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 14567 struct bpf_reg_state *src_reg) 14568 { 14569 s32 *dst_smin = &dst_reg->s32_min_value; 14570 s32 *dst_smax = &dst_reg->s32_max_value; 14571 u32 umin_val = src_reg->u32_min_value; 14572 u32 umax_val = src_reg->u32_max_value; 14573 14574 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) || 14575 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) { 14576 /* Overflow possible, we know nothing */ 14577 *dst_smin = S32_MIN; 14578 *dst_smax = S32_MAX; 14579 } 14580 if (dst_reg->u32_min_value < umax_val) { 14581 /* Overflow possible, we know nothing */ 14582 dst_reg->u32_min_value = 0; 14583 dst_reg->u32_max_value = U32_MAX; 14584 } else { 14585 /* Cannot overflow (as long as bounds are consistent) */ 14586 dst_reg->u32_min_value -= umax_val; 14587 dst_reg->u32_max_value -= umin_val; 14588 } 14589 } 14590 14591 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 14592 struct bpf_reg_state *src_reg) 14593 { 14594 s64 *dst_smin = &dst_reg->smin_value; 14595 s64 *dst_smax = &dst_reg->smax_value; 14596 u64 umin_val = src_reg->umin_value; 14597 u64 umax_val = src_reg->umax_value; 14598 14599 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) || 14600 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) { 14601 /* Overflow possible, we know nothing */ 14602 *dst_smin = S64_MIN; 14603 *dst_smax = S64_MAX; 14604 } 14605 if (dst_reg->umin_value < umax_val) { 14606 /* Overflow possible, we know nothing */ 14607 dst_reg->umin_value = 0; 14608 dst_reg->umax_value = U64_MAX; 14609 } else { 14610 /* Cannot overflow (as long as bounds are consistent) */ 14611 dst_reg->umin_value -= umax_val; 14612 dst_reg->umax_value -= umin_val; 14613 } 14614 } 14615 14616 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 14617 struct bpf_reg_state *src_reg) 14618 { 14619 s32 *dst_smin = &dst_reg->s32_min_value; 14620 s32 *dst_smax = &dst_reg->s32_max_value; 14621 u32 *dst_umin = &dst_reg->u32_min_value; 14622 u32 *dst_umax = &dst_reg->u32_max_value; 14623 s32 tmp_prod[4]; 14624 14625 if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) || 14626 check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) { 14627 /* Overflow possible, we know nothing */ 14628 *dst_umin = 0; 14629 *dst_umax = U32_MAX; 14630 } 14631 if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) || 14632 check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) || 14633 check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) || 14634 check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) { 14635 /* Overflow possible, we know nothing */ 14636 *dst_smin = S32_MIN; 14637 *dst_smax = S32_MAX; 14638 } else { 14639 *dst_smin = min_array(tmp_prod, 4); 14640 *dst_smax = max_array(tmp_prod, 4); 14641 } 14642 } 14643 14644 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 14645 struct bpf_reg_state *src_reg) 14646 { 14647 s64 *dst_smin = &dst_reg->smin_value; 14648 s64 *dst_smax = &dst_reg->smax_value; 14649 u64 *dst_umin = &dst_reg->umin_value; 14650 u64 *dst_umax = &dst_reg->umax_value; 14651 s64 tmp_prod[4]; 14652 14653 if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) || 14654 check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) { 14655 /* Overflow possible, we know nothing */ 14656 *dst_umin = 0; 14657 *dst_umax = U64_MAX; 14658 } 14659 if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) || 14660 check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) || 14661 check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) || 14662 check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) { 14663 /* Overflow possible, we know nothing */ 14664 *dst_smin = S64_MIN; 14665 *dst_smax = S64_MAX; 14666 } else { 14667 *dst_smin = min_array(tmp_prod, 4); 14668 *dst_smax = max_array(tmp_prod, 4); 14669 } 14670 } 14671 14672 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14673 struct bpf_reg_state *src_reg) 14674 { 14675 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14676 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14677 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14678 u32 umax_val = src_reg->u32_max_value; 14679 14680 if (src_known && dst_known) { 14681 __mark_reg32_known(dst_reg, var32_off.value); 14682 return; 14683 } 14684 14685 /* We get our minimum from the var_off, since that's inherently 14686 * bitwise. Our maximum is the minimum of the operands' maxima. 14687 */ 14688 dst_reg->u32_min_value = var32_off.value; 14689 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 14690 14691 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14692 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14693 */ 14694 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14695 dst_reg->s32_min_value = dst_reg->u32_min_value; 14696 dst_reg->s32_max_value = dst_reg->u32_max_value; 14697 } else { 14698 dst_reg->s32_min_value = S32_MIN; 14699 dst_reg->s32_max_value = S32_MAX; 14700 } 14701 } 14702 14703 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14704 struct bpf_reg_state *src_reg) 14705 { 14706 bool src_known = tnum_is_const(src_reg->var_off); 14707 bool dst_known = tnum_is_const(dst_reg->var_off); 14708 u64 umax_val = src_reg->umax_value; 14709 14710 if (src_known && dst_known) { 14711 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14712 return; 14713 } 14714 14715 /* We get our minimum from the var_off, since that's inherently 14716 * bitwise. Our maximum is the minimum of the operands' maxima. 14717 */ 14718 dst_reg->umin_value = dst_reg->var_off.value; 14719 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 14720 14721 /* Safe to set s64 bounds by casting u64 result into s64 when u64 14722 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 14723 */ 14724 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 14725 dst_reg->smin_value = dst_reg->umin_value; 14726 dst_reg->smax_value = dst_reg->umax_value; 14727 } else { 14728 dst_reg->smin_value = S64_MIN; 14729 dst_reg->smax_value = S64_MAX; 14730 } 14731 /* We may learn something more from the var_off */ 14732 __update_reg_bounds(dst_reg); 14733 } 14734 14735 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14736 struct bpf_reg_state *src_reg) 14737 { 14738 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14739 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14740 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14741 u32 umin_val = src_reg->u32_min_value; 14742 14743 if (src_known && dst_known) { 14744 __mark_reg32_known(dst_reg, var32_off.value); 14745 return; 14746 } 14747 14748 /* We get our maximum from the var_off, and our minimum is the 14749 * maximum of the operands' minima 14750 */ 14751 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 14752 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 14753 14754 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14755 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14756 */ 14757 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14758 dst_reg->s32_min_value = dst_reg->u32_min_value; 14759 dst_reg->s32_max_value = dst_reg->u32_max_value; 14760 } else { 14761 dst_reg->s32_min_value = S32_MIN; 14762 dst_reg->s32_max_value = S32_MAX; 14763 } 14764 } 14765 14766 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14767 struct bpf_reg_state *src_reg) 14768 { 14769 bool src_known = tnum_is_const(src_reg->var_off); 14770 bool dst_known = tnum_is_const(dst_reg->var_off); 14771 u64 umin_val = src_reg->umin_value; 14772 14773 if (src_known && dst_known) { 14774 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14775 return; 14776 } 14777 14778 /* We get our maximum from the var_off, and our minimum is the 14779 * maximum of the operands' minima 14780 */ 14781 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 14782 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 14783 14784 /* Safe to set s64 bounds by casting u64 result into s64 when u64 14785 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 14786 */ 14787 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 14788 dst_reg->smin_value = dst_reg->umin_value; 14789 dst_reg->smax_value = dst_reg->umax_value; 14790 } else { 14791 dst_reg->smin_value = S64_MIN; 14792 dst_reg->smax_value = S64_MAX; 14793 } 14794 /* We may learn something more from the var_off */ 14795 __update_reg_bounds(dst_reg); 14796 } 14797 14798 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 14799 struct bpf_reg_state *src_reg) 14800 { 14801 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14802 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14803 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14804 14805 if (src_known && dst_known) { 14806 __mark_reg32_known(dst_reg, var32_off.value); 14807 return; 14808 } 14809 14810 /* We get both minimum and maximum from the var32_off. */ 14811 dst_reg->u32_min_value = var32_off.value; 14812 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 14813 14814 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14815 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14816 */ 14817 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14818 dst_reg->s32_min_value = dst_reg->u32_min_value; 14819 dst_reg->s32_max_value = dst_reg->u32_max_value; 14820 } else { 14821 dst_reg->s32_min_value = S32_MIN; 14822 dst_reg->s32_max_value = S32_MAX; 14823 } 14824 } 14825 14826 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 14827 struct bpf_reg_state *src_reg) 14828 { 14829 bool src_known = tnum_is_const(src_reg->var_off); 14830 bool dst_known = tnum_is_const(dst_reg->var_off); 14831 14832 if (src_known && dst_known) { 14833 /* dst_reg->var_off.value has been updated earlier */ 14834 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14835 return; 14836 } 14837 14838 /* We get both minimum and maximum from the var_off. */ 14839 dst_reg->umin_value = dst_reg->var_off.value; 14840 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 14841 14842 /* Safe to set s64 bounds by casting u64 result into s64 when u64 14843 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 14844 */ 14845 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 14846 dst_reg->smin_value = dst_reg->umin_value; 14847 dst_reg->smax_value = dst_reg->umax_value; 14848 } else { 14849 dst_reg->smin_value = S64_MIN; 14850 dst_reg->smax_value = S64_MAX; 14851 } 14852 14853 __update_reg_bounds(dst_reg); 14854 } 14855 14856 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14857 u64 umin_val, u64 umax_val) 14858 { 14859 /* We lose all sign bit information (except what we can pick 14860 * up from var_off) 14861 */ 14862 dst_reg->s32_min_value = S32_MIN; 14863 dst_reg->s32_max_value = S32_MAX; 14864 /* If we might shift our top bit out, then we know nothing */ 14865 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 14866 dst_reg->u32_min_value = 0; 14867 dst_reg->u32_max_value = U32_MAX; 14868 } else { 14869 dst_reg->u32_min_value <<= umin_val; 14870 dst_reg->u32_max_value <<= umax_val; 14871 } 14872 } 14873 14874 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14875 struct bpf_reg_state *src_reg) 14876 { 14877 u32 umax_val = src_reg->u32_max_value; 14878 u32 umin_val = src_reg->u32_min_value; 14879 /* u32 alu operation will zext upper bits */ 14880 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14881 14882 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14883 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 14884 /* Not required but being careful mark reg64 bounds as unknown so 14885 * that we are forced to pick them up from tnum and zext later and 14886 * if some path skips this step we are still safe. 14887 */ 14888 __mark_reg64_unbounded(dst_reg); 14889 __update_reg32_bounds(dst_reg); 14890 } 14891 14892 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 14893 u64 umin_val, u64 umax_val) 14894 { 14895 /* Special case <<32 because it is a common compiler pattern to sign 14896 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 14897 * positive we know this shift will also be positive so we can track 14898 * bounds correctly. Otherwise we lose all sign bit information except 14899 * what we can pick up from var_off. Perhaps we can generalize this 14900 * later to shifts of any length. 14901 */ 14902 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 14903 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 14904 else 14905 dst_reg->smax_value = S64_MAX; 14906 14907 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 14908 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 14909 else 14910 dst_reg->smin_value = S64_MIN; 14911 14912 /* If we might shift our top bit out, then we know nothing */ 14913 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 14914 dst_reg->umin_value = 0; 14915 dst_reg->umax_value = U64_MAX; 14916 } else { 14917 dst_reg->umin_value <<= umin_val; 14918 dst_reg->umax_value <<= umax_val; 14919 } 14920 } 14921 14922 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 14923 struct bpf_reg_state *src_reg) 14924 { 14925 u64 umax_val = src_reg->umax_value; 14926 u64 umin_val = src_reg->umin_value; 14927 14928 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 14929 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 14930 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14931 14932 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 14933 /* We may learn something more from the var_off */ 14934 __update_reg_bounds(dst_reg); 14935 } 14936 14937 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 14938 struct bpf_reg_state *src_reg) 14939 { 14940 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14941 u32 umax_val = src_reg->u32_max_value; 14942 u32 umin_val = src_reg->u32_min_value; 14943 14944 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14945 * be negative, then either: 14946 * 1) src_reg might be zero, so the sign bit of the result is 14947 * unknown, so we lose our signed bounds 14948 * 2) it's known negative, thus the unsigned bounds capture the 14949 * signed bounds 14950 * 3) the signed bounds cross zero, so they tell us nothing 14951 * about the result 14952 * If the value in dst_reg is known nonnegative, then again the 14953 * unsigned bounds capture the signed bounds. 14954 * Thus, in all cases it suffices to blow away our signed bounds 14955 * and rely on inferring new ones from the unsigned bounds and 14956 * var_off of the result. 14957 */ 14958 dst_reg->s32_min_value = S32_MIN; 14959 dst_reg->s32_max_value = S32_MAX; 14960 14961 dst_reg->var_off = tnum_rshift(subreg, umin_val); 14962 dst_reg->u32_min_value >>= umax_val; 14963 dst_reg->u32_max_value >>= umin_val; 14964 14965 __mark_reg64_unbounded(dst_reg); 14966 __update_reg32_bounds(dst_reg); 14967 } 14968 14969 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 14970 struct bpf_reg_state *src_reg) 14971 { 14972 u64 umax_val = src_reg->umax_value; 14973 u64 umin_val = src_reg->umin_value; 14974 14975 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14976 * be negative, then either: 14977 * 1) src_reg might be zero, so the sign bit of the result is 14978 * unknown, so we lose our signed bounds 14979 * 2) it's known negative, thus the unsigned bounds capture the 14980 * signed bounds 14981 * 3) the signed bounds cross zero, so they tell us nothing 14982 * about the result 14983 * If the value in dst_reg is known nonnegative, then again the 14984 * unsigned bounds capture the signed bounds. 14985 * Thus, in all cases it suffices to blow away our signed bounds 14986 * and rely on inferring new ones from the unsigned bounds and 14987 * var_off of the result. 14988 */ 14989 dst_reg->smin_value = S64_MIN; 14990 dst_reg->smax_value = S64_MAX; 14991 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 14992 dst_reg->umin_value >>= umax_val; 14993 dst_reg->umax_value >>= umin_val; 14994 14995 /* Its not easy to operate on alu32 bounds here because it depends 14996 * on bits being shifted in. Take easy way out and mark unbounded 14997 * so we can recalculate later from tnum. 14998 */ 14999 __mark_reg32_unbounded(dst_reg); 15000 __update_reg_bounds(dst_reg); 15001 } 15002 15003 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 15004 struct bpf_reg_state *src_reg) 15005 { 15006 u64 umin_val = src_reg->u32_min_value; 15007 15008 /* Upon reaching here, src_known is true and 15009 * umax_val is equal to umin_val. 15010 */ 15011 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 15012 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 15013 15014 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 15015 15016 /* blow away the dst_reg umin_value/umax_value and rely on 15017 * dst_reg var_off to refine the result. 15018 */ 15019 dst_reg->u32_min_value = 0; 15020 dst_reg->u32_max_value = U32_MAX; 15021 15022 __mark_reg64_unbounded(dst_reg); 15023 __update_reg32_bounds(dst_reg); 15024 } 15025 15026 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 15027 struct bpf_reg_state *src_reg) 15028 { 15029 u64 umin_val = src_reg->umin_value; 15030 15031 /* Upon reaching here, src_known is true and umax_val is equal 15032 * to umin_val. 15033 */ 15034 dst_reg->smin_value >>= umin_val; 15035 dst_reg->smax_value >>= umin_val; 15036 15037 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 15038 15039 /* blow away the dst_reg umin_value/umax_value and rely on 15040 * dst_reg var_off to refine the result. 15041 */ 15042 dst_reg->umin_value = 0; 15043 dst_reg->umax_value = U64_MAX; 15044 15045 /* Its not easy to operate on alu32 bounds here because it depends 15046 * on bits being shifted in from upper 32-bits. Take easy way out 15047 * and mark unbounded so we can recalculate later from tnum. 15048 */ 15049 __mark_reg32_unbounded(dst_reg); 15050 __update_reg_bounds(dst_reg); 15051 } 15052 15053 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 15054 const struct bpf_reg_state *src_reg) 15055 { 15056 bool src_is_const = false; 15057 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 15058 15059 if (insn_bitness == 32) { 15060 if (tnum_subreg_is_const(src_reg->var_off) 15061 && src_reg->s32_min_value == src_reg->s32_max_value 15062 && src_reg->u32_min_value == src_reg->u32_max_value) 15063 src_is_const = true; 15064 } else { 15065 if (tnum_is_const(src_reg->var_off) 15066 && src_reg->smin_value == src_reg->smax_value 15067 && src_reg->umin_value == src_reg->umax_value) 15068 src_is_const = true; 15069 } 15070 15071 switch (BPF_OP(insn->code)) { 15072 case BPF_ADD: 15073 case BPF_SUB: 15074 case BPF_AND: 15075 case BPF_XOR: 15076 case BPF_OR: 15077 case BPF_MUL: 15078 return true; 15079 15080 /* Shift operators range is only computable if shift dimension operand 15081 * is a constant. Shifts greater than 31 or 63 are undefined. This 15082 * includes shifts by a negative number. 15083 */ 15084 case BPF_LSH: 15085 case BPF_RSH: 15086 case BPF_ARSH: 15087 return (src_is_const && src_reg->umax_value < insn_bitness); 15088 default: 15089 return false; 15090 } 15091 } 15092 15093 /* WARNING: This function does calculations on 64-bit values, but the actual 15094 * execution may occur on 32-bit values. Therefore, things like bitshifts 15095 * need extra checks in the 32-bit case. 15096 */ 15097 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 15098 struct bpf_insn *insn, 15099 struct bpf_reg_state *dst_reg, 15100 struct bpf_reg_state src_reg) 15101 { 15102 u8 opcode = BPF_OP(insn->code); 15103 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 15104 int ret; 15105 15106 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 15107 __mark_reg_unknown(env, dst_reg); 15108 return 0; 15109 } 15110 15111 if (sanitize_needed(opcode)) { 15112 ret = sanitize_val_alu(env, insn); 15113 if (ret < 0) 15114 return sanitize_err(env, insn, ret, NULL, NULL); 15115 } 15116 15117 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 15118 * There are two classes of instructions: The first class we track both 15119 * alu32 and alu64 sign/unsigned bounds independently this provides the 15120 * greatest amount of precision when alu operations are mixed with jmp32 15121 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 15122 * and BPF_OR. This is possible because these ops have fairly easy to 15123 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 15124 * See alu32 verifier tests for examples. The second class of 15125 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 15126 * with regards to tracking sign/unsigned bounds because the bits may 15127 * cross subreg boundaries in the alu64 case. When this happens we mark 15128 * the reg unbounded in the subreg bound space and use the resulting 15129 * tnum to calculate an approximation of the sign/unsigned bounds. 15130 */ 15131 switch (opcode) { 15132 case BPF_ADD: 15133 scalar32_min_max_add(dst_reg, &src_reg); 15134 scalar_min_max_add(dst_reg, &src_reg); 15135 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 15136 break; 15137 case BPF_SUB: 15138 scalar32_min_max_sub(dst_reg, &src_reg); 15139 scalar_min_max_sub(dst_reg, &src_reg); 15140 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 15141 break; 15142 case BPF_MUL: 15143 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 15144 scalar32_min_max_mul(dst_reg, &src_reg); 15145 scalar_min_max_mul(dst_reg, &src_reg); 15146 break; 15147 case BPF_AND: 15148 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 15149 scalar32_min_max_and(dst_reg, &src_reg); 15150 scalar_min_max_and(dst_reg, &src_reg); 15151 break; 15152 case BPF_OR: 15153 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 15154 scalar32_min_max_or(dst_reg, &src_reg); 15155 scalar_min_max_or(dst_reg, &src_reg); 15156 break; 15157 case BPF_XOR: 15158 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 15159 scalar32_min_max_xor(dst_reg, &src_reg); 15160 scalar_min_max_xor(dst_reg, &src_reg); 15161 break; 15162 case BPF_LSH: 15163 if (alu32) 15164 scalar32_min_max_lsh(dst_reg, &src_reg); 15165 else 15166 scalar_min_max_lsh(dst_reg, &src_reg); 15167 break; 15168 case BPF_RSH: 15169 if (alu32) 15170 scalar32_min_max_rsh(dst_reg, &src_reg); 15171 else 15172 scalar_min_max_rsh(dst_reg, &src_reg); 15173 break; 15174 case BPF_ARSH: 15175 if (alu32) 15176 scalar32_min_max_arsh(dst_reg, &src_reg); 15177 else 15178 scalar_min_max_arsh(dst_reg, &src_reg); 15179 break; 15180 default: 15181 break; 15182 } 15183 15184 /* ALU32 ops are zero extended into 64bit register */ 15185 if (alu32) 15186 zext_32_to_64(dst_reg); 15187 reg_bounds_sync(dst_reg); 15188 return 0; 15189 } 15190 15191 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 15192 * and var_off. 15193 */ 15194 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 15195 struct bpf_insn *insn) 15196 { 15197 struct bpf_verifier_state *vstate = env->cur_state; 15198 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15199 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 15200 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 15201 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 15202 u8 opcode = BPF_OP(insn->code); 15203 int err; 15204 15205 dst_reg = ®s[insn->dst_reg]; 15206 src_reg = NULL; 15207 15208 if (dst_reg->type == PTR_TO_ARENA) { 15209 struct bpf_insn_aux_data *aux = cur_aux(env); 15210 15211 if (BPF_CLASS(insn->code) == BPF_ALU64) 15212 /* 15213 * 32-bit operations zero upper bits automatically. 15214 * 64-bit operations need to be converted to 32. 15215 */ 15216 aux->needs_zext = true; 15217 15218 /* Any arithmetic operations are allowed on arena pointers */ 15219 return 0; 15220 } 15221 15222 if (dst_reg->type != SCALAR_VALUE) 15223 ptr_reg = dst_reg; 15224 15225 if (BPF_SRC(insn->code) == BPF_X) { 15226 src_reg = ®s[insn->src_reg]; 15227 if (src_reg->type != SCALAR_VALUE) { 15228 if (dst_reg->type != SCALAR_VALUE) { 15229 /* Combining two pointers by any ALU op yields 15230 * an arbitrary scalar. Disallow all math except 15231 * pointer subtraction 15232 */ 15233 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 15234 mark_reg_unknown(env, regs, insn->dst_reg); 15235 return 0; 15236 } 15237 verbose(env, "R%d pointer %s pointer prohibited\n", 15238 insn->dst_reg, 15239 bpf_alu_string[opcode >> 4]); 15240 return -EACCES; 15241 } else { 15242 /* scalar += pointer 15243 * This is legal, but we have to reverse our 15244 * src/dest handling in computing the range 15245 */ 15246 err = mark_chain_precision(env, insn->dst_reg); 15247 if (err) 15248 return err; 15249 return adjust_ptr_min_max_vals(env, insn, 15250 src_reg, dst_reg); 15251 } 15252 } else if (ptr_reg) { 15253 /* pointer += scalar */ 15254 err = mark_chain_precision(env, insn->src_reg); 15255 if (err) 15256 return err; 15257 return adjust_ptr_min_max_vals(env, insn, 15258 dst_reg, src_reg); 15259 } else if (dst_reg->precise) { 15260 /* if dst_reg is precise, src_reg should be precise as well */ 15261 err = mark_chain_precision(env, insn->src_reg); 15262 if (err) 15263 return err; 15264 } 15265 } else { 15266 /* Pretend the src is a reg with a known value, since we only 15267 * need to be able to read from this state. 15268 */ 15269 off_reg.type = SCALAR_VALUE; 15270 __mark_reg_known(&off_reg, insn->imm); 15271 src_reg = &off_reg; 15272 if (ptr_reg) /* pointer += K */ 15273 return adjust_ptr_min_max_vals(env, insn, 15274 ptr_reg, src_reg); 15275 } 15276 15277 /* Got here implies adding two SCALAR_VALUEs */ 15278 if (WARN_ON_ONCE(ptr_reg)) { 15279 print_verifier_state(env, vstate, vstate->curframe, true); 15280 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 15281 return -EINVAL; 15282 } 15283 if (WARN_ON(!src_reg)) { 15284 print_verifier_state(env, vstate, vstate->curframe, true); 15285 verbose(env, "verifier internal error: no src_reg\n"); 15286 return -EINVAL; 15287 } 15288 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 15289 if (err) 15290 return err; 15291 /* 15292 * Compilers can generate the code 15293 * r1 = r2 15294 * r1 += 0x1 15295 * if r2 < 1000 goto ... 15296 * use r1 in memory access 15297 * So for 64-bit alu remember constant delta between r2 and r1 and 15298 * update r1 after 'if' condition. 15299 */ 15300 if (env->bpf_capable && 15301 BPF_OP(insn->code) == BPF_ADD && !alu32 && 15302 dst_reg->id && is_reg_const(src_reg, false)) { 15303 u64 val = reg_const_value(src_reg, false); 15304 15305 if ((dst_reg->id & BPF_ADD_CONST) || 15306 /* prevent overflow in sync_linked_regs() later */ 15307 val > (u32)S32_MAX) { 15308 /* 15309 * If the register already went through rX += val 15310 * we cannot accumulate another val into rx->off. 15311 */ 15312 dst_reg->off = 0; 15313 dst_reg->id = 0; 15314 } else { 15315 dst_reg->id |= BPF_ADD_CONST; 15316 dst_reg->off = val; 15317 } 15318 } else { 15319 /* 15320 * Make sure ID is cleared otherwise dst_reg min/max could be 15321 * incorrectly propagated into other registers by sync_linked_regs() 15322 */ 15323 dst_reg->id = 0; 15324 } 15325 return 0; 15326 } 15327 15328 /* check validity of 32-bit and 64-bit arithmetic operations */ 15329 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 15330 { 15331 struct bpf_reg_state *regs = cur_regs(env); 15332 u8 opcode = BPF_OP(insn->code); 15333 int err; 15334 15335 if (opcode == BPF_END || opcode == BPF_NEG) { 15336 if (opcode == BPF_NEG) { 15337 if (BPF_SRC(insn->code) != BPF_K || 15338 insn->src_reg != BPF_REG_0 || 15339 insn->off != 0 || insn->imm != 0) { 15340 verbose(env, "BPF_NEG uses reserved fields\n"); 15341 return -EINVAL; 15342 } 15343 } else { 15344 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 15345 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 15346 (BPF_CLASS(insn->code) == BPF_ALU64 && 15347 BPF_SRC(insn->code) != BPF_TO_LE)) { 15348 verbose(env, "BPF_END uses reserved fields\n"); 15349 return -EINVAL; 15350 } 15351 } 15352 15353 /* check src operand */ 15354 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15355 if (err) 15356 return err; 15357 15358 if (is_pointer_value(env, insn->dst_reg)) { 15359 verbose(env, "R%d pointer arithmetic prohibited\n", 15360 insn->dst_reg); 15361 return -EACCES; 15362 } 15363 15364 /* check dest operand */ 15365 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15366 if (err) 15367 return err; 15368 15369 } else if (opcode == BPF_MOV) { 15370 15371 if (BPF_SRC(insn->code) == BPF_X) { 15372 if (BPF_CLASS(insn->code) == BPF_ALU) { 15373 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 15374 insn->imm) { 15375 verbose(env, "BPF_MOV uses reserved fields\n"); 15376 return -EINVAL; 15377 } 15378 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 15379 if (insn->imm != 1 && insn->imm != 1u << 16) { 15380 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 15381 return -EINVAL; 15382 } 15383 if (!env->prog->aux->arena) { 15384 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 15385 return -EINVAL; 15386 } 15387 } else { 15388 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 15389 insn->off != 32) || insn->imm) { 15390 verbose(env, "BPF_MOV uses reserved fields\n"); 15391 return -EINVAL; 15392 } 15393 } 15394 15395 /* check src operand */ 15396 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15397 if (err) 15398 return err; 15399 } else { 15400 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 15401 verbose(env, "BPF_MOV uses reserved fields\n"); 15402 return -EINVAL; 15403 } 15404 } 15405 15406 /* check dest operand, mark as required later */ 15407 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15408 if (err) 15409 return err; 15410 15411 if (BPF_SRC(insn->code) == BPF_X) { 15412 struct bpf_reg_state *src_reg = regs + insn->src_reg; 15413 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 15414 15415 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15416 if (insn->imm) { 15417 /* off == BPF_ADDR_SPACE_CAST */ 15418 mark_reg_unknown(env, regs, insn->dst_reg); 15419 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 15420 dst_reg->type = PTR_TO_ARENA; 15421 /* PTR_TO_ARENA is 32-bit */ 15422 dst_reg->subreg_def = env->insn_idx + 1; 15423 } 15424 } else if (insn->off == 0) { 15425 /* case: R1 = R2 15426 * copy register state to dest reg 15427 */ 15428 assign_scalar_id_before_mov(env, src_reg); 15429 copy_register_state(dst_reg, src_reg); 15430 dst_reg->live |= REG_LIVE_WRITTEN; 15431 dst_reg->subreg_def = DEF_NOT_SUBREG; 15432 } else { 15433 /* case: R1 = (s8, s16 s32)R2 */ 15434 if (is_pointer_value(env, insn->src_reg)) { 15435 verbose(env, 15436 "R%d sign-extension part of pointer\n", 15437 insn->src_reg); 15438 return -EACCES; 15439 } else if (src_reg->type == SCALAR_VALUE) { 15440 bool no_sext; 15441 15442 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 15443 if (no_sext) 15444 assign_scalar_id_before_mov(env, src_reg); 15445 copy_register_state(dst_reg, src_reg); 15446 if (!no_sext) 15447 dst_reg->id = 0; 15448 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 15449 dst_reg->live |= REG_LIVE_WRITTEN; 15450 dst_reg->subreg_def = DEF_NOT_SUBREG; 15451 } else { 15452 mark_reg_unknown(env, regs, insn->dst_reg); 15453 } 15454 } 15455 } else { 15456 /* R1 = (u32) R2 */ 15457 if (is_pointer_value(env, insn->src_reg)) { 15458 verbose(env, 15459 "R%d partial copy of pointer\n", 15460 insn->src_reg); 15461 return -EACCES; 15462 } else if (src_reg->type == SCALAR_VALUE) { 15463 if (insn->off == 0) { 15464 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 15465 15466 if (is_src_reg_u32) 15467 assign_scalar_id_before_mov(env, src_reg); 15468 copy_register_state(dst_reg, src_reg); 15469 /* Make sure ID is cleared if src_reg is not in u32 15470 * range otherwise dst_reg min/max could be incorrectly 15471 * propagated into src_reg by sync_linked_regs() 15472 */ 15473 if (!is_src_reg_u32) 15474 dst_reg->id = 0; 15475 dst_reg->live |= REG_LIVE_WRITTEN; 15476 dst_reg->subreg_def = env->insn_idx + 1; 15477 } else { 15478 /* case: W1 = (s8, s16)W2 */ 15479 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 15480 15481 if (no_sext) 15482 assign_scalar_id_before_mov(env, src_reg); 15483 copy_register_state(dst_reg, src_reg); 15484 if (!no_sext) 15485 dst_reg->id = 0; 15486 dst_reg->live |= REG_LIVE_WRITTEN; 15487 dst_reg->subreg_def = env->insn_idx + 1; 15488 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 15489 } 15490 } else { 15491 mark_reg_unknown(env, regs, 15492 insn->dst_reg); 15493 } 15494 zext_32_to_64(dst_reg); 15495 reg_bounds_sync(dst_reg); 15496 } 15497 } else { 15498 /* case: R = imm 15499 * remember the value we stored into this reg 15500 */ 15501 /* clear any state __mark_reg_known doesn't set */ 15502 mark_reg_unknown(env, regs, insn->dst_reg); 15503 regs[insn->dst_reg].type = SCALAR_VALUE; 15504 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15505 __mark_reg_known(regs + insn->dst_reg, 15506 insn->imm); 15507 } else { 15508 __mark_reg_known(regs + insn->dst_reg, 15509 (u32)insn->imm); 15510 } 15511 } 15512 15513 } else if (opcode > BPF_END) { 15514 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 15515 return -EINVAL; 15516 15517 } else { /* all other ALU ops: and, sub, xor, add, ... */ 15518 15519 if (BPF_SRC(insn->code) == BPF_X) { 15520 if (insn->imm != 0 || insn->off > 1 || 15521 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 15522 verbose(env, "BPF_ALU uses reserved fields\n"); 15523 return -EINVAL; 15524 } 15525 /* check src1 operand */ 15526 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15527 if (err) 15528 return err; 15529 } else { 15530 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 15531 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 15532 verbose(env, "BPF_ALU uses reserved fields\n"); 15533 return -EINVAL; 15534 } 15535 } 15536 15537 /* check src2 operand */ 15538 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15539 if (err) 15540 return err; 15541 15542 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 15543 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 15544 verbose(env, "div by zero\n"); 15545 return -EINVAL; 15546 } 15547 15548 if ((opcode == BPF_LSH || opcode == BPF_RSH || 15549 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 15550 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 15551 15552 if (insn->imm < 0 || insn->imm >= size) { 15553 verbose(env, "invalid shift %d\n", insn->imm); 15554 return -EINVAL; 15555 } 15556 } 15557 15558 /* check dest operand */ 15559 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15560 err = err ?: adjust_reg_min_max_vals(env, insn); 15561 if (err) 15562 return err; 15563 } 15564 15565 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 15566 } 15567 15568 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 15569 struct bpf_reg_state *dst_reg, 15570 enum bpf_reg_type type, 15571 bool range_right_open) 15572 { 15573 struct bpf_func_state *state; 15574 struct bpf_reg_state *reg; 15575 int new_range; 15576 15577 if (dst_reg->off < 0 || 15578 (dst_reg->off == 0 && range_right_open)) 15579 /* This doesn't give us any range */ 15580 return; 15581 15582 if (dst_reg->umax_value > MAX_PACKET_OFF || 15583 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 15584 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15585 * than pkt_end, but that's because it's also less than pkt. 15586 */ 15587 return; 15588 15589 new_range = dst_reg->off; 15590 if (range_right_open) 15591 new_range++; 15592 15593 /* Examples for register markings: 15594 * 15595 * pkt_data in dst register: 15596 * 15597 * r2 = r3; 15598 * r2 += 8; 15599 * if (r2 > pkt_end) goto <handle exception> 15600 * <access okay> 15601 * 15602 * r2 = r3; 15603 * r2 += 8; 15604 * if (r2 < pkt_end) goto <access okay> 15605 * <handle exception> 15606 * 15607 * Where: 15608 * r2 == dst_reg, pkt_end == src_reg 15609 * r2=pkt(id=n,off=8,r=0) 15610 * r3=pkt(id=n,off=0,r=0) 15611 * 15612 * pkt_data in src register: 15613 * 15614 * r2 = r3; 15615 * r2 += 8; 15616 * if (pkt_end >= r2) goto <access okay> 15617 * <handle exception> 15618 * 15619 * r2 = r3; 15620 * r2 += 8; 15621 * if (pkt_end <= r2) goto <handle exception> 15622 * <access okay> 15623 * 15624 * Where: 15625 * pkt_end == dst_reg, r2 == src_reg 15626 * r2=pkt(id=n,off=8,r=0) 15627 * r3=pkt(id=n,off=0,r=0) 15628 * 15629 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15630 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15631 * and [r3, r3 + 8-1) respectively is safe to access depending on 15632 * the check. 15633 */ 15634 15635 /* If our ids match, then we must have the same max_value. And we 15636 * don't care about the other reg's fixed offset, since if it's too big 15637 * the range won't allow anything. 15638 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 15639 */ 15640 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15641 if (reg->type == type && reg->id == dst_reg->id) 15642 /* keep the maximum range already checked */ 15643 reg->range = max(reg->range, new_range); 15644 })); 15645 } 15646 15647 /* 15648 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15649 */ 15650 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15651 u8 opcode, bool is_jmp32) 15652 { 15653 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15654 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15655 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 15656 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 15657 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 15658 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 15659 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 15660 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 15661 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 15662 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 15663 15664 switch (opcode) { 15665 case BPF_JEQ: 15666 /* constants, umin/umax and smin/smax checks would be 15667 * redundant in this case because they all should match 15668 */ 15669 if (tnum_is_const(t1) && tnum_is_const(t2)) 15670 return t1.value == t2.value; 15671 /* non-overlapping ranges */ 15672 if (umin1 > umax2 || umax1 < umin2) 15673 return 0; 15674 if (smin1 > smax2 || smax1 < smin2) 15675 return 0; 15676 if (!is_jmp32) { 15677 /* if 64-bit ranges are inconclusive, see if we can 15678 * utilize 32-bit subrange knowledge to eliminate 15679 * branches that can't be taken a priori 15680 */ 15681 if (reg1->u32_min_value > reg2->u32_max_value || 15682 reg1->u32_max_value < reg2->u32_min_value) 15683 return 0; 15684 if (reg1->s32_min_value > reg2->s32_max_value || 15685 reg1->s32_max_value < reg2->s32_min_value) 15686 return 0; 15687 } 15688 break; 15689 case BPF_JNE: 15690 /* constants, umin/umax and smin/smax checks would be 15691 * redundant in this case because they all should match 15692 */ 15693 if (tnum_is_const(t1) && tnum_is_const(t2)) 15694 return t1.value != t2.value; 15695 /* non-overlapping ranges */ 15696 if (umin1 > umax2 || umax1 < umin2) 15697 return 1; 15698 if (smin1 > smax2 || smax1 < smin2) 15699 return 1; 15700 if (!is_jmp32) { 15701 /* if 64-bit ranges are inconclusive, see if we can 15702 * utilize 32-bit subrange knowledge to eliminate 15703 * branches that can't be taken a priori 15704 */ 15705 if (reg1->u32_min_value > reg2->u32_max_value || 15706 reg1->u32_max_value < reg2->u32_min_value) 15707 return 1; 15708 if (reg1->s32_min_value > reg2->s32_max_value || 15709 reg1->s32_max_value < reg2->s32_min_value) 15710 return 1; 15711 } 15712 break; 15713 case BPF_JSET: 15714 if (!is_reg_const(reg2, is_jmp32)) { 15715 swap(reg1, reg2); 15716 swap(t1, t2); 15717 } 15718 if (!is_reg_const(reg2, is_jmp32)) 15719 return -1; 15720 if ((~t1.mask & t1.value) & t2.value) 15721 return 1; 15722 if (!((t1.mask | t1.value) & t2.value)) 15723 return 0; 15724 break; 15725 case BPF_JGT: 15726 if (umin1 > umax2) 15727 return 1; 15728 else if (umax1 <= umin2) 15729 return 0; 15730 break; 15731 case BPF_JSGT: 15732 if (smin1 > smax2) 15733 return 1; 15734 else if (smax1 <= smin2) 15735 return 0; 15736 break; 15737 case BPF_JLT: 15738 if (umax1 < umin2) 15739 return 1; 15740 else if (umin1 >= umax2) 15741 return 0; 15742 break; 15743 case BPF_JSLT: 15744 if (smax1 < smin2) 15745 return 1; 15746 else if (smin1 >= smax2) 15747 return 0; 15748 break; 15749 case BPF_JGE: 15750 if (umin1 >= umax2) 15751 return 1; 15752 else if (umax1 < umin2) 15753 return 0; 15754 break; 15755 case BPF_JSGE: 15756 if (smin1 >= smax2) 15757 return 1; 15758 else if (smax1 < smin2) 15759 return 0; 15760 break; 15761 case BPF_JLE: 15762 if (umax1 <= umin2) 15763 return 1; 15764 else if (umin1 > umax2) 15765 return 0; 15766 break; 15767 case BPF_JSLE: 15768 if (smax1 <= smin2) 15769 return 1; 15770 else if (smin1 > smax2) 15771 return 0; 15772 break; 15773 } 15774 15775 return -1; 15776 } 15777 15778 static int flip_opcode(u32 opcode) 15779 { 15780 /* How can we transform "a <op> b" into "b <op> a"? */ 15781 static const u8 opcode_flip[16] = { 15782 /* these stay the same */ 15783 [BPF_JEQ >> 4] = BPF_JEQ, 15784 [BPF_JNE >> 4] = BPF_JNE, 15785 [BPF_JSET >> 4] = BPF_JSET, 15786 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 15787 [BPF_JGE >> 4] = BPF_JLE, 15788 [BPF_JGT >> 4] = BPF_JLT, 15789 [BPF_JLE >> 4] = BPF_JGE, 15790 [BPF_JLT >> 4] = BPF_JGT, 15791 [BPF_JSGE >> 4] = BPF_JSLE, 15792 [BPF_JSGT >> 4] = BPF_JSLT, 15793 [BPF_JSLE >> 4] = BPF_JSGE, 15794 [BPF_JSLT >> 4] = BPF_JSGT 15795 }; 15796 return opcode_flip[opcode >> 4]; 15797 } 15798 15799 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 15800 struct bpf_reg_state *src_reg, 15801 u8 opcode) 15802 { 15803 struct bpf_reg_state *pkt; 15804 15805 if (src_reg->type == PTR_TO_PACKET_END) { 15806 pkt = dst_reg; 15807 } else if (dst_reg->type == PTR_TO_PACKET_END) { 15808 pkt = src_reg; 15809 opcode = flip_opcode(opcode); 15810 } else { 15811 return -1; 15812 } 15813 15814 if (pkt->range >= 0) 15815 return -1; 15816 15817 switch (opcode) { 15818 case BPF_JLE: 15819 /* pkt <= pkt_end */ 15820 fallthrough; 15821 case BPF_JGT: 15822 /* pkt > pkt_end */ 15823 if (pkt->range == BEYOND_PKT_END) 15824 /* pkt has at last one extra byte beyond pkt_end */ 15825 return opcode == BPF_JGT; 15826 break; 15827 case BPF_JLT: 15828 /* pkt < pkt_end */ 15829 fallthrough; 15830 case BPF_JGE: 15831 /* pkt >= pkt_end */ 15832 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 15833 return opcode == BPF_JGE; 15834 break; 15835 } 15836 return -1; 15837 } 15838 15839 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 15840 * and return: 15841 * 1 - branch will be taken and "goto target" will be executed 15842 * 0 - branch will not be taken and fall-through to next insn 15843 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 15844 * range [0,10] 15845 */ 15846 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15847 u8 opcode, bool is_jmp32) 15848 { 15849 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 15850 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 15851 15852 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 15853 u64 val; 15854 15855 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 15856 if (!is_reg_const(reg2, is_jmp32)) { 15857 opcode = flip_opcode(opcode); 15858 swap(reg1, reg2); 15859 } 15860 /* and ensure that reg2 is a constant */ 15861 if (!is_reg_const(reg2, is_jmp32)) 15862 return -1; 15863 15864 if (!reg_not_null(reg1)) 15865 return -1; 15866 15867 /* If pointer is valid tests against zero will fail so we can 15868 * use this to direct branch taken. 15869 */ 15870 val = reg_const_value(reg2, is_jmp32); 15871 if (val != 0) 15872 return -1; 15873 15874 switch (opcode) { 15875 case BPF_JEQ: 15876 return 0; 15877 case BPF_JNE: 15878 return 1; 15879 default: 15880 return -1; 15881 } 15882 } 15883 15884 /* now deal with two scalars, but not necessarily constants */ 15885 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 15886 } 15887 15888 /* Opcode that corresponds to a *false* branch condition. 15889 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 15890 */ 15891 static u8 rev_opcode(u8 opcode) 15892 { 15893 switch (opcode) { 15894 case BPF_JEQ: return BPF_JNE; 15895 case BPF_JNE: return BPF_JEQ; 15896 /* JSET doesn't have it's reverse opcode in BPF, so add 15897 * BPF_X flag to denote the reverse of that operation 15898 */ 15899 case BPF_JSET: return BPF_JSET | BPF_X; 15900 case BPF_JSET | BPF_X: return BPF_JSET; 15901 case BPF_JGE: return BPF_JLT; 15902 case BPF_JGT: return BPF_JLE; 15903 case BPF_JLE: return BPF_JGT; 15904 case BPF_JLT: return BPF_JGE; 15905 case BPF_JSGE: return BPF_JSLT; 15906 case BPF_JSGT: return BPF_JSLE; 15907 case BPF_JSLE: return BPF_JSGT; 15908 case BPF_JSLT: return BPF_JSGE; 15909 default: return 0; 15910 } 15911 } 15912 15913 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 15914 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15915 u8 opcode, bool is_jmp32) 15916 { 15917 struct tnum t; 15918 u64 val; 15919 15920 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 15921 switch (opcode) { 15922 case BPF_JGE: 15923 case BPF_JGT: 15924 case BPF_JSGE: 15925 case BPF_JSGT: 15926 opcode = flip_opcode(opcode); 15927 swap(reg1, reg2); 15928 break; 15929 default: 15930 break; 15931 } 15932 15933 switch (opcode) { 15934 case BPF_JEQ: 15935 if (is_jmp32) { 15936 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 15937 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 15938 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 15939 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 15940 reg2->u32_min_value = reg1->u32_min_value; 15941 reg2->u32_max_value = reg1->u32_max_value; 15942 reg2->s32_min_value = reg1->s32_min_value; 15943 reg2->s32_max_value = reg1->s32_max_value; 15944 15945 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 15946 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15947 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 15948 } else { 15949 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 15950 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 15951 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 15952 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 15953 reg2->umin_value = reg1->umin_value; 15954 reg2->umax_value = reg1->umax_value; 15955 reg2->smin_value = reg1->smin_value; 15956 reg2->smax_value = reg1->smax_value; 15957 15958 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 15959 reg2->var_off = reg1->var_off; 15960 } 15961 break; 15962 case BPF_JNE: 15963 if (!is_reg_const(reg2, is_jmp32)) 15964 swap(reg1, reg2); 15965 if (!is_reg_const(reg2, is_jmp32)) 15966 break; 15967 15968 /* try to recompute the bound of reg1 if reg2 is a const and 15969 * is exactly the edge of reg1. 15970 */ 15971 val = reg_const_value(reg2, is_jmp32); 15972 if (is_jmp32) { 15973 /* u32_min_value is not equal to 0xffffffff at this point, 15974 * because otherwise u32_max_value is 0xffffffff as well, 15975 * in such a case both reg1 and reg2 would be constants, 15976 * jump would be predicted and reg_set_min_max() won't 15977 * be called. 15978 * 15979 * Same reasoning works for all {u,s}{min,max}{32,64} cases 15980 * below. 15981 */ 15982 if (reg1->u32_min_value == (u32)val) 15983 reg1->u32_min_value++; 15984 if (reg1->u32_max_value == (u32)val) 15985 reg1->u32_max_value--; 15986 if (reg1->s32_min_value == (s32)val) 15987 reg1->s32_min_value++; 15988 if (reg1->s32_max_value == (s32)val) 15989 reg1->s32_max_value--; 15990 } else { 15991 if (reg1->umin_value == (u64)val) 15992 reg1->umin_value++; 15993 if (reg1->umax_value == (u64)val) 15994 reg1->umax_value--; 15995 if (reg1->smin_value == (s64)val) 15996 reg1->smin_value++; 15997 if (reg1->smax_value == (s64)val) 15998 reg1->smax_value--; 15999 } 16000 break; 16001 case BPF_JSET: 16002 if (!is_reg_const(reg2, is_jmp32)) 16003 swap(reg1, reg2); 16004 if (!is_reg_const(reg2, is_jmp32)) 16005 break; 16006 val = reg_const_value(reg2, is_jmp32); 16007 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 16008 * requires single bit to learn something useful. E.g., if we 16009 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 16010 * are actually set? We can learn something definite only if 16011 * it's a single-bit value to begin with. 16012 * 16013 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 16014 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 16015 * bit 1 is set, which we can readily use in adjustments. 16016 */ 16017 if (!is_power_of_2(val)) 16018 break; 16019 if (is_jmp32) { 16020 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 16021 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 16022 } else { 16023 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 16024 } 16025 break; 16026 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 16027 if (!is_reg_const(reg2, is_jmp32)) 16028 swap(reg1, reg2); 16029 if (!is_reg_const(reg2, is_jmp32)) 16030 break; 16031 val = reg_const_value(reg2, is_jmp32); 16032 if (is_jmp32) { 16033 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 16034 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 16035 } else { 16036 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 16037 } 16038 break; 16039 case BPF_JLE: 16040 if (is_jmp32) { 16041 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 16042 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 16043 } else { 16044 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 16045 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 16046 } 16047 break; 16048 case BPF_JLT: 16049 if (is_jmp32) { 16050 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 16051 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 16052 } else { 16053 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 16054 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 16055 } 16056 break; 16057 case BPF_JSLE: 16058 if (is_jmp32) { 16059 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 16060 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 16061 } else { 16062 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 16063 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 16064 } 16065 break; 16066 case BPF_JSLT: 16067 if (is_jmp32) { 16068 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 16069 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 16070 } else { 16071 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 16072 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 16073 } 16074 break; 16075 default: 16076 return; 16077 } 16078 } 16079 16080 /* Adjusts the register min/max values in the case that the dst_reg and 16081 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 16082 * check, in which case we have a fake SCALAR_VALUE representing insn->imm). 16083 * Technically we can do similar adjustments for pointers to the same object, 16084 * but we don't support that right now. 16085 */ 16086 static int reg_set_min_max(struct bpf_verifier_env *env, 16087 struct bpf_reg_state *true_reg1, 16088 struct bpf_reg_state *true_reg2, 16089 struct bpf_reg_state *false_reg1, 16090 struct bpf_reg_state *false_reg2, 16091 u8 opcode, bool is_jmp32) 16092 { 16093 int err; 16094 16095 /* If either register is a pointer, we can't learn anything about its 16096 * variable offset from the compare (unless they were a pointer into 16097 * the same object, but we don't bother with that). 16098 */ 16099 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 16100 return 0; 16101 16102 /* fallthrough (FALSE) branch */ 16103 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 16104 reg_bounds_sync(false_reg1); 16105 reg_bounds_sync(false_reg2); 16106 16107 /* jump (TRUE) branch */ 16108 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 16109 reg_bounds_sync(true_reg1); 16110 reg_bounds_sync(true_reg2); 16111 16112 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 16113 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 16114 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 16115 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 16116 return err; 16117 } 16118 16119 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 16120 struct bpf_reg_state *reg, u32 id, 16121 bool is_null) 16122 { 16123 if (type_may_be_null(reg->type) && reg->id == id && 16124 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 16125 /* Old offset (both fixed and variable parts) should have been 16126 * known-zero, because we don't allow pointer arithmetic on 16127 * pointers that might be NULL. If we see this happening, don't 16128 * convert the register. 16129 * 16130 * But in some cases, some helpers that return local kptrs 16131 * advance offset for the returned pointer. In those cases, it 16132 * is fine to expect to see reg->off. 16133 */ 16134 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 16135 return; 16136 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 16137 WARN_ON_ONCE(reg->off)) 16138 return; 16139 16140 if (is_null) { 16141 reg->type = SCALAR_VALUE; 16142 /* We don't need id and ref_obj_id from this point 16143 * onwards anymore, thus we should better reset it, 16144 * so that state pruning has chances to take effect. 16145 */ 16146 reg->id = 0; 16147 reg->ref_obj_id = 0; 16148 16149 return; 16150 } 16151 16152 mark_ptr_not_null_reg(reg); 16153 16154 if (!reg_may_point_to_spin_lock(reg)) { 16155 /* For not-NULL ptr, reg->ref_obj_id will be reset 16156 * in release_reference(). 16157 * 16158 * reg->id is still used by spin_lock ptr. Other 16159 * than spin_lock ptr type, reg->id can be reset. 16160 */ 16161 reg->id = 0; 16162 } 16163 } 16164 } 16165 16166 /* The logic is similar to find_good_pkt_pointers(), both could eventually 16167 * be folded together at some point. 16168 */ 16169 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 16170 bool is_null) 16171 { 16172 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 16173 struct bpf_reg_state *regs = state->regs, *reg; 16174 u32 ref_obj_id = regs[regno].ref_obj_id; 16175 u32 id = regs[regno].id; 16176 16177 if (ref_obj_id && ref_obj_id == id && is_null) 16178 /* regs[regno] is in the " == NULL" branch. 16179 * No one could have freed the reference state before 16180 * doing the NULL check. 16181 */ 16182 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 16183 16184 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 16185 mark_ptr_or_null_reg(state, reg, id, is_null); 16186 })); 16187 } 16188 16189 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 16190 struct bpf_reg_state *dst_reg, 16191 struct bpf_reg_state *src_reg, 16192 struct bpf_verifier_state *this_branch, 16193 struct bpf_verifier_state *other_branch) 16194 { 16195 if (BPF_SRC(insn->code) != BPF_X) 16196 return false; 16197 16198 /* Pointers are always 64-bit. */ 16199 if (BPF_CLASS(insn->code) == BPF_JMP32) 16200 return false; 16201 16202 switch (BPF_OP(insn->code)) { 16203 case BPF_JGT: 16204 if ((dst_reg->type == PTR_TO_PACKET && 16205 src_reg->type == PTR_TO_PACKET_END) || 16206 (dst_reg->type == PTR_TO_PACKET_META && 16207 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16208 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 16209 find_good_pkt_pointers(this_branch, dst_reg, 16210 dst_reg->type, false); 16211 mark_pkt_end(other_branch, insn->dst_reg, true); 16212 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16213 src_reg->type == PTR_TO_PACKET) || 16214 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16215 src_reg->type == PTR_TO_PACKET_META)) { 16216 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 16217 find_good_pkt_pointers(other_branch, src_reg, 16218 src_reg->type, true); 16219 mark_pkt_end(this_branch, insn->src_reg, false); 16220 } else { 16221 return false; 16222 } 16223 break; 16224 case BPF_JLT: 16225 if ((dst_reg->type == PTR_TO_PACKET && 16226 src_reg->type == PTR_TO_PACKET_END) || 16227 (dst_reg->type == PTR_TO_PACKET_META && 16228 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16229 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 16230 find_good_pkt_pointers(other_branch, dst_reg, 16231 dst_reg->type, true); 16232 mark_pkt_end(this_branch, insn->dst_reg, false); 16233 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16234 src_reg->type == PTR_TO_PACKET) || 16235 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16236 src_reg->type == PTR_TO_PACKET_META)) { 16237 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 16238 find_good_pkt_pointers(this_branch, src_reg, 16239 src_reg->type, false); 16240 mark_pkt_end(other_branch, insn->src_reg, true); 16241 } else { 16242 return false; 16243 } 16244 break; 16245 case BPF_JGE: 16246 if ((dst_reg->type == PTR_TO_PACKET && 16247 src_reg->type == PTR_TO_PACKET_END) || 16248 (dst_reg->type == PTR_TO_PACKET_META && 16249 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16250 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 16251 find_good_pkt_pointers(this_branch, dst_reg, 16252 dst_reg->type, true); 16253 mark_pkt_end(other_branch, insn->dst_reg, false); 16254 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16255 src_reg->type == PTR_TO_PACKET) || 16256 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16257 src_reg->type == PTR_TO_PACKET_META)) { 16258 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 16259 find_good_pkt_pointers(other_branch, src_reg, 16260 src_reg->type, false); 16261 mark_pkt_end(this_branch, insn->src_reg, true); 16262 } else { 16263 return false; 16264 } 16265 break; 16266 case BPF_JLE: 16267 if ((dst_reg->type == PTR_TO_PACKET && 16268 src_reg->type == PTR_TO_PACKET_END) || 16269 (dst_reg->type == PTR_TO_PACKET_META && 16270 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16271 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 16272 find_good_pkt_pointers(other_branch, dst_reg, 16273 dst_reg->type, false); 16274 mark_pkt_end(this_branch, insn->dst_reg, true); 16275 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16276 src_reg->type == PTR_TO_PACKET) || 16277 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16278 src_reg->type == PTR_TO_PACKET_META)) { 16279 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 16280 find_good_pkt_pointers(this_branch, src_reg, 16281 src_reg->type, true); 16282 mark_pkt_end(other_branch, insn->src_reg, false); 16283 } else { 16284 return false; 16285 } 16286 break; 16287 default: 16288 return false; 16289 } 16290 16291 return true; 16292 } 16293 16294 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 16295 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 16296 { 16297 struct linked_reg *e; 16298 16299 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 16300 return; 16301 16302 e = linked_regs_push(reg_set); 16303 if (e) { 16304 e->frameno = frameno; 16305 e->is_reg = is_reg; 16306 e->regno = spi_or_reg; 16307 } else { 16308 reg->id = 0; 16309 } 16310 } 16311 16312 /* For all R being scalar registers or spilled scalar registers 16313 * in verifier state, save R in linked_regs if R->id == id. 16314 * If there are too many Rs sharing same id, reset id for leftover Rs. 16315 */ 16316 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id, 16317 struct linked_regs *linked_regs) 16318 { 16319 struct bpf_func_state *func; 16320 struct bpf_reg_state *reg; 16321 int i, j; 16322 16323 id = id & ~BPF_ADD_CONST; 16324 for (i = vstate->curframe; i >= 0; i--) { 16325 func = vstate->frame[i]; 16326 for (j = 0; j < BPF_REG_FP; j++) { 16327 reg = &func->regs[j]; 16328 __collect_linked_regs(linked_regs, reg, id, i, j, true); 16329 } 16330 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 16331 if (!is_spilled_reg(&func->stack[j])) 16332 continue; 16333 reg = &func->stack[j].spilled_ptr; 16334 __collect_linked_regs(linked_regs, reg, id, i, j, false); 16335 } 16336 } 16337 } 16338 16339 /* For all R in linked_regs, copy known_reg range into R 16340 * if R->id == known_reg->id. 16341 */ 16342 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg, 16343 struct linked_regs *linked_regs) 16344 { 16345 struct bpf_reg_state fake_reg; 16346 struct bpf_reg_state *reg; 16347 struct linked_reg *e; 16348 int i; 16349 16350 for (i = 0; i < linked_regs->cnt; ++i) { 16351 e = &linked_regs->entries[i]; 16352 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 16353 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 16354 if (reg->type != SCALAR_VALUE || reg == known_reg) 16355 continue; 16356 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 16357 continue; 16358 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 16359 reg->off == known_reg->off) { 16360 s32 saved_subreg_def = reg->subreg_def; 16361 16362 copy_register_state(reg, known_reg); 16363 reg->subreg_def = saved_subreg_def; 16364 } else { 16365 s32 saved_subreg_def = reg->subreg_def; 16366 s32 saved_off = reg->off; 16367 16368 fake_reg.type = SCALAR_VALUE; 16369 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off); 16370 16371 /* reg = known_reg; reg += delta */ 16372 copy_register_state(reg, known_reg); 16373 /* 16374 * Must preserve off, id and add_const flag, 16375 * otherwise another sync_linked_regs() will be incorrect. 16376 */ 16377 reg->off = saved_off; 16378 reg->subreg_def = saved_subreg_def; 16379 16380 scalar32_min_max_add(reg, &fake_reg); 16381 scalar_min_max_add(reg, &fake_reg); 16382 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 16383 } 16384 } 16385 } 16386 16387 static int check_cond_jmp_op(struct bpf_verifier_env *env, 16388 struct bpf_insn *insn, int *insn_idx) 16389 { 16390 struct bpf_verifier_state *this_branch = env->cur_state; 16391 struct bpf_verifier_state *other_branch; 16392 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 16393 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 16394 struct bpf_reg_state *eq_branch_regs; 16395 struct linked_regs linked_regs = {}; 16396 u8 opcode = BPF_OP(insn->code); 16397 int insn_flags = 0; 16398 bool is_jmp32; 16399 int pred = -1; 16400 int err; 16401 16402 /* Only conditional jumps are expected to reach here. */ 16403 if (opcode == BPF_JA || opcode > BPF_JCOND) { 16404 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 16405 return -EINVAL; 16406 } 16407 16408 if (opcode == BPF_JCOND) { 16409 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 16410 int idx = *insn_idx; 16411 16412 if (insn->code != (BPF_JMP | BPF_JCOND) || 16413 insn->src_reg != BPF_MAY_GOTO || 16414 insn->dst_reg || insn->imm) { 16415 verbose(env, "invalid may_goto imm %d\n", insn->imm); 16416 return -EINVAL; 16417 } 16418 prev_st = find_prev_entry(env, cur_st->parent, idx); 16419 16420 /* branch out 'fallthrough' insn as a new state to explore */ 16421 queued_st = push_stack(env, idx + 1, idx, false); 16422 if (!queued_st) 16423 return -ENOMEM; 16424 16425 queued_st->may_goto_depth++; 16426 if (prev_st) 16427 widen_imprecise_scalars(env, prev_st, queued_st); 16428 *insn_idx += insn->off; 16429 return 0; 16430 } 16431 16432 /* check src2 operand */ 16433 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16434 if (err) 16435 return err; 16436 16437 dst_reg = ®s[insn->dst_reg]; 16438 if (BPF_SRC(insn->code) == BPF_X) { 16439 if (insn->imm != 0) { 16440 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 16441 return -EINVAL; 16442 } 16443 16444 /* check src1 operand */ 16445 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16446 if (err) 16447 return err; 16448 16449 src_reg = ®s[insn->src_reg]; 16450 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 16451 is_pointer_value(env, insn->src_reg)) { 16452 verbose(env, "R%d pointer comparison prohibited\n", 16453 insn->src_reg); 16454 return -EACCES; 16455 } 16456 16457 if (src_reg->type == PTR_TO_STACK) 16458 insn_flags |= INSN_F_SRC_REG_STACK; 16459 if (dst_reg->type == PTR_TO_STACK) 16460 insn_flags |= INSN_F_DST_REG_STACK; 16461 } else { 16462 if (insn->src_reg != BPF_REG_0) { 16463 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 16464 return -EINVAL; 16465 } 16466 src_reg = &env->fake_reg[0]; 16467 memset(src_reg, 0, sizeof(*src_reg)); 16468 src_reg->type = SCALAR_VALUE; 16469 __mark_reg_known(src_reg, insn->imm); 16470 16471 if (dst_reg->type == PTR_TO_STACK) 16472 insn_flags |= INSN_F_DST_REG_STACK; 16473 } 16474 16475 if (insn_flags) { 16476 err = push_insn_history(env, this_branch, insn_flags, 0); 16477 if (err) 16478 return err; 16479 } 16480 16481 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 16482 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 16483 if (pred >= 0) { 16484 /* If we get here with a dst_reg pointer type it is because 16485 * above is_branch_taken() special cased the 0 comparison. 16486 */ 16487 if (!__is_pointer_value(false, dst_reg)) 16488 err = mark_chain_precision(env, insn->dst_reg); 16489 if (BPF_SRC(insn->code) == BPF_X && !err && 16490 !__is_pointer_value(false, src_reg)) 16491 err = mark_chain_precision(env, insn->src_reg); 16492 if (err) 16493 return err; 16494 } 16495 16496 if (pred == 1) { 16497 /* Only follow the goto, ignore fall-through. If needed, push 16498 * the fall-through branch for simulation under speculative 16499 * execution. 16500 */ 16501 if (!env->bypass_spec_v1 && 16502 !sanitize_speculative_path(env, insn, *insn_idx + 1, 16503 *insn_idx)) 16504 return -EFAULT; 16505 if (env->log.level & BPF_LOG_LEVEL) 16506 print_insn_state(env, this_branch, this_branch->curframe); 16507 *insn_idx += insn->off; 16508 return 0; 16509 } else if (pred == 0) { 16510 /* Only follow the fall-through branch, since that's where the 16511 * program will go. If needed, push the goto branch for 16512 * simulation under speculative execution. 16513 */ 16514 if (!env->bypass_spec_v1 && 16515 !sanitize_speculative_path(env, insn, 16516 *insn_idx + insn->off + 1, 16517 *insn_idx)) 16518 return -EFAULT; 16519 if (env->log.level & BPF_LOG_LEVEL) 16520 print_insn_state(env, this_branch, this_branch->curframe); 16521 return 0; 16522 } 16523 16524 /* Push scalar registers sharing same ID to jump history, 16525 * do this before creating 'other_branch', so that both 16526 * 'this_branch' and 'other_branch' share this history 16527 * if parent state is created. 16528 */ 16529 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 16530 collect_linked_regs(this_branch, src_reg->id, &linked_regs); 16531 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 16532 collect_linked_regs(this_branch, dst_reg->id, &linked_regs); 16533 if (linked_regs.cnt > 1) { 16534 err = push_insn_history(env, this_branch, 0, linked_regs_pack(&linked_regs)); 16535 if (err) 16536 return err; 16537 } 16538 16539 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 16540 false); 16541 if (!other_branch) 16542 return -EFAULT; 16543 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 16544 16545 if (BPF_SRC(insn->code) == BPF_X) { 16546 err = reg_set_min_max(env, 16547 &other_branch_regs[insn->dst_reg], 16548 &other_branch_regs[insn->src_reg], 16549 dst_reg, src_reg, opcode, is_jmp32); 16550 } else /* BPF_SRC(insn->code) == BPF_K */ { 16551 /* reg_set_min_max() can mangle the fake_reg. Make a copy 16552 * so that these are two different memory locations. The 16553 * src_reg is not used beyond here in context of K. 16554 */ 16555 memcpy(&env->fake_reg[1], &env->fake_reg[0], 16556 sizeof(env->fake_reg[0])); 16557 err = reg_set_min_max(env, 16558 &other_branch_regs[insn->dst_reg], 16559 &env->fake_reg[0], 16560 dst_reg, &env->fake_reg[1], 16561 opcode, is_jmp32); 16562 } 16563 if (err) 16564 return err; 16565 16566 if (BPF_SRC(insn->code) == BPF_X && 16567 src_reg->type == SCALAR_VALUE && src_reg->id && 16568 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 16569 sync_linked_regs(this_branch, src_reg, &linked_regs); 16570 sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs); 16571 } 16572 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 16573 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 16574 sync_linked_regs(this_branch, dst_reg, &linked_regs); 16575 sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs); 16576 } 16577 16578 /* if one pointer register is compared to another pointer 16579 * register check if PTR_MAYBE_NULL could be lifted. 16580 * E.g. register A - maybe null 16581 * register B - not null 16582 * for JNE A, B, ... - A is not null in the false branch; 16583 * for JEQ A, B, ... - A is not null in the true branch. 16584 * 16585 * Since PTR_TO_BTF_ID points to a kernel struct that does 16586 * not need to be null checked by the BPF program, i.e., 16587 * could be null even without PTR_MAYBE_NULL marking, so 16588 * only propagate nullness when neither reg is that type. 16589 */ 16590 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16591 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16592 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16593 base_type(src_reg->type) != PTR_TO_BTF_ID && 16594 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16595 eq_branch_regs = NULL; 16596 switch (opcode) { 16597 case BPF_JEQ: 16598 eq_branch_regs = other_branch_regs; 16599 break; 16600 case BPF_JNE: 16601 eq_branch_regs = regs; 16602 break; 16603 default: 16604 /* do nothing */ 16605 break; 16606 } 16607 if (eq_branch_regs) { 16608 if (type_may_be_null(src_reg->type)) 16609 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16610 else 16611 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16612 } 16613 } 16614 16615 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16616 * NOTE: these optimizations below are related with pointer comparison 16617 * which will never be JMP32. 16618 */ 16619 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 16620 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16621 type_may_be_null(dst_reg->type)) { 16622 /* Mark all identical registers in each branch as either 16623 * safe or unknown depending R == 0 or R != 0 conditional. 16624 */ 16625 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16626 opcode == BPF_JNE); 16627 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16628 opcode == BPF_JEQ); 16629 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16630 this_branch, other_branch) && 16631 is_pointer_value(env, insn->dst_reg)) { 16632 verbose(env, "R%d pointer comparison prohibited\n", 16633 insn->dst_reg); 16634 return -EACCES; 16635 } 16636 if (env->log.level & BPF_LOG_LEVEL) 16637 print_insn_state(env, this_branch, this_branch->curframe); 16638 return 0; 16639 } 16640 16641 /* verify BPF_LD_IMM64 instruction */ 16642 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16643 { 16644 struct bpf_insn_aux_data *aux = cur_aux(env); 16645 struct bpf_reg_state *regs = cur_regs(env); 16646 struct bpf_reg_state *dst_reg; 16647 struct bpf_map *map; 16648 int err; 16649 16650 if (BPF_SIZE(insn->code) != BPF_DW) { 16651 verbose(env, "invalid BPF_LD_IMM insn\n"); 16652 return -EINVAL; 16653 } 16654 if (insn->off != 0) { 16655 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 16656 return -EINVAL; 16657 } 16658 16659 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16660 if (err) 16661 return err; 16662 16663 dst_reg = ®s[insn->dst_reg]; 16664 if (insn->src_reg == 0) { 16665 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16666 16667 dst_reg->type = SCALAR_VALUE; 16668 __mark_reg_known(®s[insn->dst_reg], imm); 16669 return 0; 16670 } 16671 16672 /* All special src_reg cases are listed below. From this point onwards 16673 * we either succeed and assign a corresponding dst_reg->type after 16674 * zeroing the offset, or fail and reject the program. 16675 */ 16676 mark_reg_known_zero(env, regs, insn->dst_reg); 16677 16678 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16679 dst_reg->type = aux->btf_var.reg_type; 16680 switch (base_type(dst_reg->type)) { 16681 case PTR_TO_MEM: 16682 dst_reg->mem_size = aux->btf_var.mem_size; 16683 break; 16684 case PTR_TO_BTF_ID: 16685 dst_reg->btf = aux->btf_var.btf; 16686 dst_reg->btf_id = aux->btf_var.btf_id; 16687 break; 16688 default: 16689 verbose(env, "bpf verifier is misconfigured\n"); 16690 return -EFAULT; 16691 } 16692 return 0; 16693 } 16694 16695 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16696 struct bpf_prog_aux *aux = env->prog->aux; 16697 u32 subprogno = find_subprog(env, 16698 env->insn_idx + insn->imm + 1); 16699 16700 if (!aux->func_info) { 16701 verbose(env, "missing btf func_info\n"); 16702 return -EINVAL; 16703 } 16704 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16705 verbose(env, "callback function not static\n"); 16706 return -EINVAL; 16707 } 16708 16709 dst_reg->type = PTR_TO_FUNC; 16710 dst_reg->subprogno = subprogno; 16711 return 0; 16712 } 16713 16714 map = env->used_maps[aux->map_index]; 16715 dst_reg->map_ptr = map; 16716 16717 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16718 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16719 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16720 __mark_reg_unknown(env, dst_reg); 16721 return 0; 16722 } 16723 dst_reg->type = PTR_TO_MAP_VALUE; 16724 dst_reg->off = aux->map_off; 16725 WARN_ON_ONCE(map->max_entries != 1); 16726 /* We want reg->id to be same (0) as map_value is not distinct */ 16727 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16728 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16729 dst_reg->type = CONST_PTR_TO_MAP; 16730 } else { 16731 verbose(env, "bpf verifier is misconfigured\n"); 16732 return -EINVAL; 16733 } 16734 16735 return 0; 16736 } 16737 16738 static bool may_access_skb(enum bpf_prog_type type) 16739 { 16740 switch (type) { 16741 case BPF_PROG_TYPE_SOCKET_FILTER: 16742 case BPF_PROG_TYPE_SCHED_CLS: 16743 case BPF_PROG_TYPE_SCHED_ACT: 16744 return true; 16745 default: 16746 return false; 16747 } 16748 } 16749 16750 /* verify safety of LD_ABS|LD_IND instructions: 16751 * - they can only appear in the programs where ctx == skb 16752 * - since they are wrappers of function calls, they scratch R1-R5 registers, 16753 * preserve R6-R9, and store return value into R0 16754 * 16755 * Implicit input: 16756 * ctx == skb == R6 == CTX 16757 * 16758 * Explicit input: 16759 * SRC == any register 16760 * IMM == 32-bit immediate 16761 * 16762 * Output: 16763 * R0 - 8/16/32-bit skb data converted to cpu endianness 16764 */ 16765 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 16766 { 16767 struct bpf_reg_state *regs = cur_regs(env); 16768 static const int ctx_reg = BPF_REG_6; 16769 u8 mode = BPF_MODE(insn->code); 16770 int i, err; 16771 16772 if (!may_access_skb(resolve_prog_type(env->prog))) { 16773 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 16774 return -EINVAL; 16775 } 16776 16777 if (!env->ops->gen_ld_abs) { 16778 verbose(env, "bpf verifier is misconfigured\n"); 16779 return -EINVAL; 16780 } 16781 16782 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 16783 BPF_SIZE(insn->code) == BPF_DW || 16784 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 16785 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 16786 return -EINVAL; 16787 } 16788 16789 /* check whether implicit source operand (register R6) is readable */ 16790 err = check_reg_arg(env, ctx_reg, SRC_OP); 16791 if (err) 16792 return err; 16793 16794 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 16795 * gen_ld_abs() may terminate the program at runtime, leading to 16796 * reference leak. 16797 */ 16798 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 16799 if (err) 16800 return err; 16801 16802 if (regs[ctx_reg].type != PTR_TO_CTX) { 16803 verbose(env, 16804 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 16805 return -EINVAL; 16806 } 16807 16808 if (mode == BPF_IND) { 16809 /* check explicit source operand */ 16810 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16811 if (err) 16812 return err; 16813 } 16814 16815 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 16816 if (err < 0) 16817 return err; 16818 16819 /* reset caller saved regs to unreadable */ 16820 for (i = 0; i < CALLER_SAVED_REGS; i++) { 16821 mark_reg_not_init(env, regs, caller_saved[i]); 16822 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 16823 } 16824 16825 /* mark destination R0 register as readable, since it contains 16826 * the value fetched from the packet. 16827 * Already marked as written above. 16828 */ 16829 mark_reg_unknown(env, regs, BPF_REG_0); 16830 /* ld_abs load up to 32-bit skb data. */ 16831 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 16832 return 0; 16833 } 16834 16835 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 16836 { 16837 const char *exit_ctx = "At program exit"; 16838 struct tnum enforce_attach_type_range = tnum_unknown; 16839 const struct bpf_prog *prog = env->prog; 16840 struct bpf_reg_state *reg = reg_state(env, regno); 16841 struct bpf_retval_range range = retval_range(0, 1); 16842 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16843 int err; 16844 struct bpf_func_state *frame = env->cur_state->frame[0]; 16845 const bool is_subprog = frame->subprogno; 16846 bool return_32bit = false; 16847 const struct btf_type *reg_type, *ret_type = NULL; 16848 16849 /* LSM and struct_ops func-ptr's return type could be "void" */ 16850 if (!is_subprog || frame->in_exception_callback_fn) { 16851 switch (prog_type) { 16852 case BPF_PROG_TYPE_LSM: 16853 if (prog->expected_attach_type == BPF_LSM_CGROUP) 16854 /* See below, can be 0 or 0-1 depending on hook. */ 16855 break; 16856 if (!prog->aux->attach_func_proto->type) 16857 return 0; 16858 break; 16859 case BPF_PROG_TYPE_STRUCT_OPS: 16860 if (!prog->aux->attach_func_proto->type) 16861 return 0; 16862 16863 if (frame->in_exception_callback_fn) 16864 break; 16865 16866 /* Allow a struct_ops program to return a referenced kptr if it 16867 * matches the operator's return type and is in its unmodified 16868 * form. A scalar zero (i.e., a null pointer) is also allowed. 16869 */ 16870 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 16871 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 16872 prog->aux->attach_func_proto->type, 16873 NULL); 16874 if (ret_type && ret_type == reg_type && reg->ref_obj_id) 16875 return __check_ptr_off_reg(env, reg, regno, false); 16876 break; 16877 default: 16878 break; 16879 } 16880 } 16881 16882 /* eBPF calling convention is such that R0 is used 16883 * to return the value from eBPF program. 16884 * Make sure that it's readable at this time 16885 * of bpf_exit, which means that program wrote 16886 * something into it earlier 16887 */ 16888 err = check_reg_arg(env, regno, SRC_OP); 16889 if (err) 16890 return err; 16891 16892 if (is_pointer_value(env, regno)) { 16893 verbose(env, "R%d leaks addr as return value\n", regno); 16894 return -EACCES; 16895 } 16896 16897 if (frame->in_async_callback_fn) { 16898 /* enforce return zero from async callbacks like timer */ 16899 exit_ctx = "At async callback return"; 16900 range = retval_range(0, 0); 16901 goto enforce_retval; 16902 } 16903 16904 if (is_subprog && !frame->in_exception_callback_fn) { 16905 if (reg->type != SCALAR_VALUE) { 16906 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 16907 regno, reg_type_str(env, reg->type)); 16908 return -EINVAL; 16909 } 16910 return 0; 16911 } 16912 16913 switch (prog_type) { 16914 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 16915 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 16916 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 16917 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 16918 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 16919 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 16920 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 16921 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 16922 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 16923 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 16924 range = retval_range(1, 1); 16925 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 16926 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 16927 range = retval_range(0, 3); 16928 break; 16929 case BPF_PROG_TYPE_CGROUP_SKB: 16930 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 16931 range = retval_range(0, 3); 16932 enforce_attach_type_range = tnum_range(2, 3); 16933 } 16934 break; 16935 case BPF_PROG_TYPE_CGROUP_SOCK: 16936 case BPF_PROG_TYPE_SOCK_OPS: 16937 case BPF_PROG_TYPE_CGROUP_DEVICE: 16938 case BPF_PROG_TYPE_CGROUP_SYSCTL: 16939 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 16940 break; 16941 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16942 if (!env->prog->aux->attach_btf_id) 16943 return 0; 16944 range = retval_range(0, 0); 16945 break; 16946 case BPF_PROG_TYPE_TRACING: 16947 switch (env->prog->expected_attach_type) { 16948 case BPF_TRACE_FENTRY: 16949 case BPF_TRACE_FEXIT: 16950 range = retval_range(0, 0); 16951 break; 16952 case BPF_TRACE_RAW_TP: 16953 case BPF_MODIFY_RETURN: 16954 return 0; 16955 case BPF_TRACE_ITER: 16956 break; 16957 default: 16958 return -ENOTSUPP; 16959 } 16960 break; 16961 case BPF_PROG_TYPE_KPROBE: 16962 switch (env->prog->expected_attach_type) { 16963 case BPF_TRACE_KPROBE_SESSION: 16964 case BPF_TRACE_UPROBE_SESSION: 16965 range = retval_range(0, 1); 16966 break; 16967 default: 16968 return 0; 16969 } 16970 break; 16971 case BPF_PROG_TYPE_SK_LOOKUP: 16972 range = retval_range(SK_DROP, SK_PASS); 16973 break; 16974 16975 case BPF_PROG_TYPE_LSM: 16976 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 16977 /* no range found, any return value is allowed */ 16978 if (!get_func_retval_range(env->prog, &range)) 16979 return 0; 16980 /* no restricted range, any return value is allowed */ 16981 if (range.minval == S32_MIN && range.maxval == S32_MAX) 16982 return 0; 16983 return_32bit = true; 16984 } else if (!env->prog->aux->attach_func_proto->type) { 16985 /* Make sure programs that attach to void 16986 * hooks don't try to modify return value. 16987 */ 16988 range = retval_range(1, 1); 16989 } 16990 break; 16991 16992 case BPF_PROG_TYPE_NETFILTER: 16993 range = retval_range(NF_DROP, NF_ACCEPT); 16994 break; 16995 case BPF_PROG_TYPE_STRUCT_OPS: 16996 if (!ret_type) 16997 return 0; 16998 range = retval_range(0, 0); 16999 break; 17000 case BPF_PROG_TYPE_EXT: 17001 /* freplace program can return anything as its return value 17002 * depends on the to-be-replaced kernel func or bpf program. 17003 */ 17004 default: 17005 return 0; 17006 } 17007 17008 enforce_retval: 17009 if (reg->type != SCALAR_VALUE) { 17010 verbose(env, "%s the register R%d is not a known value (%s)\n", 17011 exit_ctx, regno, reg_type_str(env, reg->type)); 17012 return -EINVAL; 17013 } 17014 17015 err = mark_chain_precision(env, regno); 17016 if (err) 17017 return err; 17018 17019 if (!retval_range_within(range, reg, return_32bit)) { 17020 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 17021 if (!is_subprog && 17022 prog->expected_attach_type == BPF_LSM_CGROUP && 17023 prog_type == BPF_PROG_TYPE_LSM && 17024 !prog->aux->attach_func_proto->type) 17025 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 17026 return -EINVAL; 17027 } 17028 17029 if (!tnum_is_unknown(enforce_attach_type_range) && 17030 tnum_in(enforce_attach_type_range, reg->var_off)) 17031 env->prog->enforce_expected_attach_type = 1; 17032 return 0; 17033 } 17034 17035 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off) 17036 { 17037 struct bpf_subprog_info *subprog; 17038 17039 subprog = find_containing_subprog(env, off); 17040 subprog->changes_pkt_data = true; 17041 } 17042 17043 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off) 17044 { 17045 struct bpf_subprog_info *subprog; 17046 17047 subprog = find_containing_subprog(env, off); 17048 subprog->might_sleep = true; 17049 } 17050 17051 /* 't' is an index of a call-site. 17052 * 'w' is a callee entry point. 17053 * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED. 17054 * Rely on DFS traversal order and absence of recursive calls to guarantee that 17055 * callee's change_pkt_data marks would be correct at that moment. 17056 */ 17057 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w) 17058 { 17059 struct bpf_subprog_info *caller, *callee; 17060 17061 caller = find_containing_subprog(env, t); 17062 callee = find_containing_subprog(env, w); 17063 caller->changes_pkt_data |= callee->changes_pkt_data; 17064 caller->might_sleep |= callee->might_sleep; 17065 } 17066 17067 /* non-recursive DFS pseudo code 17068 * 1 procedure DFS-iterative(G,v): 17069 * 2 label v as discovered 17070 * 3 let S be a stack 17071 * 4 S.push(v) 17072 * 5 while S is not empty 17073 * 6 t <- S.peek() 17074 * 7 if t is what we're looking for: 17075 * 8 return t 17076 * 9 for all edges e in G.adjacentEdges(t) do 17077 * 10 if edge e is already labelled 17078 * 11 continue with the next edge 17079 * 12 w <- G.adjacentVertex(t,e) 17080 * 13 if vertex w is not discovered and not explored 17081 * 14 label e as tree-edge 17082 * 15 label w as discovered 17083 * 16 S.push(w) 17084 * 17 continue at 5 17085 * 18 else if vertex w is discovered 17086 * 19 label e as back-edge 17087 * 20 else 17088 * 21 // vertex w is explored 17089 * 22 label e as forward- or cross-edge 17090 * 23 label t as explored 17091 * 24 S.pop() 17092 * 17093 * convention: 17094 * 0x10 - discovered 17095 * 0x11 - discovered and fall-through edge labelled 17096 * 0x12 - discovered and fall-through and branch edges labelled 17097 * 0x20 - explored 17098 */ 17099 17100 enum { 17101 DISCOVERED = 0x10, 17102 EXPLORED = 0x20, 17103 FALLTHROUGH = 1, 17104 BRANCH = 2, 17105 }; 17106 17107 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 17108 { 17109 env->insn_aux_data[idx].prune_point = true; 17110 } 17111 17112 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 17113 { 17114 return env->insn_aux_data[insn_idx].prune_point; 17115 } 17116 17117 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 17118 { 17119 env->insn_aux_data[idx].force_checkpoint = true; 17120 } 17121 17122 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 17123 { 17124 return env->insn_aux_data[insn_idx].force_checkpoint; 17125 } 17126 17127 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 17128 { 17129 env->insn_aux_data[idx].calls_callback = true; 17130 } 17131 17132 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 17133 { 17134 return env->insn_aux_data[insn_idx].calls_callback; 17135 } 17136 17137 enum { 17138 DONE_EXPLORING = 0, 17139 KEEP_EXPLORING = 1, 17140 }; 17141 17142 /* t, w, e - match pseudo-code above: 17143 * t - index of current instruction 17144 * w - next instruction 17145 * e - edge 17146 */ 17147 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 17148 { 17149 int *insn_stack = env->cfg.insn_stack; 17150 int *insn_state = env->cfg.insn_state; 17151 17152 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 17153 return DONE_EXPLORING; 17154 17155 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 17156 return DONE_EXPLORING; 17157 17158 if (w < 0 || w >= env->prog->len) { 17159 verbose_linfo(env, t, "%d: ", t); 17160 verbose(env, "jump out of range from insn %d to %d\n", t, w); 17161 return -EINVAL; 17162 } 17163 17164 if (e == BRANCH) { 17165 /* mark branch target for state pruning */ 17166 mark_prune_point(env, w); 17167 mark_jmp_point(env, w); 17168 } 17169 17170 if (insn_state[w] == 0) { 17171 /* tree-edge */ 17172 insn_state[t] = DISCOVERED | e; 17173 insn_state[w] = DISCOVERED; 17174 if (env->cfg.cur_stack >= env->prog->len) 17175 return -E2BIG; 17176 insn_stack[env->cfg.cur_stack++] = w; 17177 return KEEP_EXPLORING; 17178 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 17179 if (env->bpf_capable) 17180 return DONE_EXPLORING; 17181 verbose_linfo(env, t, "%d: ", t); 17182 verbose_linfo(env, w, "%d: ", w); 17183 verbose(env, "back-edge from insn %d to %d\n", t, w); 17184 return -EINVAL; 17185 } else if (insn_state[w] == EXPLORED) { 17186 /* forward- or cross-edge */ 17187 insn_state[t] = DISCOVERED | e; 17188 } else { 17189 verbose(env, "insn state internal bug\n"); 17190 return -EFAULT; 17191 } 17192 return DONE_EXPLORING; 17193 } 17194 17195 static int visit_func_call_insn(int t, struct bpf_insn *insns, 17196 struct bpf_verifier_env *env, 17197 bool visit_callee) 17198 { 17199 int ret, insn_sz; 17200 int w; 17201 17202 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 17203 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 17204 if (ret) 17205 return ret; 17206 17207 mark_prune_point(env, t + insn_sz); 17208 /* when we exit from subprog, we need to record non-linear history */ 17209 mark_jmp_point(env, t + insn_sz); 17210 17211 if (visit_callee) { 17212 w = t + insns[t].imm + 1; 17213 mark_prune_point(env, t); 17214 merge_callee_effects(env, t, w); 17215 ret = push_insn(t, w, BRANCH, env); 17216 } 17217 return ret; 17218 } 17219 17220 /* Bitmask with 1s for all caller saved registers */ 17221 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 17222 17223 /* True if do_misc_fixups() replaces calls to helper number 'imm', 17224 * replacement patch is presumed to follow bpf_fastcall contract 17225 * (see mark_fastcall_pattern_for_call() below). 17226 */ 17227 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 17228 { 17229 switch (imm) { 17230 #ifdef CONFIG_X86_64 17231 case BPF_FUNC_get_smp_processor_id: 17232 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 17233 #endif 17234 default: 17235 return false; 17236 } 17237 } 17238 17239 struct call_summary { 17240 u8 num_params; 17241 bool is_void; 17242 bool fastcall; 17243 }; 17244 17245 /* If @call is a kfunc or helper call, fills @cs and returns true, 17246 * otherwise returns false. 17247 */ 17248 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 17249 struct call_summary *cs) 17250 { 17251 struct bpf_kfunc_call_arg_meta meta; 17252 const struct bpf_func_proto *fn; 17253 int i; 17254 17255 if (bpf_helper_call(call)) { 17256 17257 if (get_helper_proto(env, call->imm, &fn) < 0) 17258 /* error would be reported later */ 17259 return false; 17260 cs->fastcall = fn->allow_fastcall && 17261 (verifier_inlines_helper_call(env, call->imm) || 17262 bpf_jit_inlines_helper_call(call->imm)); 17263 cs->is_void = fn->ret_type == RET_VOID; 17264 cs->num_params = 0; 17265 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 17266 if (fn->arg_type[i] == ARG_DONTCARE) 17267 break; 17268 cs->num_params++; 17269 } 17270 return true; 17271 } 17272 17273 if (bpf_pseudo_kfunc_call(call)) { 17274 int err; 17275 17276 err = fetch_kfunc_meta(env, call, &meta, NULL); 17277 if (err < 0) 17278 /* error would be reported later */ 17279 return false; 17280 cs->num_params = btf_type_vlen(meta.func_proto); 17281 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 17282 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 17283 return true; 17284 } 17285 17286 return false; 17287 } 17288 17289 /* LLVM define a bpf_fastcall function attribute. 17290 * This attribute means that function scratches only some of 17291 * the caller saved registers defined by ABI. 17292 * For BPF the set of such registers could be defined as follows: 17293 * - R0 is scratched only if function is non-void; 17294 * - R1-R5 are scratched only if corresponding parameter type is defined 17295 * in the function prototype. 17296 * 17297 * The contract between kernel and clang allows to simultaneously use 17298 * such functions and maintain backwards compatibility with old 17299 * kernels that don't understand bpf_fastcall calls: 17300 * 17301 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 17302 * registers are not scratched by the call; 17303 * 17304 * - as a post-processing step, clang visits each bpf_fastcall call and adds 17305 * spill/fill for every live r0-r5; 17306 * 17307 * - stack offsets used for the spill/fill are allocated as lowest 17308 * stack offsets in whole function and are not used for any other 17309 * purposes; 17310 * 17311 * - when kernel loads a program, it looks for such patterns 17312 * (bpf_fastcall function surrounded by spills/fills) and checks if 17313 * spill/fill stack offsets are used exclusively in fastcall patterns; 17314 * 17315 * - if so, and if verifier or current JIT inlines the call to the 17316 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 17317 * spill/fill pairs; 17318 * 17319 * - when old kernel loads a program, presence of spill/fill pairs 17320 * keeps BPF program valid, albeit slightly less efficient. 17321 * 17322 * For example: 17323 * 17324 * r1 = 1; 17325 * r2 = 2; 17326 * *(u64 *)(r10 - 8) = r1; r1 = 1; 17327 * *(u64 *)(r10 - 16) = r2; r2 = 2; 17328 * call %[to_be_inlined] --> call %[to_be_inlined] 17329 * r2 = *(u64 *)(r10 - 16); r0 = r1; 17330 * r1 = *(u64 *)(r10 - 8); r0 += r2; 17331 * r0 = r1; exit; 17332 * r0 += r2; 17333 * exit; 17334 * 17335 * The purpose of mark_fastcall_pattern_for_call is to: 17336 * - look for such patterns; 17337 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 17338 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 17339 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 17340 * at which bpf_fastcall spill/fill stack slots start; 17341 * - update env->subprog_info[*]->keep_fastcall_stack. 17342 * 17343 * The .fastcall_pattern and .fastcall_stack_off are used by 17344 * check_fastcall_stack_contract() to check if every stack access to 17345 * fastcall spill/fill stack slot originates from spill/fill 17346 * instructions, members of fastcall patterns. 17347 * 17348 * If such condition holds true for a subprogram, fastcall patterns could 17349 * be rewritten by remove_fastcall_spills_fills(). 17350 * Otherwise bpf_fastcall patterns are not changed in the subprogram 17351 * (code, presumably, generated by an older clang version). 17352 * 17353 * For example, it is *not* safe to remove spill/fill below: 17354 * 17355 * r1 = 1; 17356 * *(u64 *)(r10 - 8) = r1; r1 = 1; 17357 * call %[to_be_inlined] --> call %[to_be_inlined] 17358 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 17359 * r0 = *(u64 *)(r10 - 8); r0 += r1; 17360 * r0 += r1; exit; 17361 * exit; 17362 */ 17363 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 17364 struct bpf_subprog_info *subprog, 17365 int insn_idx, s16 lowest_off) 17366 { 17367 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 17368 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 17369 u32 clobbered_regs_mask; 17370 struct call_summary cs; 17371 u32 expected_regs_mask; 17372 s16 off; 17373 int i; 17374 17375 if (!get_call_summary(env, call, &cs)) 17376 return; 17377 17378 /* A bitmask specifying which caller saved registers are clobbered 17379 * by a call to a helper/kfunc *as if* this helper/kfunc follows 17380 * bpf_fastcall contract: 17381 * - includes R0 if function is non-void; 17382 * - includes R1-R5 if corresponding parameter has is described 17383 * in the function prototype. 17384 */ 17385 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 17386 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 17387 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 17388 17389 /* match pairs of form: 17390 * 17391 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 17392 * ... 17393 * call %[to_be_inlined] 17394 * ... 17395 * rX = *(u64 *)(r10 - Y) 17396 */ 17397 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 17398 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 17399 break; 17400 stx = &insns[insn_idx - i]; 17401 ldx = &insns[insn_idx + i]; 17402 /* must be a stack spill/fill pair */ 17403 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 17404 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 17405 stx->dst_reg != BPF_REG_10 || 17406 ldx->src_reg != BPF_REG_10) 17407 break; 17408 /* must be a spill/fill for the same reg */ 17409 if (stx->src_reg != ldx->dst_reg) 17410 break; 17411 /* must be one of the previously unseen registers */ 17412 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 17413 break; 17414 /* must be a spill/fill for the same expected offset, 17415 * no need to check offset alignment, BPF_DW stack access 17416 * is always 8-byte aligned. 17417 */ 17418 if (stx->off != off || ldx->off != off) 17419 break; 17420 expected_regs_mask &= ~BIT(stx->src_reg); 17421 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 17422 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 17423 } 17424 if (i == 1) 17425 return; 17426 17427 /* Conditionally set 'fastcall_spills_num' to allow forward 17428 * compatibility when more helper functions are marked as 17429 * bpf_fastcall at compile time than current kernel supports, e.g: 17430 * 17431 * 1: *(u64 *)(r10 - 8) = r1 17432 * 2: call A ;; assume A is bpf_fastcall for current kernel 17433 * 3: r1 = *(u64 *)(r10 - 8) 17434 * 4: *(u64 *)(r10 - 8) = r1 17435 * 5: call B ;; assume B is not bpf_fastcall for current kernel 17436 * 6: r1 = *(u64 *)(r10 - 8) 17437 * 17438 * There is no need to block bpf_fastcall rewrite for such program. 17439 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 17440 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 17441 * does not remove spill/fill pair {4,6}. 17442 */ 17443 if (cs.fastcall) 17444 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 17445 else 17446 subprog->keep_fastcall_stack = 1; 17447 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 17448 } 17449 17450 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 17451 { 17452 struct bpf_subprog_info *subprog = env->subprog_info; 17453 struct bpf_insn *insn; 17454 s16 lowest_off; 17455 int s, i; 17456 17457 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 17458 /* find lowest stack spill offset used in this subprog */ 17459 lowest_off = 0; 17460 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 17461 insn = env->prog->insnsi + i; 17462 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 17463 insn->dst_reg != BPF_REG_10) 17464 continue; 17465 lowest_off = min(lowest_off, insn->off); 17466 } 17467 /* use this offset to find fastcall patterns */ 17468 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 17469 insn = env->prog->insnsi + i; 17470 if (insn->code != (BPF_JMP | BPF_CALL)) 17471 continue; 17472 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 17473 } 17474 } 17475 return 0; 17476 } 17477 17478 /* Visits the instruction at index t and returns one of the following: 17479 * < 0 - an error occurred 17480 * DONE_EXPLORING - the instruction was fully explored 17481 * KEEP_EXPLORING - there is still work to be done before it is fully explored 17482 */ 17483 static int visit_insn(int t, struct bpf_verifier_env *env) 17484 { 17485 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 17486 int ret, off, insn_sz; 17487 17488 if (bpf_pseudo_func(insn)) 17489 return visit_func_call_insn(t, insns, env, true); 17490 17491 /* All non-branch instructions have a single fall-through edge. */ 17492 if (BPF_CLASS(insn->code) != BPF_JMP && 17493 BPF_CLASS(insn->code) != BPF_JMP32) { 17494 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 17495 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 17496 } 17497 17498 switch (BPF_OP(insn->code)) { 17499 case BPF_EXIT: 17500 return DONE_EXPLORING; 17501 17502 case BPF_CALL: 17503 if (is_async_callback_calling_insn(insn)) 17504 /* Mark this call insn as a prune point to trigger 17505 * is_state_visited() check before call itself is 17506 * processed by __check_func_call(). Otherwise new 17507 * async state will be pushed for further exploration. 17508 */ 17509 mark_prune_point(env, t); 17510 /* For functions that invoke callbacks it is not known how many times 17511 * callback would be called. Verifier models callback calling functions 17512 * by repeatedly visiting callback bodies and returning to origin call 17513 * instruction. 17514 * In order to stop such iteration verifier needs to identify when a 17515 * state identical some state from a previous iteration is reached. 17516 * Check below forces creation of checkpoint before callback calling 17517 * instruction to allow search for such identical states. 17518 */ 17519 if (is_sync_callback_calling_insn(insn)) { 17520 mark_calls_callback(env, t); 17521 mark_force_checkpoint(env, t); 17522 mark_prune_point(env, t); 17523 mark_jmp_point(env, t); 17524 } 17525 if (bpf_helper_call(insn)) { 17526 const struct bpf_func_proto *fp; 17527 17528 ret = get_helper_proto(env, insn->imm, &fp); 17529 /* If called in a non-sleepable context program will be 17530 * rejected anyway, so we should end up with precise 17531 * sleepable marks on subprogs, except for dead code 17532 * elimination. 17533 */ 17534 if (ret == 0 && fp->might_sleep) 17535 mark_subprog_might_sleep(env, t); 17536 if (bpf_helper_changes_pkt_data(insn->imm)) 17537 mark_subprog_changes_pkt_data(env, t); 17538 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17539 struct bpf_kfunc_call_arg_meta meta; 17540 17541 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 17542 if (ret == 0 && is_iter_next_kfunc(&meta)) { 17543 mark_prune_point(env, t); 17544 /* Checking and saving state checkpoints at iter_next() call 17545 * is crucial for fast convergence of open-coded iterator loop 17546 * logic, so we need to force it. If we don't do that, 17547 * is_state_visited() might skip saving a checkpoint, causing 17548 * unnecessarily long sequence of not checkpointed 17549 * instructions and jumps, leading to exhaustion of jump 17550 * history buffer, and potentially other undesired outcomes. 17551 * It is expected that with correct open-coded iterators 17552 * convergence will happen quickly, so we don't run a risk of 17553 * exhausting memory. 17554 */ 17555 mark_force_checkpoint(env, t); 17556 } 17557 /* Same as helpers, if called in a non-sleepable context 17558 * program will be rejected anyway, so we should end up 17559 * with precise sleepable marks on subprogs, except for 17560 * dead code elimination. 17561 */ 17562 if (ret == 0 && is_kfunc_sleepable(&meta)) 17563 mark_subprog_might_sleep(env, t); 17564 } 17565 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 17566 17567 case BPF_JA: 17568 if (BPF_SRC(insn->code) != BPF_K) 17569 return -EINVAL; 17570 17571 if (BPF_CLASS(insn->code) == BPF_JMP) 17572 off = insn->off; 17573 else 17574 off = insn->imm; 17575 17576 /* unconditional jump with single edge */ 17577 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 17578 if (ret) 17579 return ret; 17580 17581 mark_prune_point(env, t + off + 1); 17582 mark_jmp_point(env, t + off + 1); 17583 17584 return ret; 17585 17586 default: 17587 /* conditional jump with two edges */ 17588 mark_prune_point(env, t); 17589 if (is_may_goto_insn(insn)) 17590 mark_force_checkpoint(env, t); 17591 17592 ret = push_insn(t, t + 1, FALLTHROUGH, env); 17593 if (ret) 17594 return ret; 17595 17596 return push_insn(t, t + insn->off + 1, BRANCH, env); 17597 } 17598 } 17599 17600 /* non-recursive depth-first-search to detect loops in BPF program 17601 * loop == back-edge in directed graph 17602 */ 17603 static int check_cfg(struct bpf_verifier_env *env) 17604 { 17605 int insn_cnt = env->prog->len; 17606 int *insn_stack, *insn_state, *insn_postorder; 17607 int ex_insn_beg, i, ret = 0; 17608 17609 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 17610 if (!insn_state) 17611 return -ENOMEM; 17612 17613 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 17614 if (!insn_stack) { 17615 kvfree(insn_state); 17616 return -ENOMEM; 17617 } 17618 17619 insn_postorder = env->cfg.insn_postorder = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 17620 if (!insn_postorder) { 17621 kvfree(insn_state); 17622 kvfree(insn_stack); 17623 return -ENOMEM; 17624 } 17625 17626 ex_insn_beg = env->exception_callback_subprog 17627 ? env->subprog_info[env->exception_callback_subprog].start 17628 : 0; 17629 17630 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 17631 insn_stack[0] = 0; /* 0 is the first instruction */ 17632 env->cfg.cur_stack = 1; 17633 17634 walk_cfg: 17635 while (env->cfg.cur_stack > 0) { 17636 int t = insn_stack[env->cfg.cur_stack - 1]; 17637 17638 ret = visit_insn(t, env); 17639 switch (ret) { 17640 case DONE_EXPLORING: 17641 insn_state[t] = EXPLORED; 17642 env->cfg.cur_stack--; 17643 insn_postorder[env->cfg.cur_postorder++] = t; 17644 break; 17645 case KEEP_EXPLORING: 17646 break; 17647 default: 17648 if (ret > 0) { 17649 verbose(env, "visit_insn internal bug\n"); 17650 ret = -EFAULT; 17651 } 17652 goto err_free; 17653 } 17654 } 17655 17656 if (env->cfg.cur_stack < 0) { 17657 verbose(env, "pop stack internal bug\n"); 17658 ret = -EFAULT; 17659 goto err_free; 17660 } 17661 17662 if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) { 17663 insn_state[ex_insn_beg] = DISCOVERED; 17664 insn_stack[0] = ex_insn_beg; 17665 env->cfg.cur_stack = 1; 17666 goto walk_cfg; 17667 } 17668 17669 for (i = 0; i < insn_cnt; i++) { 17670 struct bpf_insn *insn = &env->prog->insnsi[i]; 17671 17672 if (insn_state[i] != EXPLORED) { 17673 verbose(env, "unreachable insn %d\n", i); 17674 ret = -EINVAL; 17675 goto err_free; 17676 } 17677 if (bpf_is_ldimm64(insn)) { 17678 if (insn_state[i + 1] != 0) { 17679 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 17680 ret = -EINVAL; 17681 goto err_free; 17682 } 17683 i++; /* skip second half of ldimm64 */ 17684 } 17685 } 17686 ret = 0; /* cfg looks good */ 17687 env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data; 17688 env->prog->aux->might_sleep = env->subprog_info[0].might_sleep; 17689 17690 err_free: 17691 kvfree(insn_state); 17692 kvfree(insn_stack); 17693 env->cfg.insn_state = env->cfg.insn_stack = NULL; 17694 return ret; 17695 } 17696 17697 static int check_abnormal_return(struct bpf_verifier_env *env) 17698 { 17699 int i; 17700 17701 for (i = 1; i < env->subprog_cnt; i++) { 17702 if (env->subprog_info[i].has_ld_abs) { 17703 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 17704 return -EINVAL; 17705 } 17706 if (env->subprog_info[i].has_tail_call) { 17707 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 17708 return -EINVAL; 17709 } 17710 } 17711 return 0; 17712 } 17713 17714 /* The minimum supported BTF func info size */ 17715 #define MIN_BPF_FUNCINFO_SIZE 8 17716 #define MAX_FUNCINFO_REC_SIZE 252 17717 17718 static int check_btf_func_early(struct bpf_verifier_env *env, 17719 const union bpf_attr *attr, 17720 bpfptr_t uattr) 17721 { 17722 u32 krec_size = sizeof(struct bpf_func_info); 17723 const struct btf_type *type, *func_proto; 17724 u32 i, nfuncs, urec_size, min_size; 17725 struct bpf_func_info *krecord; 17726 struct bpf_prog *prog; 17727 const struct btf *btf; 17728 u32 prev_offset = 0; 17729 bpfptr_t urecord; 17730 int ret = -ENOMEM; 17731 17732 nfuncs = attr->func_info_cnt; 17733 if (!nfuncs) { 17734 if (check_abnormal_return(env)) 17735 return -EINVAL; 17736 return 0; 17737 } 17738 17739 urec_size = attr->func_info_rec_size; 17740 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 17741 urec_size > MAX_FUNCINFO_REC_SIZE || 17742 urec_size % sizeof(u32)) { 17743 verbose(env, "invalid func info rec size %u\n", urec_size); 17744 return -EINVAL; 17745 } 17746 17747 prog = env->prog; 17748 btf = prog->aux->btf; 17749 17750 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 17751 min_size = min_t(u32, krec_size, urec_size); 17752 17753 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 17754 if (!krecord) 17755 return -ENOMEM; 17756 17757 for (i = 0; i < nfuncs; i++) { 17758 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 17759 if (ret) { 17760 if (ret == -E2BIG) { 17761 verbose(env, "nonzero tailing record in func info"); 17762 /* set the size kernel expects so loader can zero 17763 * out the rest of the record. 17764 */ 17765 if (copy_to_bpfptr_offset(uattr, 17766 offsetof(union bpf_attr, func_info_rec_size), 17767 &min_size, sizeof(min_size))) 17768 ret = -EFAULT; 17769 } 17770 goto err_free; 17771 } 17772 17773 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 17774 ret = -EFAULT; 17775 goto err_free; 17776 } 17777 17778 /* check insn_off */ 17779 ret = -EINVAL; 17780 if (i == 0) { 17781 if (krecord[i].insn_off) { 17782 verbose(env, 17783 "nonzero insn_off %u for the first func info record", 17784 krecord[i].insn_off); 17785 goto err_free; 17786 } 17787 } else if (krecord[i].insn_off <= prev_offset) { 17788 verbose(env, 17789 "same or smaller insn offset (%u) than previous func info record (%u)", 17790 krecord[i].insn_off, prev_offset); 17791 goto err_free; 17792 } 17793 17794 /* check type_id */ 17795 type = btf_type_by_id(btf, krecord[i].type_id); 17796 if (!type || !btf_type_is_func(type)) { 17797 verbose(env, "invalid type id %d in func info", 17798 krecord[i].type_id); 17799 goto err_free; 17800 } 17801 17802 func_proto = btf_type_by_id(btf, type->type); 17803 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 17804 /* btf_func_check() already verified it during BTF load */ 17805 goto err_free; 17806 17807 prev_offset = krecord[i].insn_off; 17808 bpfptr_add(&urecord, urec_size); 17809 } 17810 17811 prog->aux->func_info = krecord; 17812 prog->aux->func_info_cnt = nfuncs; 17813 return 0; 17814 17815 err_free: 17816 kvfree(krecord); 17817 return ret; 17818 } 17819 17820 static int check_btf_func(struct bpf_verifier_env *env, 17821 const union bpf_attr *attr, 17822 bpfptr_t uattr) 17823 { 17824 const struct btf_type *type, *func_proto, *ret_type; 17825 u32 i, nfuncs, urec_size; 17826 struct bpf_func_info *krecord; 17827 struct bpf_func_info_aux *info_aux = NULL; 17828 struct bpf_prog *prog; 17829 const struct btf *btf; 17830 bpfptr_t urecord; 17831 bool scalar_return; 17832 int ret = -ENOMEM; 17833 17834 nfuncs = attr->func_info_cnt; 17835 if (!nfuncs) { 17836 if (check_abnormal_return(env)) 17837 return -EINVAL; 17838 return 0; 17839 } 17840 if (nfuncs != env->subprog_cnt) { 17841 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 17842 return -EINVAL; 17843 } 17844 17845 urec_size = attr->func_info_rec_size; 17846 17847 prog = env->prog; 17848 btf = prog->aux->btf; 17849 17850 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 17851 17852 krecord = prog->aux->func_info; 17853 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 17854 if (!info_aux) 17855 return -ENOMEM; 17856 17857 for (i = 0; i < nfuncs; i++) { 17858 /* check insn_off */ 17859 ret = -EINVAL; 17860 17861 if (env->subprog_info[i].start != krecord[i].insn_off) { 17862 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 17863 goto err_free; 17864 } 17865 17866 /* Already checked type_id */ 17867 type = btf_type_by_id(btf, krecord[i].type_id); 17868 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 17869 /* Already checked func_proto */ 17870 func_proto = btf_type_by_id(btf, type->type); 17871 17872 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 17873 scalar_return = 17874 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 17875 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 17876 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 17877 goto err_free; 17878 } 17879 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 17880 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 17881 goto err_free; 17882 } 17883 17884 bpfptr_add(&urecord, urec_size); 17885 } 17886 17887 prog->aux->func_info_aux = info_aux; 17888 return 0; 17889 17890 err_free: 17891 kfree(info_aux); 17892 return ret; 17893 } 17894 17895 static void adjust_btf_func(struct bpf_verifier_env *env) 17896 { 17897 struct bpf_prog_aux *aux = env->prog->aux; 17898 int i; 17899 17900 if (!aux->func_info) 17901 return; 17902 17903 /* func_info is not available for hidden subprogs */ 17904 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 17905 aux->func_info[i].insn_off = env->subprog_info[i].start; 17906 } 17907 17908 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 17909 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 17910 17911 static int check_btf_line(struct bpf_verifier_env *env, 17912 const union bpf_attr *attr, 17913 bpfptr_t uattr) 17914 { 17915 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 17916 struct bpf_subprog_info *sub; 17917 struct bpf_line_info *linfo; 17918 struct bpf_prog *prog; 17919 const struct btf *btf; 17920 bpfptr_t ulinfo; 17921 int err; 17922 17923 nr_linfo = attr->line_info_cnt; 17924 if (!nr_linfo) 17925 return 0; 17926 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 17927 return -EINVAL; 17928 17929 rec_size = attr->line_info_rec_size; 17930 if (rec_size < MIN_BPF_LINEINFO_SIZE || 17931 rec_size > MAX_LINEINFO_REC_SIZE || 17932 rec_size & (sizeof(u32) - 1)) 17933 return -EINVAL; 17934 17935 /* Need to zero it in case the userspace may 17936 * pass in a smaller bpf_line_info object. 17937 */ 17938 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 17939 GFP_KERNEL | __GFP_NOWARN); 17940 if (!linfo) 17941 return -ENOMEM; 17942 17943 prog = env->prog; 17944 btf = prog->aux->btf; 17945 17946 s = 0; 17947 sub = env->subprog_info; 17948 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 17949 expected_size = sizeof(struct bpf_line_info); 17950 ncopy = min_t(u32, expected_size, rec_size); 17951 for (i = 0; i < nr_linfo; i++) { 17952 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 17953 if (err) { 17954 if (err == -E2BIG) { 17955 verbose(env, "nonzero tailing record in line_info"); 17956 if (copy_to_bpfptr_offset(uattr, 17957 offsetof(union bpf_attr, line_info_rec_size), 17958 &expected_size, sizeof(expected_size))) 17959 err = -EFAULT; 17960 } 17961 goto err_free; 17962 } 17963 17964 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 17965 err = -EFAULT; 17966 goto err_free; 17967 } 17968 17969 /* 17970 * Check insn_off to ensure 17971 * 1) strictly increasing AND 17972 * 2) bounded by prog->len 17973 * 17974 * The linfo[0].insn_off == 0 check logically falls into 17975 * the later "missing bpf_line_info for func..." case 17976 * because the first linfo[0].insn_off must be the 17977 * first sub also and the first sub must have 17978 * subprog_info[0].start == 0. 17979 */ 17980 if ((i && linfo[i].insn_off <= prev_offset) || 17981 linfo[i].insn_off >= prog->len) { 17982 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 17983 i, linfo[i].insn_off, prev_offset, 17984 prog->len); 17985 err = -EINVAL; 17986 goto err_free; 17987 } 17988 17989 if (!prog->insnsi[linfo[i].insn_off].code) { 17990 verbose(env, 17991 "Invalid insn code at line_info[%u].insn_off\n", 17992 i); 17993 err = -EINVAL; 17994 goto err_free; 17995 } 17996 17997 if (!btf_name_by_offset(btf, linfo[i].line_off) || 17998 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 17999 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 18000 err = -EINVAL; 18001 goto err_free; 18002 } 18003 18004 if (s != env->subprog_cnt) { 18005 if (linfo[i].insn_off == sub[s].start) { 18006 sub[s].linfo_idx = i; 18007 s++; 18008 } else if (sub[s].start < linfo[i].insn_off) { 18009 verbose(env, "missing bpf_line_info for func#%u\n", s); 18010 err = -EINVAL; 18011 goto err_free; 18012 } 18013 } 18014 18015 prev_offset = linfo[i].insn_off; 18016 bpfptr_add(&ulinfo, rec_size); 18017 } 18018 18019 if (s != env->subprog_cnt) { 18020 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 18021 env->subprog_cnt - s, s); 18022 err = -EINVAL; 18023 goto err_free; 18024 } 18025 18026 prog->aux->linfo = linfo; 18027 prog->aux->nr_linfo = nr_linfo; 18028 18029 return 0; 18030 18031 err_free: 18032 kvfree(linfo); 18033 return err; 18034 } 18035 18036 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 18037 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 18038 18039 static int check_core_relo(struct bpf_verifier_env *env, 18040 const union bpf_attr *attr, 18041 bpfptr_t uattr) 18042 { 18043 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 18044 struct bpf_core_relo core_relo = {}; 18045 struct bpf_prog *prog = env->prog; 18046 const struct btf *btf = prog->aux->btf; 18047 struct bpf_core_ctx ctx = { 18048 .log = &env->log, 18049 .btf = btf, 18050 }; 18051 bpfptr_t u_core_relo; 18052 int err; 18053 18054 nr_core_relo = attr->core_relo_cnt; 18055 if (!nr_core_relo) 18056 return 0; 18057 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 18058 return -EINVAL; 18059 18060 rec_size = attr->core_relo_rec_size; 18061 if (rec_size < MIN_CORE_RELO_SIZE || 18062 rec_size > MAX_CORE_RELO_SIZE || 18063 rec_size % sizeof(u32)) 18064 return -EINVAL; 18065 18066 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 18067 expected_size = sizeof(struct bpf_core_relo); 18068 ncopy = min_t(u32, expected_size, rec_size); 18069 18070 /* Unlike func_info and line_info, copy and apply each CO-RE 18071 * relocation record one at a time. 18072 */ 18073 for (i = 0; i < nr_core_relo; i++) { 18074 /* future proofing when sizeof(bpf_core_relo) changes */ 18075 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 18076 if (err) { 18077 if (err == -E2BIG) { 18078 verbose(env, "nonzero tailing record in core_relo"); 18079 if (copy_to_bpfptr_offset(uattr, 18080 offsetof(union bpf_attr, core_relo_rec_size), 18081 &expected_size, sizeof(expected_size))) 18082 err = -EFAULT; 18083 } 18084 break; 18085 } 18086 18087 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 18088 err = -EFAULT; 18089 break; 18090 } 18091 18092 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 18093 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 18094 i, core_relo.insn_off, prog->len); 18095 err = -EINVAL; 18096 break; 18097 } 18098 18099 err = bpf_core_apply(&ctx, &core_relo, i, 18100 &prog->insnsi[core_relo.insn_off / 8]); 18101 if (err) 18102 break; 18103 bpfptr_add(&u_core_relo, rec_size); 18104 } 18105 return err; 18106 } 18107 18108 static int check_btf_info_early(struct bpf_verifier_env *env, 18109 const union bpf_attr *attr, 18110 bpfptr_t uattr) 18111 { 18112 struct btf *btf; 18113 int err; 18114 18115 if (!attr->func_info_cnt && !attr->line_info_cnt) { 18116 if (check_abnormal_return(env)) 18117 return -EINVAL; 18118 return 0; 18119 } 18120 18121 btf = btf_get_by_fd(attr->prog_btf_fd); 18122 if (IS_ERR(btf)) 18123 return PTR_ERR(btf); 18124 if (btf_is_kernel(btf)) { 18125 btf_put(btf); 18126 return -EACCES; 18127 } 18128 env->prog->aux->btf = btf; 18129 18130 err = check_btf_func_early(env, attr, uattr); 18131 if (err) 18132 return err; 18133 return 0; 18134 } 18135 18136 static int check_btf_info(struct bpf_verifier_env *env, 18137 const union bpf_attr *attr, 18138 bpfptr_t uattr) 18139 { 18140 int err; 18141 18142 if (!attr->func_info_cnt && !attr->line_info_cnt) { 18143 if (check_abnormal_return(env)) 18144 return -EINVAL; 18145 return 0; 18146 } 18147 18148 err = check_btf_func(env, attr, uattr); 18149 if (err) 18150 return err; 18151 18152 err = check_btf_line(env, attr, uattr); 18153 if (err) 18154 return err; 18155 18156 err = check_core_relo(env, attr, uattr); 18157 if (err) 18158 return err; 18159 18160 return 0; 18161 } 18162 18163 /* check %cur's range satisfies %old's */ 18164 static bool range_within(const struct bpf_reg_state *old, 18165 const struct bpf_reg_state *cur) 18166 { 18167 return old->umin_value <= cur->umin_value && 18168 old->umax_value >= cur->umax_value && 18169 old->smin_value <= cur->smin_value && 18170 old->smax_value >= cur->smax_value && 18171 old->u32_min_value <= cur->u32_min_value && 18172 old->u32_max_value >= cur->u32_max_value && 18173 old->s32_min_value <= cur->s32_min_value && 18174 old->s32_max_value >= cur->s32_max_value; 18175 } 18176 18177 /* If in the old state two registers had the same id, then they need to have 18178 * the same id in the new state as well. But that id could be different from 18179 * the old state, so we need to track the mapping from old to new ids. 18180 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 18181 * regs with old id 5 must also have new id 9 for the new state to be safe. But 18182 * regs with a different old id could still have new id 9, we don't care about 18183 * that. 18184 * So we look through our idmap to see if this old id has been seen before. If 18185 * so, we require the new id to match; otherwise, we add the id pair to the map. 18186 */ 18187 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 18188 { 18189 struct bpf_id_pair *map = idmap->map; 18190 unsigned int i; 18191 18192 /* either both IDs should be set or both should be zero */ 18193 if (!!old_id != !!cur_id) 18194 return false; 18195 18196 if (old_id == 0) /* cur_id == 0 as well */ 18197 return true; 18198 18199 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 18200 if (!map[i].old) { 18201 /* Reached an empty slot; haven't seen this id before */ 18202 map[i].old = old_id; 18203 map[i].cur = cur_id; 18204 return true; 18205 } 18206 if (map[i].old == old_id) 18207 return map[i].cur == cur_id; 18208 if (map[i].cur == cur_id) 18209 return false; 18210 } 18211 /* We ran out of idmap slots, which should be impossible */ 18212 WARN_ON_ONCE(1); 18213 return false; 18214 } 18215 18216 /* Similar to check_ids(), but allocate a unique temporary ID 18217 * for 'old_id' or 'cur_id' of zero. 18218 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 18219 */ 18220 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 18221 { 18222 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 18223 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 18224 18225 return check_ids(old_id, cur_id, idmap); 18226 } 18227 18228 static void clean_func_state(struct bpf_verifier_env *env, 18229 struct bpf_func_state *st) 18230 { 18231 enum bpf_reg_liveness live; 18232 int i, j; 18233 18234 for (i = 0; i < BPF_REG_FP; i++) { 18235 live = st->regs[i].live; 18236 /* liveness must not touch this register anymore */ 18237 st->regs[i].live |= REG_LIVE_DONE; 18238 if (!(live & REG_LIVE_READ)) 18239 /* since the register is unused, clear its state 18240 * to make further comparison simpler 18241 */ 18242 __mark_reg_not_init(env, &st->regs[i]); 18243 } 18244 18245 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 18246 live = st->stack[i].spilled_ptr.live; 18247 /* liveness must not touch this stack slot anymore */ 18248 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 18249 if (!(live & REG_LIVE_READ)) { 18250 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 18251 for (j = 0; j < BPF_REG_SIZE; j++) 18252 st->stack[i].slot_type[j] = STACK_INVALID; 18253 } 18254 } 18255 } 18256 18257 static void clean_verifier_state(struct bpf_verifier_env *env, 18258 struct bpf_verifier_state *st) 18259 { 18260 int i; 18261 18262 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 18263 /* all regs in this state in all frames were already marked */ 18264 return; 18265 18266 for (i = 0; i <= st->curframe; i++) 18267 clean_func_state(env, st->frame[i]); 18268 } 18269 18270 /* the parentage chains form a tree. 18271 * the verifier states are added to state lists at given insn and 18272 * pushed into state stack for future exploration. 18273 * when the verifier reaches bpf_exit insn some of the verifer states 18274 * stored in the state lists have their final liveness state already, 18275 * but a lot of states will get revised from liveness point of view when 18276 * the verifier explores other branches. 18277 * Example: 18278 * 1: r0 = 1 18279 * 2: if r1 == 100 goto pc+1 18280 * 3: r0 = 2 18281 * 4: exit 18282 * when the verifier reaches exit insn the register r0 in the state list of 18283 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 18284 * of insn 2 and goes exploring further. At the insn 4 it will walk the 18285 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 18286 * 18287 * Since the verifier pushes the branch states as it sees them while exploring 18288 * the program the condition of walking the branch instruction for the second 18289 * time means that all states below this branch were already explored and 18290 * their final liveness marks are already propagated. 18291 * Hence when the verifier completes the search of state list in is_state_visited() 18292 * we can call this clean_live_states() function to mark all liveness states 18293 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 18294 * will not be used. 18295 * This function also clears the registers and stack for states that !READ 18296 * to simplify state merging. 18297 * 18298 * Important note here that walking the same branch instruction in the callee 18299 * doesn't meant that the states are DONE. The verifier has to compare 18300 * the callsites 18301 */ 18302 static void clean_live_states(struct bpf_verifier_env *env, int insn, 18303 struct bpf_verifier_state *cur) 18304 { 18305 struct bpf_verifier_state *loop_entry; 18306 struct bpf_verifier_state_list *sl; 18307 struct list_head *pos, *head; 18308 18309 head = explored_state(env, insn); 18310 list_for_each(pos, head) { 18311 sl = container_of(pos, struct bpf_verifier_state_list, node); 18312 if (sl->state.branches) 18313 continue; 18314 loop_entry = get_loop_entry(env, &sl->state); 18315 if (!IS_ERR_OR_NULL(loop_entry) && loop_entry->branches) 18316 continue; 18317 if (sl->state.insn_idx != insn || 18318 !same_callsites(&sl->state, cur)) 18319 continue; 18320 clean_verifier_state(env, &sl->state); 18321 } 18322 } 18323 18324 static bool regs_exact(const struct bpf_reg_state *rold, 18325 const struct bpf_reg_state *rcur, 18326 struct bpf_idmap *idmap) 18327 { 18328 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 18329 check_ids(rold->id, rcur->id, idmap) && 18330 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 18331 } 18332 18333 enum exact_level { 18334 NOT_EXACT, 18335 EXACT, 18336 RANGE_WITHIN 18337 }; 18338 18339 /* Returns true if (rold safe implies rcur safe) */ 18340 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 18341 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 18342 enum exact_level exact) 18343 { 18344 if (exact == EXACT) 18345 return regs_exact(rold, rcur, idmap); 18346 18347 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 18348 /* explored state didn't use this */ 18349 return true; 18350 if (rold->type == NOT_INIT) { 18351 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 18352 /* explored state can't have used this */ 18353 return true; 18354 } 18355 18356 /* Enforce that register types have to match exactly, including their 18357 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 18358 * rule. 18359 * 18360 * One can make a point that using a pointer register as unbounded 18361 * SCALAR would be technically acceptable, but this could lead to 18362 * pointer leaks because scalars are allowed to leak while pointers 18363 * are not. We could make this safe in special cases if root is 18364 * calling us, but it's probably not worth the hassle. 18365 * 18366 * Also, register types that are *not* MAYBE_NULL could technically be 18367 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 18368 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 18369 * to the same map). 18370 * However, if the old MAYBE_NULL register then got NULL checked, 18371 * doing so could have affected others with the same id, and we can't 18372 * check for that because we lost the id when we converted to 18373 * a non-MAYBE_NULL variant. 18374 * So, as a general rule we don't allow mixing MAYBE_NULL and 18375 * non-MAYBE_NULL registers as well. 18376 */ 18377 if (rold->type != rcur->type) 18378 return false; 18379 18380 switch (base_type(rold->type)) { 18381 case SCALAR_VALUE: 18382 if (env->explore_alu_limits) { 18383 /* explore_alu_limits disables tnum_in() and range_within() 18384 * logic and requires everything to be strict 18385 */ 18386 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 18387 check_scalar_ids(rold->id, rcur->id, idmap); 18388 } 18389 if (!rold->precise && exact == NOT_EXACT) 18390 return true; 18391 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST)) 18392 return false; 18393 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off)) 18394 return false; 18395 /* Why check_ids() for scalar registers? 18396 * 18397 * Consider the following BPF code: 18398 * 1: r6 = ... unbound scalar, ID=a ... 18399 * 2: r7 = ... unbound scalar, ID=b ... 18400 * 3: if (r6 > r7) goto +1 18401 * 4: r6 = r7 18402 * 5: if (r6 > X) goto ... 18403 * 6: ... memory operation using r7 ... 18404 * 18405 * First verification path is [1-6]: 18406 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 18407 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark 18408 * r7 <= X, because r6 and r7 share same id. 18409 * Next verification path is [1-4, 6]. 18410 * 18411 * Instruction (6) would be reached in two states: 18412 * I. r6{.id=b}, r7{.id=b} via path 1-6; 18413 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 18414 * 18415 * Use check_ids() to distinguish these states. 18416 * --- 18417 * Also verify that new value satisfies old value range knowledge. 18418 */ 18419 return range_within(rold, rcur) && 18420 tnum_in(rold->var_off, rcur->var_off) && 18421 check_scalar_ids(rold->id, rcur->id, idmap); 18422 case PTR_TO_MAP_KEY: 18423 case PTR_TO_MAP_VALUE: 18424 case PTR_TO_MEM: 18425 case PTR_TO_BUF: 18426 case PTR_TO_TP_BUFFER: 18427 /* If the new min/max/var_off satisfy the old ones and 18428 * everything else matches, we are OK. 18429 */ 18430 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 18431 range_within(rold, rcur) && 18432 tnum_in(rold->var_off, rcur->var_off) && 18433 check_ids(rold->id, rcur->id, idmap) && 18434 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 18435 case PTR_TO_PACKET_META: 18436 case PTR_TO_PACKET: 18437 /* We must have at least as much range as the old ptr 18438 * did, so that any accesses which were safe before are 18439 * still safe. This is true even if old range < old off, 18440 * since someone could have accessed through (ptr - k), or 18441 * even done ptr -= k in a register, to get a safe access. 18442 */ 18443 if (rold->range > rcur->range) 18444 return false; 18445 /* If the offsets don't match, we can't trust our alignment; 18446 * nor can we be sure that we won't fall out of range. 18447 */ 18448 if (rold->off != rcur->off) 18449 return false; 18450 /* id relations must be preserved */ 18451 if (!check_ids(rold->id, rcur->id, idmap)) 18452 return false; 18453 /* new val must satisfy old val knowledge */ 18454 return range_within(rold, rcur) && 18455 tnum_in(rold->var_off, rcur->var_off); 18456 case PTR_TO_STACK: 18457 /* two stack pointers are equal only if they're pointing to 18458 * the same stack frame, since fp-8 in foo != fp-8 in bar 18459 */ 18460 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 18461 case PTR_TO_ARENA: 18462 return true; 18463 default: 18464 return regs_exact(rold, rcur, idmap); 18465 } 18466 } 18467 18468 static struct bpf_reg_state unbound_reg; 18469 18470 static __init int unbound_reg_init(void) 18471 { 18472 __mark_reg_unknown_imprecise(&unbound_reg); 18473 unbound_reg.live |= REG_LIVE_READ; 18474 return 0; 18475 } 18476 late_initcall(unbound_reg_init); 18477 18478 static bool is_stack_all_misc(struct bpf_verifier_env *env, 18479 struct bpf_stack_state *stack) 18480 { 18481 u32 i; 18482 18483 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 18484 if ((stack->slot_type[i] == STACK_MISC) || 18485 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 18486 continue; 18487 return false; 18488 } 18489 18490 return true; 18491 } 18492 18493 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 18494 struct bpf_stack_state *stack) 18495 { 18496 if (is_spilled_scalar_reg64(stack)) 18497 return &stack->spilled_ptr; 18498 18499 if (is_stack_all_misc(env, stack)) 18500 return &unbound_reg; 18501 18502 return NULL; 18503 } 18504 18505 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 18506 struct bpf_func_state *cur, struct bpf_idmap *idmap, 18507 enum exact_level exact) 18508 { 18509 int i, spi; 18510 18511 /* walk slots of the explored stack and ignore any additional 18512 * slots in the current stack, since explored(safe) state 18513 * didn't use them 18514 */ 18515 for (i = 0; i < old->allocated_stack; i++) { 18516 struct bpf_reg_state *old_reg, *cur_reg; 18517 18518 spi = i / BPF_REG_SIZE; 18519 18520 if (exact != NOT_EXACT && 18521 (i >= cur->allocated_stack || 18522 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 18523 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 18524 return false; 18525 18526 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 18527 && exact == NOT_EXACT) { 18528 i += BPF_REG_SIZE - 1; 18529 /* explored state didn't use this */ 18530 continue; 18531 } 18532 18533 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 18534 continue; 18535 18536 if (env->allow_uninit_stack && 18537 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 18538 continue; 18539 18540 /* explored stack has more populated slots than current stack 18541 * and these slots were used 18542 */ 18543 if (i >= cur->allocated_stack) 18544 return false; 18545 18546 /* 64-bit scalar spill vs all slots MISC and vice versa. 18547 * Load from all slots MISC produces unbound scalar. 18548 * Construct a fake register for such stack and call 18549 * regsafe() to ensure scalar ids are compared. 18550 */ 18551 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 18552 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 18553 if (old_reg && cur_reg) { 18554 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 18555 return false; 18556 i += BPF_REG_SIZE - 1; 18557 continue; 18558 } 18559 18560 /* if old state was safe with misc data in the stack 18561 * it will be safe with zero-initialized stack. 18562 * The opposite is not true 18563 */ 18564 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 18565 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 18566 continue; 18567 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 18568 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 18569 /* Ex: old explored (safe) state has STACK_SPILL in 18570 * this stack slot, but current has STACK_MISC -> 18571 * this verifier states are not equivalent, 18572 * return false to continue verification of this path 18573 */ 18574 return false; 18575 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 18576 continue; 18577 /* Both old and cur are having same slot_type */ 18578 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 18579 case STACK_SPILL: 18580 /* when explored and current stack slot are both storing 18581 * spilled registers, check that stored pointers types 18582 * are the same as well. 18583 * Ex: explored safe path could have stored 18584 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 18585 * but current path has stored: 18586 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 18587 * such verifier states are not equivalent. 18588 * return false to continue verification of this path 18589 */ 18590 if (!regsafe(env, &old->stack[spi].spilled_ptr, 18591 &cur->stack[spi].spilled_ptr, idmap, exact)) 18592 return false; 18593 break; 18594 case STACK_DYNPTR: 18595 old_reg = &old->stack[spi].spilled_ptr; 18596 cur_reg = &cur->stack[spi].spilled_ptr; 18597 if (old_reg->dynptr.type != cur_reg->dynptr.type || 18598 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 18599 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 18600 return false; 18601 break; 18602 case STACK_ITER: 18603 old_reg = &old->stack[spi].spilled_ptr; 18604 cur_reg = &cur->stack[spi].spilled_ptr; 18605 /* iter.depth is not compared between states as it 18606 * doesn't matter for correctness and would otherwise 18607 * prevent convergence; we maintain it only to prevent 18608 * infinite loop check triggering, see 18609 * iter_active_depths_differ() 18610 */ 18611 if (old_reg->iter.btf != cur_reg->iter.btf || 18612 old_reg->iter.btf_id != cur_reg->iter.btf_id || 18613 old_reg->iter.state != cur_reg->iter.state || 18614 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 18615 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 18616 return false; 18617 break; 18618 case STACK_IRQ_FLAG: 18619 old_reg = &old->stack[spi].spilled_ptr; 18620 cur_reg = &cur->stack[spi].spilled_ptr; 18621 if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) || 18622 old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class) 18623 return false; 18624 break; 18625 case STACK_MISC: 18626 case STACK_ZERO: 18627 case STACK_INVALID: 18628 continue; 18629 /* Ensure that new unhandled slot types return false by default */ 18630 default: 18631 return false; 18632 } 18633 } 18634 return true; 18635 } 18636 18637 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur, 18638 struct bpf_idmap *idmap) 18639 { 18640 int i; 18641 18642 if (old->acquired_refs != cur->acquired_refs) 18643 return false; 18644 18645 if (old->active_locks != cur->active_locks) 18646 return false; 18647 18648 if (old->active_preempt_locks != cur->active_preempt_locks) 18649 return false; 18650 18651 if (old->active_rcu_lock != cur->active_rcu_lock) 18652 return false; 18653 18654 if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap)) 18655 return false; 18656 18657 if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) || 18658 old->active_lock_ptr != cur->active_lock_ptr) 18659 return false; 18660 18661 for (i = 0; i < old->acquired_refs; i++) { 18662 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) || 18663 old->refs[i].type != cur->refs[i].type) 18664 return false; 18665 switch (old->refs[i].type) { 18666 case REF_TYPE_PTR: 18667 case REF_TYPE_IRQ: 18668 break; 18669 case REF_TYPE_LOCK: 18670 case REF_TYPE_RES_LOCK: 18671 case REF_TYPE_RES_LOCK_IRQ: 18672 if (old->refs[i].ptr != cur->refs[i].ptr) 18673 return false; 18674 break; 18675 default: 18676 WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type); 18677 return false; 18678 } 18679 } 18680 18681 return true; 18682 } 18683 18684 /* compare two verifier states 18685 * 18686 * all states stored in state_list are known to be valid, since 18687 * verifier reached 'bpf_exit' instruction through them 18688 * 18689 * this function is called when verifier exploring different branches of 18690 * execution popped from the state stack. If it sees an old state that has 18691 * more strict register state and more strict stack state then this execution 18692 * branch doesn't need to be explored further, since verifier already 18693 * concluded that more strict state leads to valid finish. 18694 * 18695 * Therefore two states are equivalent if register state is more conservative 18696 * and explored stack state is more conservative than the current one. 18697 * Example: 18698 * explored current 18699 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 18700 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 18701 * 18702 * In other words if current stack state (one being explored) has more 18703 * valid slots than old one that already passed validation, it means 18704 * the verifier can stop exploring and conclude that current state is valid too 18705 * 18706 * Similarly with registers. If explored state has register type as invalid 18707 * whereas register type in current state is meaningful, it means that 18708 * the current state will reach 'bpf_exit' instruction safely 18709 */ 18710 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 18711 struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact) 18712 { 18713 u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before; 18714 u16 i; 18715 18716 if (old->callback_depth > cur->callback_depth) 18717 return false; 18718 18719 for (i = 0; i < MAX_BPF_REG; i++) 18720 if (((1 << i) & live_regs) && 18721 !regsafe(env, &old->regs[i], &cur->regs[i], 18722 &env->idmap_scratch, exact)) 18723 return false; 18724 18725 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 18726 return false; 18727 18728 return true; 18729 } 18730 18731 static void reset_idmap_scratch(struct bpf_verifier_env *env) 18732 { 18733 env->idmap_scratch.tmp_id_gen = env->id_gen; 18734 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 18735 } 18736 18737 static bool states_equal(struct bpf_verifier_env *env, 18738 struct bpf_verifier_state *old, 18739 struct bpf_verifier_state *cur, 18740 enum exact_level exact) 18741 { 18742 u32 insn_idx; 18743 int i; 18744 18745 if (old->curframe != cur->curframe) 18746 return false; 18747 18748 reset_idmap_scratch(env); 18749 18750 /* Verification state from speculative execution simulation 18751 * must never prune a non-speculative execution one. 18752 */ 18753 if (old->speculative && !cur->speculative) 18754 return false; 18755 18756 if (old->in_sleepable != cur->in_sleepable) 18757 return false; 18758 18759 if (!refsafe(old, cur, &env->idmap_scratch)) 18760 return false; 18761 18762 /* for states to be equal callsites have to be the same 18763 * and all frame states need to be equivalent 18764 */ 18765 for (i = 0; i <= old->curframe; i++) { 18766 insn_idx = i == old->curframe 18767 ? env->insn_idx 18768 : old->frame[i + 1]->callsite; 18769 if (old->frame[i]->callsite != cur->frame[i]->callsite) 18770 return false; 18771 if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact)) 18772 return false; 18773 } 18774 return true; 18775 } 18776 18777 /* Return 0 if no propagation happened. Return negative error code if error 18778 * happened. Otherwise, return the propagated bit. 18779 */ 18780 static int propagate_liveness_reg(struct bpf_verifier_env *env, 18781 struct bpf_reg_state *reg, 18782 struct bpf_reg_state *parent_reg) 18783 { 18784 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 18785 u8 flag = reg->live & REG_LIVE_READ; 18786 int err; 18787 18788 /* When comes here, read flags of PARENT_REG or REG could be any of 18789 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 18790 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 18791 */ 18792 if (parent_flag == REG_LIVE_READ64 || 18793 /* Or if there is no read flag from REG. */ 18794 !flag || 18795 /* Or if the read flag from REG is the same as PARENT_REG. */ 18796 parent_flag == flag) 18797 return 0; 18798 18799 err = mark_reg_read(env, reg, parent_reg, flag); 18800 if (err) 18801 return err; 18802 18803 return flag; 18804 } 18805 18806 /* A write screens off any subsequent reads; but write marks come from the 18807 * straight-line code between a state and its parent. When we arrive at an 18808 * equivalent state (jump target or such) we didn't arrive by the straight-line 18809 * code, so read marks in the state must propagate to the parent regardless 18810 * of the state's write marks. That's what 'parent == state->parent' comparison 18811 * in mark_reg_read() is for. 18812 */ 18813 static int propagate_liveness(struct bpf_verifier_env *env, 18814 const struct bpf_verifier_state *vstate, 18815 struct bpf_verifier_state *vparent) 18816 { 18817 struct bpf_reg_state *state_reg, *parent_reg; 18818 struct bpf_func_state *state, *parent; 18819 int i, frame, err = 0; 18820 18821 if (vparent->curframe != vstate->curframe) { 18822 WARN(1, "propagate_live: parent frame %d current frame %d\n", 18823 vparent->curframe, vstate->curframe); 18824 return -EFAULT; 18825 } 18826 /* Propagate read liveness of registers... */ 18827 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 18828 for (frame = 0; frame <= vstate->curframe; frame++) { 18829 parent = vparent->frame[frame]; 18830 state = vstate->frame[frame]; 18831 parent_reg = parent->regs; 18832 state_reg = state->regs; 18833 /* We don't need to worry about FP liveness, it's read-only */ 18834 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 18835 err = propagate_liveness_reg(env, &state_reg[i], 18836 &parent_reg[i]); 18837 if (err < 0) 18838 return err; 18839 if (err == REG_LIVE_READ64) 18840 mark_insn_zext(env, &parent_reg[i]); 18841 } 18842 18843 /* Propagate stack slots. */ 18844 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 18845 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 18846 parent_reg = &parent->stack[i].spilled_ptr; 18847 state_reg = &state->stack[i].spilled_ptr; 18848 err = propagate_liveness_reg(env, state_reg, 18849 parent_reg); 18850 if (err < 0) 18851 return err; 18852 } 18853 } 18854 return 0; 18855 } 18856 18857 /* find precise scalars in the previous equivalent state and 18858 * propagate them into the current state 18859 */ 18860 static int propagate_precision(struct bpf_verifier_env *env, 18861 const struct bpf_verifier_state *old) 18862 { 18863 struct bpf_reg_state *state_reg; 18864 struct bpf_func_state *state; 18865 int i, err = 0, fr; 18866 bool first; 18867 18868 for (fr = old->curframe; fr >= 0; fr--) { 18869 state = old->frame[fr]; 18870 state_reg = state->regs; 18871 first = true; 18872 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 18873 if (state_reg->type != SCALAR_VALUE || 18874 !state_reg->precise || 18875 !(state_reg->live & REG_LIVE_READ)) 18876 continue; 18877 if (env->log.level & BPF_LOG_LEVEL2) { 18878 if (first) 18879 verbose(env, "frame %d: propagating r%d", fr, i); 18880 else 18881 verbose(env, ",r%d", i); 18882 } 18883 bt_set_frame_reg(&env->bt, fr, i); 18884 first = false; 18885 } 18886 18887 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 18888 if (!is_spilled_reg(&state->stack[i])) 18889 continue; 18890 state_reg = &state->stack[i].spilled_ptr; 18891 if (state_reg->type != SCALAR_VALUE || 18892 !state_reg->precise || 18893 !(state_reg->live & REG_LIVE_READ)) 18894 continue; 18895 if (env->log.level & BPF_LOG_LEVEL2) { 18896 if (first) 18897 verbose(env, "frame %d: propagating fp%d", 18898 fr, (-i - 1) * BPF_REG_SIZE); 18899 else 18900 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 18901 } 18902 bt_set_frame_slot(&env->bt, fr, i); 18903 first = false; 18904 } 18905 if (!first) 18906 verbose(env, "\n"); 18907 } 18908 18909 err = mark_chain_precision_batch(env); 18910 if (err < 0) 18911 return err; 18912 18913 return 0; 18914 } 18915 18916 static bool states_maybe_looping(struct bpf_verifier_state *old, 18917 struct bpf_verifier_state *cur) 18918 { 18919 struct bpf_func_state *fold, *fcur; 18920 int i, fr = cur->curframe; 18921 18922 if (old->curframe != fr) 18923 return false; 18924 18925 fold = old->frame[fr]; 18926 fcur = cur->frame[fr]; 18927 for (i = 0; i < MAX_BPF_REG; i++) 18928 if (memcmp(&fold->regs[i], &fcur->regs[i], 18929 offsetof(struct bpf_reg_state, parent))) 18930 return false; 18931 return true; 18932 } 18933 18934 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 18935 { 18936 return env->insn_aux_data[insn_idx].is_iter_next; 18937 } 18938 18939 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 18940 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 18941 * states to match, which otherwise would look like an infinite loop. So while 18942 * iter_next() calls are taken care of, we still need to be careful and 18943 * prevent erroneous and too eager declaration of "ininite loop", when 18944 * iterators are involved. 18945 * 18946 * Here's a situation in pseudo-BPF assembly form: 18947 * 18948 * 0: again: ; set up iter_next() call args 18949 * 1: r1 = &it ; <CHECKPOINT HERE> 18950 * 2: call bpf_iter_num_next ; this is iter_next() call 18951 * 3: if r0 == 0 goto done 18952 * 4: ... something useful here ... 18953 * 5: goto again ; another iteration 18954 * 6: done: 18955 * 7: r1 = &it 18956 * 8: call bpf_iter_num_destroy ; clean up iter state 18957 * 9: exit 18958 * 18959 * This is a typical loop. Let's assume that we have a prune point at 1:, 18960 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 18961 * again`, assuming other heuristics don't get in a way). 18962 * 18963 * When we first time come to 1:, let's say we have some state X. We proceed 18964 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 18965 * Now we come back to validate that forked ACTIVE state. We proceed through 18966 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 18967 * are converging. But the problem is that we don't know that yet, as this 18968 * convergence has to happen at iter_next() call site only. So if nothing is 18969 * done, at 1: verifier will use bounded loop logic and declare infinite 18970 * looping (and would be *technically* correct, if not for iterator's 18971 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 18972 * don't want that. So what we do in process_iter_next_call() when we go on 18973 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 18974 * a different iteration. So when we suspect an infinite loop, we additionally 18975 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 18976 * pretend we are not looping and wait for next iter_next() call. 18977 * 18978 * This only applies to ACTIVE state. In DRAINED state we don't expect to 18979 * loop, because that would actually mean infinite loop, as DRAINED state is 18980 * "sticky", and so we'll keep returning into the same instruction with the 18981 * same state (at least in one of possible code paths). 18982 * 18983 * This approach allows to keep infinite loop heuristic even in the face of 18984 * active iterator. E.g., C snippet below is and will be detected as 18985 * inifintely looping: 18986 * 18987 * struct bpf_iter_num it; 18988 * int *p, x; 18989 * 18990 * bpf_iter_num_new(&it, 0, 10); 18991 * while ((p = bpf_iter_num_next(&t))) { 18992 * x = p; 18993 * while (x--) {} // <<-- infinite loop here 18994 * } 18995 * 18996 */ 18997 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 18998 { 18999 struct bpf_reg_state *slot, *cur_slot; 19000 struct bpf_func_state *state; 19001 int i, fr; 19002 19003 for (fr = old->curframe; fr >= 0; fr--) { 19004 state = old->frame[fr]; 19005 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 19006 if (state->stack[i].slot_type[0] != STACK_ITER) 19007 continue; 19008 19009 slot = &state->stack[i].spilled_ptr; 19010 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 19011 continue; 19012 19013 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 19014 if (cur_slot->iter.depth != slot->iter.depth) 19015 return true; 19016 } 19017 } 19018 return false; 19019 } 19020 19021 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 19022 { 19023 struct bpf_verifier_state_list *new_sl; 19024 struct bpf_verifier_state_list *sl; 19025 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 19026 int i, j, n, err, states_cnt = 0; 19027 bool force_new_state, add_new_state, force_exact; 19028 struct list_head *pos, *tmp, *head; 19029 19030 force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) || 19031 /* Avoid accumulating infinitely long jmp history */ 19032 cur->insn_hist_end - cur->insn_hist_start > 40; 19033 19034 /* bpf progs typically have pruning point every 4 instructions 19035 * http://vger.kernel.org/bpfconf2019.html#session-1 19036 * Do not add new state for future pruning if the verifier hasn't seen 19037 * at least 2 jumps and at least 8 instructions. 19038 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 19039 * In tests that amounts to up to 50% reduction into total verifier 19040 * memory consumption and 20% verifier time speedup. 19041 */ 19042 add_new_state = force_new_state; 19043 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 19044 env->insn_processed - env->prev_insn_processed >= 8) 19045 add_new_state = true; 19046 19047 clean_live_states(env, insn_idx, cur); 19048 19049 head = explored_state(env, insn_idx); 19050 list_for_each_safe(pos, tmp, head) { 19051 sl = container_of(pos, struct bpf_verifier_state_list, node); 19052 states_cnt++; 19053 if (sl->state.insn_idx != insn_idx) 19054 continue; 19055 19056 if (sl->state.branches) { 19057 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 19058 19059 if (frame->in_async_callback_fn && 19060 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 19061 /* Different async_entry_cnt means that the verifier is 19062 * processing another entry into async callback. 19063 * Seeing the same state is not an indication of infinite 19064 * loop or infinite recursion. 19065 * But finding the same state doesn't mean that it's safe 19066 * to stop processing the current state. The previous state 19067 * hasn't yet reached bpf_exit, since state.branches > 0. 19068 * Checking in_async_callback_fn alone is not enough either. 19069 * Since the verifier still needs to catch infinite loops 19070 * inside async callbacks. 19071 */ 19072 goto skip_inf_loop_check; 19073 } 19074 /* BPF open-coded iterators loop detection is special. 19075 * states_maybe_looping() logic is too simplistic in detecting 19076 * states that *might* be equivalent, because it doesn't know 19077 * about ID remapping, so don't even perform it. 19078 * See process_iter_next_call() and iter_active_depths_differ() 19079 * for overview of the logic. When current and one of parent 19080 * states are detected as equivalent, it's a good thing: we prove 19081 * convergence and can stop simulating further iterations. 19082 * It's safe to assume that iterator loop will finish, taking into 19083 * account iter_next() contract of eventually returning 19084 * sticky NULL result. 19085 * 19086 * Note, that states have to be compared exactly in this case because 19087 * read and precision marks might not be finalized inside the loop. 19088 * E.g. as in the program below: 19089 * 19090 * 1. r7 = -16 19091 * 2. r6 = bpf_get_prandom_u32() 19092 * 3. while (bpf_iter_num_next(&fp[-8])) { 19093 * 4. if (r6 != 42) { 19094 * 5. r7 = -32 19095 * 6. r6 = bpf_get_prandom_u32() 19096 * 7. continue 19097 * 8. } 19098 * 9. r0 = r10 19099 * 10. r0 += r7 19100 * 11. r8 = *(u64 *)(r0 + 0) 19101 * 12. r6 = bpf_get_prandom_u32() 19102 * 13. } 19103 * 19104 * Here verifier would first visit path 1-3, create a checkpoint at 3 19105 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 19106 * not have read or precision mark for r7 yet, thus inexact states 19107 * comparison would discard current state with r7=-32 19108 * => unsafe memory access at 11 would not be caught. 19109 */ 19110 if (is_iter_next_insn(env, insn_idx)) { 19111 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 19112 struct bpf_func_state *cur_frame; 19113 struct bpf_reg_state *iter_state, *iter_reg; 19114 int spi; 19115 19116 cur_frame = cur->frame[cur->curframe]; 19117 /* btf_check_iter_kfuncs() enforces that 19118 * iter state pointer is always the first arg 19119 */ 19120 iter_reg = &cur_frame->regs[BPF_REG_1]; 19121 /* current state is valid due to states_equal(), 19122 * so we can assume valid iter and reg state, 19123 * no need for extra (re-)validations 19124 */ 19125 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 19126 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 19127 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 19128 update_loop_entry(env, cur, &sl->state); 19129 goto hit; 19130 } 19131 } 19132 goto skip_inf_loop_check; 19133 } 19134 if (is_may_goto_insn_at(env, insn_idx)) { 19135 if (sl->state.may_goto_depth != cur->may_goto_depth && 19136 states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 19137 update_loop_entry(env, cur, &sl->state); 19138 goto hit; 19139 } 19140 } 19141 if (calls_callback(env, insn_idx)) { 19142 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 19143 goto hit; 19144 goto skip_inf_loop_check; 19145 } 19146 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 19147 if (states_maybe_looping(&sl->state, cur) && 19148 states_equal(env, &sl->state, cur, EXACT) && 19149 !iter_active_depths_differ(&sl->state, cur) && 19150 sl->state.may_goto_depth == cur->may_goto_depth && 19151 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 19152 verbose_linfo(env, insn_idx, "; "); 19153 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 19154 verbose(env, "cur state:"); 19155 print_verifier_state(env, cur, cur->curframe, true); 19156 verbose(env, "old state:"); 19157 print_verifier_state(env, &sl->state, cur->curframe, true); 19158 return -EINVAL; 19159 } 19160 /* if the verifier is processing a loop, avoid adding new state 19161 * too often, since different loop iterations have distinct 19162 * states and may not help future pruning. 19163 * This threshold shouldn't be too low to make sure that 19164 * a loop with large bound will be rejected quickly. 19165 * The most abusive loop will be: 19166 * r1 += 1 19167 * if r1 < 1000000 goto pc-2 19168 * 1M insn_procssed limit / 100 == 10k peak states. 19169 * This threshold shouldn't be too high either, since states 19170 * at the end of the loop are likely to be useful in pruning. 19171 */ 19172 skip_inf_loop_check: 19173 if (!force_new_state && 19174 env->jmps_processed - env->prev_jmps_processed < 20 && 19175 env->insn_processed - env->prev_insn_processed < 100) 19176 add_new_state = false; 19177 goto miss; 19178 } 19179 /* If sl->state is a part of a loop and this loop's entry is a part of 19180 * current verification path then states have to be compared exactly. 19181 * 'force_exact' is needed to catch the following case: 19182 * 19183 * initial Here state 'succ' was processed first, 19184 * | it was eventually tracked to produce a 19185 * V state identical to 'hdr'. 19186 * .---------> hdr All branches from 'succ' had been explored 19187 * | | and thus 'succ' has its .branches == 0. 19188 * | V 19189 * | .------... Suppose states 'cur' and 'succ' correspond 19190 * | | | to the same instruction + callsites. 19191 * | V V In such case it is necessary to check 19192 * | ... ... if 'succ' and 'cur' are states_equal(). 19193 * | | | If 'succ' and 'cur' are a part of the 19194 * | V V same loop exact flag has to be set. 19195 * | succ <- cur To check if that is the case, verify 19196 * | | if loop entry of 'succ' is in current 19197 * | V DFS path. 19198 * | ... 19199 * | | 19200 * '----' 19201 * 19202 * Additional details are in the comment before get_loop_entry(). 19203 */ 19204 loop_entry = get_loop_entry(env, &sl->state); 19205 if (IS_ERR(loop_entry)) 19206 return PTR_ERR(loop_entry); 19207 force_exact = loop_entry && loop_entry->branches > 0; 19208 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) { 19209 if (force_exact) 19210 update_loop_entry(env, cur, loop_entry); 19211 hit: 19212 sl->hit_cnt++; 19213 /* reached equivalent register/stack state, 19214 * prune the search. 19215 * Registers read by the continuation are read by us. 19216 * If we have any write marks in env->cur_state, they 19217 * will prevent corresponding reads in the continuation 19218 * from reaching our parent (an explored_state). Our 19219 * own state will get the read marks recorded, but 19220 * they'll be immediately forgotten as we're pruning 19221 * this state and will pop a new one. 19222 */ 19223 err = propagate_liveness(env, &sl->state, cur); 19224 19225 /* if previous state reached the exit with precision and 19226 * current state is equivalent to it (except precision marks) 19227 * the precision needs to be propagated back in 19228 * the current state. 19229 */ 19230 if (is_jmp_point(env, env->insn_idx)) 19231 err = err ? : push_insn_history(env, cur, 0, 0); 19232 err = err ? : propagate_precision(env, &sl->state); 19233 if (err) 19234 return err; 19235 return 1; 19236 } 19237 miss: 19238 /* when new state is not going to be added do not increase miss count. 19239 * Otherwise several loop iterations will remove the state 19240 * recorded earlier. The goal of these heuristics is to have 19241 * states from some iterations of the loop (some in the beginning 19242 * and some at the end) to help pruning. 19243 */ 19244 if (add_new_state) 19245 sl->miss_cnt++; 19246 /* heuristic to determine whether this state is beneficial 19247 * to keep checking from state equivalence point of view. 19248 * Higher numbers increase max_states_per_insn and verification time, 19249 * but do not meaningfully decrease insn_processed. 19250 * 'n' controls how many times state could miss before eviction. 19251 * Use bigger 'n' for checkpoints because evicting checkpoint states 19252 * too early would hinder iterator convergence. 19253 */ 19254 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 19255 if (sl->miss_cnt > sl->hit_cnt * n + n) { 19256 /* the state is unlikely to be useful. Remove it to 19257 * speed up verification 19258 */ 19259 sl->in_free_list = true; 19260 list_del(&sl->node); 19261 list_add(&sl->node, &env->free_list); 19262 env->free_list_size++; 19263 env->explored_states_size--; 19264 maybe_free_verifier_state(env, sl); 19265 } 19266 } 19267 19268 if (env->max_states_per_insn < states_cnt) 19269 env->max_states_per_insn = states_cnt; 19270 19271 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 19272 return 0; 19273 19274 if (!add_new_state) 19275 return 0; 19276 19277 /* There were no equivalent states, remember the current one. 19278 * Technically the current state is not proven to be safe yet, 19279 * but it will either reach outer most bpf_exit (which means it's safe) 19280 * or it will be rejected. When there are no loops the verifier won't be 19281 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 19282 * again on the way to bpf_exit. 19283 * When looping the sl->state.branches will be > 0 and this state 19284 * will not be considered for equivalence until branches == 0. 19285 */ 19286 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 19287 if (!new_sl) 19288 return -ENOMEM; 19289 env->total_states++; 19290 env->explored_states_size++; 19291 update_peak_states(env); 19292 env->prev_jmps_processed = env->jmps_processed; 19293 env->prev_insn_processed = env->insn_processed; 19294 19295 /* forget precise markings we inherited, see __mark_chain_precision */ 19296 if (env->bpf_capable) 19297 mark_all_scalars_imprecise(env, cur); 19298 19299 /* add new state to the head of linked list */ 19300 new = &new_sl->state; 19301 err = copy_verifier_state(new, cur); 19302 if (err) { 19303 free_verifier_state(new, false); 19304 kfree(new_sl); 19305 return err; 19306 } 19307 new->insn_idx = insn_idx; 19308 WARN_ONCE(new->branches != 1, 19309 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 19310 19311 cur->parent = new; 19312 cur->first_insn_idx = insn_idx; 19313 cur->insn_hist_start = cur->insn_hist_end; 19314 cur->dfs_depth = new->dfs_depth + 1; 19315 list_add(&new_sl->node, head); 19316 19317 /* connect new state to parentage chain. Current frame needs all 19318 * registers connected. Only r6 - r9 of the callers are alive (pushed 19319 * to the stack implicitly by JITs) so in callers' frames connect just 19320 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 19321 * the state of the call instruction (with WRITTEN set), and r0 comes 19322 * from callee with its full parentage chain, anyway. 19323 */ 19324 /* clear write marks in current state: the writes we did are not writes 19325 * our child did, so they don't screen off its reads from us. 19326 * (There are no read marks in current state, because reads always mark 19327 * their parent and current state never has children yet. Only 19328 * explored_states can get read marks.) 19329 */ 19330 for (j = 0; j <= cur->curframe; j++) { 19331 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 19332 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 19333 for (i = 0; i < BPF_REG_FP; i++) 19334 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 19335 } 19336 19337 /* all stack frames are accessible from callee, clear them all */ 19338 for (j = 0; j <= cur->curframe; j++) { 19339 struct bpf_func_state *frame = cur->frame[j]; 19340 struct bpf_func_state *newframe = new->frame[j]; 19341 19342 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 19343 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 19344 frame->stack[i].spilled_ptr.parent = 19345 &newframe->stack[i].spilled_ptr; 19346 } 19347 } 19348 return 0; 19349 } 19350 19351 /* Return true if it's OK to have the same insn return a different type. */ 19352 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 19353 { 19354 switch (base_type(type)) { 19355 case PTR_TO_CTX: 19356 case PTR_TO_SOCKET: 19357 case PTR_TO_SOCK_COMMON: 19358 case PTR_TO_TCP_SOCK: 19359 case PTR_TO_XDP_SOCK: 19360 case PTR_TO_BTF_ID: 19361 case PTR_TO_ARENA: 19362 return false; 19363 default: 19364 return true; 19365 } 19366 } 19367 19368 /* If an instruction was previously used with particular pointer types, then we 19369 * need to be careful to avoid cases such as the below, where it may be ok 19370 * for one branch accessing the pointer, but not ok for the other branch: 19371 * 19372 * R1 = sock_ptr 19373 * goto X; 19374 * ... 19375 * R1 = some_other_valid_ptr; 19376 * goto X; 19377 * ... 19378 * R2 = *(u32 *)(R1 + 0); 19379 */ 19380 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 19381 { 19382 return src != prev && (!reg_type_mismatch_ok(src) || 19383 !reg_type_mismatch_ok(prev)); 19384 } 19385 19386 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 19387 bool allow_trust_mismatch) 19388 { 19389 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 19390 19391 if (*prev_type == NOT_INIT) { 19392 /* Saw a valid insn 19393 * dst_reg = *(u32 *)(src_reg + off) 19394 * save type to validate intersecting paths 19395 */ 19396 *prev_type = type; 19397 } else if (reg_type_mismatch(type, *prev_type)) { 19398 /* Abuser program is trying to use the same insn 19399 * dst_reg = *(u32*) (src_reg + off) 19400 * with different pointer types: 19401 * src_reg == ctx in one branch and 19402 * src_reg == stack|map in some other branch. 19403 * Reject it. 19404 */ 19405 if (allow_trust_mismatch && 19406 base_type(type) == PTR_TO_BTF_ID && 19407 base_type(*prev_type) == PTR_TO_BTF_ID) { 19408 /* 19409 * Have to support a use case when one path through 19410 * the program yields TRUSTED pointer while another 19411 * is UNTRUSTED. Fallback to UNTRUSTED to generate 19412 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 19413 */ 19414 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 19415 } else { 19416 verbose(env, "same insn cannot be used with different pointers\n"); 19417 return -EINVAL; 19418 } 19419 } 19420 19421 return 0; 19422 } 19423 19424 static int do_check(struct bpf_verifier_env *env) 19425 { 19426 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19427 struct bpf_verifier_state *state = env->cur_state; 19428 struct bpf_insn *insns = env->prog->insnsi; 19429 struct bpf_reg_state *regs; 19430 int insn_cnt = env->prog->len; 19431 bool do_print_state = false; 19432 int prev_insn_idx = -1; 19433 19434 for (;;) { 19435 bool exception_exit = false; 19436 struct bpf_insn *insn; 19437 u8 class; 19438 int err; 19439 19440 /* reset current history entry on each new instruction */ 19441 env->cur_hist_ent = NULL; 19442 19443 env->prev_insn_idx = prev_insn_idx; 19444 if (env->insn_idx >= insn_cnt) { 19445 verbose(env, "invalid insn idx %d insn_cnt %d\n", 19446 env->insn_idx, insn_cnt); 19447 return -EFAULT; 19448 } 19449 19450 insn = &insns[env->insn_idx]; 19451 class = BPF_CLASS(insn->code); 19452 19453 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 19454 verbose(env, 19455 "BPF program is too large. Processed %d insn\n", 19456 env->insn_processed); 19457 return -E2BIG; 19458 } 19459 19460 state->last_insn_idx = env->prev_insn_idx; 19461 19462 if (is_prune_point(env, env->insn_idx)) { 19463 err = is_state_visited(env, env->insn_idx); 19464 if (err < 0) 19465 return err; 19466 if (err == 1) { 19467 /* found equivalent state, can prune the search */ 19468 if (env->log.level & BPF_LOG_LEVEL) { 19469 if (do_print_state) 19470 verbose(env, "\nfrom %d to %d%s: safe\n", 19471 env->prev_insn_idx, env->insn_idx, 19472 env->cur_state->speculative ? 19473 " (speculative execution)" : ""); 19474 else 19475 verbose(env, "%d: safe\n", env->insn_idx); 19476 } 19477 goto process_bpf_exit; 19478 } 19479 } 19480 19481 if (is_jmp_point(env, env->insn_idx)) { 19482 err = push_insn_history(env, state, 0, 0); 19483 if (err) 19484 return err; 19485 } 19486 19487 if (signal_pending(current)) 19488 return -EAGAIN; 19489 19490 if (need_resched()) 19491 cond_resched(); 19492 19493 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 19494 verbose(env, "\nfrom %d to %d%s:", 19495 env->prev_insn_idx, env->insn_idx, 19496 env->cur_state->speculative ? 19497 " (speculative execution)" : ""); 19498 print_verifier_state(env, state, state->curframe, true); 19499 do_print_state = false; 19500 } 19501 19502 if (env->log.level & BPF_LOG_LEVEL) { 19503 if (verifier_state_scratched(env)) 19504 print_insn_state(env, state, state->curframe); 19505 19506 verbose_linfo(env, env->insn_idx, "; "); 19507 env->prev_log_pos = env->log.end_pos; 19508 verbose(env, "%d: ", env->insn_idx); 19509 verbose_insn(env, insn); 19510 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 19511 env->prev_log_pos = env->log.end_pos; 19512 } 19513 19514 if (bpf_prog_is_offloaded(env->prog->aux)) { 19515 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 19516 env->prev_insn_idx); 19517 if (err) 19518 return err; 19519 } 19520 19521 regs = cur_regs(env); 19522 sanitize_mark_insn_seen(env); 19523 prev_insn_idx = env->insn_idx; 19524 19525 if (class == BPF_ALU || class == BPF_ALU64) { 19526 err = check_alu_op(env, insn); 19527 if (err) 19528 return err; 19529 19530 } else if (class == BPF_LDX) { 19531 bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX; 19532 19533 /* Check for reserved fields is already done in 19534 * resolve_pseudo_ldimm64(). 19535 */ 19536 err = check_load_mem(env, insn, false, is_ldsx, true, 19537 "ldx"); 19538 if (err) 19539 return err; 19540 } else if (class == BPF_STX) { 19541 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 19542 err = check_atomic(env, insn); 19543 if (err) 19544 return err; 19545 env->insn_idx++; 19546 continue; 19547 } 19548 19549 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 19550 verbose(env, "BPF_STX uses reserved fields\n"); 19551 return -EINVAL; 19552 } 19553 19554 err = check_store_reg(env, insn, false); 19555 if (err) 19556 return err; 19557 } else if (class == BPF_ST) { 19558 enum bpf_reg_type dst_reg_type; 19559 19560 if (BPF_MODE(insn->code) != BPF_MEM || 19561 insn->src_reg != BPF_REG_0) { 19562 verbose(env, "BPF_ST uses reserved fields\n"); 19563 return -EINVAL; 19564 } 19565 /* check src operand */ 19566 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 19567 if (err) 19568 return err; 19569 19570 dst_reg_type = regs[insn->dst_reg].type; 19571 19572 /* check that memory (dst_reg + off) is writeable */ 19573 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 19574 insn->off, BPF_SIZE(insn->code), 19575 BPF_WRITE, -1, false, false); 19576 if (err) 19577 return err; 19578 19579 err = save_aux_ptr_type(env, dst_reg_type, false); 19580 if (err) 19581 return err; 19582 } else if (class == BPF_JMP || class == BPF_JMP32) { 19583 u8 opcode = BPF_OP(insn->code); 19584 19585 env->jmps_processed++; 19586 if (opcode == BPF_CALL) { 19587 if (BPF_SRC(insn->code) != BPF_K || 19588 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 19589 && insn->off != 0) || 19590 (insn->src_reg != BPF_REG_0 && 19591 insn->src_reg != BPF_PSEUDO_CALL && 19592 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 19593 insn->dst_reg != BPF_REG_0 || 19594 class == BPF_JMP32) { 19595 verbose(env, "BPF_CALL uses reserved fields\n"); 19596 return -EINVAL; 19597 } 19598 19599 if (env->cur_state->active_locks) { 19600 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 19601 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 19602 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) { 19603 verbose(env, "function calls are not allowed while holding a lock\n"); 19604 return -EINVAL; 19605 } 19606 } 19607 if (insn->src_reg == BPF_PSEUDO_CALL) { 19608 err = check_func_call(env, insn, &env->insn_idx); 19609 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19610 err = check_kfunc_call(env, insn, &env->insn_idx); 19611 if (!err && is_bpf_throw_kfunc(insn)) { 19612 exception_exit = true; 19613 goto process_bpf_exit_full; 19614 } 19615 } else { 19616 err = check_helper_call(env, insn, &env->insn_idx); 19617 } 19618 if (err) 19619 return err; 19620 19621 mark_reg_scratched(env, BPF_REG_0); 19622 } else if (opcode == BPF_JA) { 19623 if (BPF_SRC(insn->code) != BPF_K || 19624 insn->src_reg != BPF_REG_0 || 19625 insn->dst_reg != BPF_REG_0 || 19626 (class == BPF_JMP && insn->imm != 0) || 19627 (class == BPF_JMP32 && insn->off != 0)) { 19628 verbose(env, "BPF_JA uses reserved fields\n"); 19629 return -EINVAL; 19630 } 19631 19632 if (class == BPF_JMP) 19633 env->insn_idx += insn->off + 1; 19634 else 19635 env->insn_idx += insn->imm + 1; 19636 continue; 19637 19638 } else if (opcode == BPF_EXIT) { 19639 if (BPF_SRC(insn->code) != BPF_K || 19640 insn->imm != 0 || 19641 insn->src_reg != BPF_REG_0 || 19642 insn->dst_reg != BPF_REG_0 || 19643 class == BPF_JMP32) { 19644 verbose(env, "BPF_EXIT uses reserved fields\n"); 19645 return -EINVAL; 19646 } 19647 process_bpf_exit_full: 19648 /* We must do check_reference_leak here before 19649 * prepare_func_exit to handle the case when 19650 * state->curframe > 0, it may be a callback 19651 * function, for which reference_state must 19652 * match caller reference state when it exits. 19653 */ 19654 err = check_resource_leak(env, exception_exit, !env->cur_state->curframe, 19655 "BPF_EXIT instruction in main prog"); 19656 if (err) 19657 return err; 19658 19659 /* The side effect of the prepare_func_exit 19660 * which is being skipped is that it frees 19661 * bpf_func_state. Typically, process_bpf_exit 19662 * will only be hit with outermost exit. 19663 * copy_verifier_state in pop_stack will handle 19664 * freeing of any extra bpf_func_state left over 19665 * from not processing all nested function 19666 * exits. We also skip return code checks as 19667 * they are not needed for exceptional exits. 19668 */ 19669 if (exception_exit) 19670 goto process_bpf_exit; 19671 19672 if (state->curframe) { 19673 /* exit from nested function */ 19674 err = prepare_func_exit(env, &env->insn_idx); 19675 if (err) 19676 return err; 19677 do_print_state = true; 19678 continue; 19679 } 19680 19681 err = check_return_code(env, BPF_REG_0, "R0"); 19682 if (err) 19683 return err; 19684 process_bpf_exit: 19685 mark_verifier_state_scratched(env); 19686 update_branch_counts(env, env->cur_state); 19687 err = pop_stack(env, &prev_insn_idx, 19688 &env->insn_idx, pop_log); 19689 if (err < 0) { 19690 if (err != -ENOENT) 19691 return err; 19692 break; 19693 } else { 19694 if (verifier_bug_if(env->cur_state->loop_entry, env, 19695 "broken loop detection")) 19696 return -EFAULT; 19697 do_print_state = true; 19698 continue; 19699 } 19700 } else { 19701 err = check_cond_jmp_op(env, insn, &env->insn_idx); 19702 if (err) 19703 return err; 19704 } 19705 } else if (class == BPF_LD) { 19706 u8 mode = BPF_MODE(insn->code); 19707 19708 if (mode == BPF_ABS || mode == BPF_IND) { 19709 err = check_ld_abs(env, insn); 19710 if (err) 19711 return err; 19712 19713 } else if (mode == BPF_IMM) { 19714 err = check_ld_imm(env, insn); 19715 if (err) 19716 return err; 19717 19718 env->insn_idx++; 19719 sanitize_mark_insn_seen(env); 19720 } else { 19721 verbose(env, "invalid BPF_LD mode\n"); 19722 return -EINVAL; 19723 } 19724 } else { 19725 verbose(env, "unknown insn class %d\n", class); 19726 return -EINVAL; 19727 } 19728 19729 env->insn_idx++; 19730 } 19731 19732 return 0; 19733 } 19734 19735 static int find_btf_percpu_datasec(struct btf *btf) 19736 { 19737 const struct btf_type *t; 19738 const char *tname; 19739 int i, n; 19740 19741 /* 19742 * Both vmlinux and module each have their own ".data..percpu" 19743 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 19744 * types to look at only module's own BTF types. 19745 */ 19746 n = btf_nr_types(btf); 19747 if (btf_is_module(btf)) 19748 i = btf_nr_types(btf_vmlinux); 19749 else 19750 i = 1; 19751 19752 for(; i < n; i++) { 19753 t = btf_type_by_id(btf, i); 19754 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 19755 continue; 19756 19757 tname = btf_name_by_offset(btf, t->name_off); 19758 if (!strcmp(tname, ".data..percpu")) 19759 return i; 19760 } 19761 19762 return -ENOENT; 19763 } 19764 19765 /* 19766 * Add btf to the used_btfs array and return the index. (If the btf was 19767 * already added, then just return the index.) Upon successful insertion 19768 * increase btf refcnt, and, if present, also refcount the corresponding 19769 * kernel module. 19770 */ 19771 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 19772 { 19773 struct btf_mod_pair *btf_mod; 19774 int i; 19775 19776 /* check whether we recorded this BTF (and maybe module) already */ 19777 for (i = 0; i < env->used_btf_cnt; i++) 19778 if (env->used_btfs[i].btf == btf) 19779 return i; 19780 19781 if (env->used_btf_cnt >= MAX_USED_BTFS) 19782 return -E2BIG; 19783 19784 btf_get(btf); 19785 19786 btf_mod = &env->used_btfs[env->used_btf_cnt]; 19787 btf_mod->btf = btf; 19788 btf_mod->module = NULL; 19789 19790 /* if we reference variables from kernel module, bump its refcount */ 19791 if (btf_is_module(btf)) { 19792 btf_mod->module = btf_try_get_module(btf); 19793 if (!btf_mod->module) { 19794 btf_put(btf); 19795 return -ENXIO; 19796 } 19797 } 19798 19799 return env->used_btf_cnt++; 19800 } 19801 19802 /* replace pseudo btf_id with kernel symbol address */ 19803 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 19804 struct bpf_insn *insn, 19805 struct bpf_insn_aux_data *aux, 19806 struct btf *btf) 19807 { 19808 const struct btf_var_secinfo *vsi; 19809 const struct btf_type *datasec; 19810 const struct btf_type *t; 19811 const char *sym_name; 19812 bool percpu = false; 19813 u32 type, id = insn->imm; 19814 s32 datasec_id; 19815 u64 addr; 19816 int i; 19817 19818 t = btf_type_by_id(btf, id); 19819 if (!t) { 19820 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 19821 return -ENOENT; 19822 } 19823 19824 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 19825 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 19826 return -EINVAL; 19827 } 19828 19829 sym_name = btf_name_by_offset(btf, t->name_off); 19830 addr = kallsyms_lookup_name(sym_name); 19831 if (!addr) { 19832 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 19833 sym_name); 19834 return -ENOENT; 19835 } 19836 insn[0].imm = (u32)addr; 19837 insn[1].imm = addr >> 32; 19838 19839 if (btf_type_is_func(t)) { 19840 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 19841 aux->btf_var.mem_size = 0; 19842 return 0; 19843 } 19844 19845 datasec_id = find_btf_percpu_datasec(btf); 19846 if (datasec_id > 0) { 19847 datasec = btf_type_by_id(btf, datasec_id); 19848 for_each_vsi(i, datasec, vsi) { 19849 if (vsi->type == id) { 19850 percpu = true; 19851 break; 19852 } 19853 } 19854 } 19855 19856 type = t->type; 19857 t = btf_type_skip_modifiers(btf, type, NULL); 19858 if (percpu) { 19859 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 19860 aux->btf_var.btf = btf; 19861 aux->btf_var.btf_id = type; 19862 } else if (!btf_type_is_struct(t)) { 19863 const struct btf_type *ret; 19864 const char *tname; 19865 u32 tsize; 19866 19867 /* resolve the type size of ksym. */ 19868 ret = btf_resolve_size(btf, t, &tsize); 19869 if (IS_ERR(ret)) { 19870 tname = btf_name_by_offset(btf, t->name_off); 19871 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 19872 tname, PTR_ERR(ret)); 19873 return -EINVAL; 19874 } 19875 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 19876 aux->btf_var.mem_size = tsize; 19877 } else { 19878 aux->btf_var.reg_type = PTR_TO_BTF_ID; 19879 aux->btf_var.btf = btf; 19880 aux->btf_var.btf_id = type; 19881 } 19882 19883 return 0; 19884 } 19885 19886 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 19887 struct bpf_insn *insn, 19888 struct bpf_insn_aux_data *aux) 19889 { 19890 struct btf *btf; 19891 int btf_fd; 19892 int err; 19893 19894 btf_fd = insn[1].imm; 19895 if (btf_fd) { 19896 CLASS(fd, f)(btf_fd); 19897 19898 btf = __btf_get_by_fd(f); 19899 if (IS_ERR(btf)) { 19900 verbose(env, "invalid module BTF object FD specified.\n"); 19901 return -EINVAL; 19902 } 19903 } else { 19904 if (!btf_vmlinux) { 19905 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 19906 return -EINVAL; 19907 } 19908 btf = btf_vmlinux; 19909 } 19910 19911 err = __check_pseudo_btf_id(env, insn, aux, btf); 19912 if (err) 19913 return err; 19914 19915 err = __add_used_btf(env, btf); 19916 if (err < 0) 19917 return err; 19918 return 0; 19919 } 19920 19921 static bool is_tracing_prog_type(enum bpf_prog_type type) 19922 { 19923 switch (type) { 19924 case BPF_PROG_TYPE_KPROBE: 19925 case BPF_PROG_TYPE_TRACEPOINT: 19926 case BPF_PROG_TYPE_PERF_EVENT: 19927 case BPF_PROG_TYPE_RAW_TRACEPOINT: 19928 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 19929 return true; 19930 default: 19931 return false; 19932 } 19933 } 19934 19935 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 19936 { 19937 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 19938 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 19939 } 19940 19941 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 19942 struct bpf_map *map, 19943 struct bpf_prog *prog) 19944 19945 { 19946 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19947 19948 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 19949 btf_record_has_field(map->record, BPF_RB_ROOT)) { 19950 if (is_tracing_prog_type(prog_type)) { 19951 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 19952 return -EINVAL; 19953 } 19954 } 19955 19956 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 19957 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 19958 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 19959 return -EINVAL; 19960 } 19961 19962 if (is_tracing_prog_type(prog_type)) { 19963 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 19964 return -EINVAL; 19965 } 19966 } 19967 19968 if (btf_record_has_field(map->record, BPF_TIMER)) { 19969 if (is_tracing_prog_type(prog_type)) { 19970 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 19971 return -EINVAL; 19972 } 19973 } 19974 19975 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) { 19976 if (is_tracing_prog_type(prog_type)) { 19977 verbose(env, "tracing progs cannot use bpf_wq yet\n"); 19978 return -EINVAL; 19979 } 19980 } 19981 19982 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 19983 !bpf_offload_prog_map_match(prog, map)) { 19984 verbose(env, "offload device mismatch between prog and map\n"); 19985 return -EINVAL; 19986 } 19987 19988 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 19989 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 19990 return -EINVAL; 19991 } 19992 19993 if (prog->sleepable) 19994 switch (map->map_type) { 19995 case BPF_MAP_TYPE_HASH: 19996 case BPF_MAP_TYPE_LRU_HASH: 19997 case BPF_MAP_TYPE_ARRAY: 19998 case BPF_MAP_TYPE_PERCPU_HASH: 19999 case BPF_MAP_TYPE_PERCPU_ARRAY: 20000 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 20001 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 20002 case BPF_MAP_TYPE_HASH_OF_MAPS: 20003 case BPF_MAP_TYPE_RINGBUF: 20004 case BPF_MAP_TYPE_USER_RINGBUF: 20005 case BPF_MAP_TYPE_INODE_STORAGE: 20006 case BPF_MAP_TYPE_SK_STORAGE: 20007 case BPF_MAP_TYPE_TASK_STORAGE: 20008 case BPF_MAP_TYPE_CGRP_STORAGE: 20009 case BPF_MAP_TYPE_QUEUE: 20010 case BPF_MAP_TYPE_STACK: 20011 case BPF_MAP_TYPE_ARENA: 20012 break; 20013 default: 20014 verbose(env, 20015 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 20016 return -EINVAL; 20017 } 20018 20019 if (bpf_map_is_cgroup_storage(map) && 20020 bpf_cgroup_storage_assign(env->prog->aux, map)) { 20021 verbose(env, "only one cgroup storage of each type is allowed\n"); 20022 return -EBUSY; 20023 } 20024 20025 if (map->map_type == BPF_MAP_TYPE_ARENA) { 20026 if (env->prog->aux->arena) { 20027 verbose(env, "Only one arena per program\n"); 20028 return -EBUSY; 20029 } 20030 if (!env->allow_ptr_leaks || !env->bpf_capable) { 20031 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 20032 return -EPERM; 20033 } 20034 if (!env->prog->jit_requested) { 20035 verbose(env, "JIT is required to use arena\n"); 20036 return -EOPNOTSUPP; 20037 } 20038 if (!bpf_jit_supports_arena()) { 20039 verbose(env, "JIT doesn't support arena\n"); 20040 return -EOPNOTSUPP; 20041 } 20042 env->prog->aux->arena = (void *)map; 20043 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 20044 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 20045 return -EINVAL; 20046 } 20047 } 20048 20049 return 0; 20050 } 20051 20052 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 20053 { 20054 int i, err; 20055 20056 /* check whether we recorded this map already */ 20057 for (i = 0; i < env->used_map_cnt; i++) 20058 if (env->used_maps[i] == map) 20059 return i; 20060 20061 if (env->used_map_cnt >= MAX_USED_MAPS) { 20062 verbose(env, "The total number of maps per program has reached the limit of %u\n", 20063 MAX_USED_MAPS); 20064 return -E2BIG; 20065 } 20066 20067 err = check_map_prog_compatibility(env, map, env->prog); 20068 if (err) 20069 return err; 20070 20071 if (env->prog->sleepable) 20072 atomic64_inc(&map->sleepable_refcnt); 20073 20074 /* hold the map. If the program is rejected by verifier, 20075 * the map will be released by release_maps() or it 20076 * will be used by the valid program until it's unloaded 20077 * and all maps are released in bpf_free_used_maps() 20078 */ 20079 bpf_map_inc(map); 20080 20081 env->used_maps[env->used_map_cnt++] = map; 20082 20083 return env->used_map_cnt - 1; 20084 } 20085 20086 /* Add map behind fd to used maps list, if it's not already there, and return 20087 * its index. 20088 * Returns <0 on error, or >= 0 index, on success. 20089 */ 20090 static int add_used_map(struct bpf_verifier_env *env, int fd) 20091 { 20092 struct bpf_map *map; 20093 CLASS(fd, f)(fd); 20094 20095 map = __bpf_map_get(f); 20096 if (IS_ERR(map)) { 20097 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 20098 return PTR_ERR(map); 20099 } 20100 20101 return __add_used_map(env, map); 20102 } 20103 20104 /* find and rewrite pseudo imm in ld_imm64 instructions: 20105 * 20106 * 1. if it accesses map FD, replace it with actual map pointer. 20107 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 20108 * 20109 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 20110 */ 20111 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 20112 { 20113 struct bpf_insn *insn = env->prog->insnsi; 20114 int insn_cnt = env->prog->len; 20115 int i, err; 20116 20117 err = bpf_prog_calc_tag(env->prog); 20118 if (err) 20119 return err; 20120 20121 for (i = 0; i < insn_cnt; i++, insn++) { 20122 if (BPF_CLASS(insn->code) == BPF_LDX && 20123 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 20124 insn->imm != 0)) { 20125 verbose(env, "BPF_LDX uses reserved fields\n"); 20126 return -EINVAL; 20127 } 20128 20129 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 20130 struct bpf_insn_aux_data *aux; 20131 struct bpf_map *map; 20132 int map_idx; 20133 u64 addr; 20134 u32 fd; 20135 20136 if (i == insn_cnt - 1 || insn[1].code != 0 || 20137 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 20138 insn[1].off != 0) { 20139 verbose(env, "invalid bpf_ld_imm64 insn\n"); 20140 return -EINVAL; 20141 } 20142 20143 if (insn[0].src_reg == 0) 20144 /* valid generic load 64-bit imm */ 20145 goto next_insn; 20146 20147 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 20148 aux = &env->insn_aux_data[i]; 20149 err = check_pseudo_btf_id(env, insn, aux); 20150 if (err) 20151 return err; 20152 goto next_insn; 20153 } 20154 20155 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 20156 aux = &env->insn_aux_data[i]; 20157 aux->ptr_type = PTR_TO_FUNC; 20158 goto next_insn; 20159 } 20160 20161 /* In final convert_pseudo_ld_imm64() step, this is 20162 * converted into regular 64-bit imm load insn. 20163 */ 20164 switch (insn[0].src_reg) { 20165 case BPF_PSEUDO_MAP_VALUE: 20166 case BPF_PSEUDO_MAP_IDX_VALUE: 20167 break; 20168 case BPF_PSEUDO_MAP_FD: 20169 case BPF_PSEUDO_MAP_IDX: 20170 if (insn[1].imm == 0) 20171 break; 20172 fallthrough; 20173 default: 20174 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 20175 return -EINVAL; 20176 } 20177 20178 switch (insn[0].src_reg) { 20179 case BPF_PSEUDO_MAP_IDX_VALUE: 20180 case BPF_PSEUDO_MAP_IDX: 20181 if (bpfptr_is_null(env->fd_array)) { 20182 verbose(env, "fd_idx without fd_array is invalid\n"); 20183 return -EPROTO; 20184 } 20185 if (copy_from_bpfptr_offset(&fd, env->fd_array, 20186 insn[0].imm * sizeof(fd), 20187 sizeof(fd))) 20188 return -EFAULT; 20189 break; 20190 default: 20191 fd = insn[0].imm; 20192 break; 20193 } 20194 20195 map_idx = add_used_map(env, fd); 20196 if (map_idx < 0) 20197 return map_idx; 20198 map = env->used_maps[map_idx]; 20199 20200 aux = &env->insn_aux_data[i]; 20201 aux->map_index = map_idx; 20202 20203 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 20204 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 20205 addr = (unsigned long)map; 20206 } else { 20207 u32 off = insn[1].imm; 20208 20209 if (off >= BPF_MAX_VAR_OFF) { 20210 verbose(env, "direct value offset of %u is not allowed\n", off); 20211 return -EINVAL; 20212 } 20213 20214 if (!map->ops->map_direct_value_addr) { 20215 verbose(env, "no direct value access support for this map type\n"); 20216 return -EINVAL; 20217 } 20218 20219 err = map->ops->map_direct_value_addr(map, &addr, off); 20220 if (err) { 20221 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 20222 map->value_size, off); 20223 return err; 20224 } 20225 20226 aux->map_off = off; 20227 addr += off; 20228 } 20229 20230 insn[0].imm = (u32)addr; 20231 insn[1].imm = addr >> 32; 20232 20233 next_insn: 20234 insn++; 20235 i++; 20236 continue; 20237 } 20238 20239 /* Basic sanity check before we invest more work here. */ 20240 if (!bpf_opcode_in_insntable(insn->code)) { 20241 verbose(env, "unknown opcode %02x\n", insn->code); 20242 return -EINVAL; 20243 } 20244 } 20245 20246 /* now all pseudo BPF_LD_IMM64 instructions load valid 20247 * 'struct bpf_map *' into a register instead of user map_fd. 20248 * These pointers will be used later by verifier to validate map access. 20249 */ 20250 return 0; 20251 } 20252 20253 /* drop refcnt of maps used by the rejected program */ 20254 static void release_maps(struct bpf_verifier_env *env) 20255 { 20256 __bpf_free_used_maps(env->prog->aux, env->used_maps, 20257 env->used_map_cnt); 20258 } 20259 20260 /* drop refcnt of maps used by the rejected program */ 20261 static void release_btfs(struct bpf_verifier_env *env) 20262 { 20263 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 20264 } 20265 20266 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 20267 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 20268 { 20269 struct bpf_insn *insn = env->prog->insnsi; 20270 int insn_cnt = env->prog->len; 20271 int i; 20272 20273 for (i = 0; i < insn_cnt; i++, insn++) { 20274 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 20275 continue; 20276 if (insn->src_reg == BPF_PSEUDO_FUNC) 20277 continue; 20278 insn->src_reg = 0; 20279 } 20280 } 20281 20282 /* single env->prog->insni[off] instruction was replaced with the range 20283 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 20284 * [0, off) and [off, end) to new locations, so the patched range stays zero 20285 */ 20286 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 20287 struct bpf_insn_aux_data *new_data, 20288 struct bpf_prog *new_prog, u32 off, u32 cnt) 20289 { 20290 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 20291 struct bpf_insn *insn = new_prog->insnsi; 20292 u32 old_seen = old_data[off].seen; 20293 u32 prog_len; 20294 int i; 20295 20296 /* aux info at OFF always needs adjustment, no matter fast path 20297 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 20298 * original insn at old prog. 20299 */ 20300 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 20301 20302 if (cnt == 1) 20303 return; 20304 prog_len = new_prog->len; 20305 20306 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 20307 memcpy(new_data + off + cnt - 1, old_data + off, 20308 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 20309 for (i = off; i < off + cnt - 1; i++) { 20310 /* Expand insni[off]'s seen count to the patched range. */ 20311 new_data[i].seen = old_seen; 20312 new_data[i].zext_dst = insn_has_def32(env, insn + i); 20313 } 20314 env->insn_aux_data = new_data; 20315 vfree(old_data); 20316 } 20317 20318 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 20319 { 20320 int i; 20321 20322 if (len == 1) 20323 return; 20324 /* NOTE: fake 'exit' subprog should be updated as well. */ 20325 for (i = 0; i <= env->subprog_cnt; i++) { 20326 if (env->subprog_info[i].start <= off) 20327 continue; 20328 env->subprog_info[i].start += len - 1; 20329 } 20330 } 20331 20332 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 20333 { 20334 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 20335 int i, sz = prog->aux->size_poke_tab; 20336 struct bpf_jit_poke_descriptor *desc; 20337 20338 for (i = 0; i < sz; i++) { 20339 desc = &tab[i]; 20340 if (desc->insn_idx <= off) 20341 continue; 20342 desc->insn_idx += len - 1; 20343 } 20344 } 20345 20346 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 20347 const struct bpf_insn *patch, u32 len) 20348 { 20349 struct bpf_prog *new_prog; 20350 struct bpf_insn_aux_data *new_data = NULL; 20351 20352 if (len > 1) { 20353 new_data = vzalloc(array_size(env->prog->len + len - 1, 20354 sizeof(struct bpf_insn_aux_data))); 20355 if (!new_data) 20356 return NULL; 20357 } 20358 20359 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 20360 if (IS_ERR(new_prog)) { 20361 if (PTR_ERR(new_prog) == -ERANGE) 20362 verbose(env, 20363 "insn %d cannot be patched due to 16-bit range\n", 20364 env->insn_aux_data[off].orig_idx); 20365 vfree(new_data); 20366 return NULL; 20367 } 20368 adjust_insn_aux_data(env, new_data, new_prog, off, len); 20369 adjust_subprog_starts(env, off, len); 20370 adjust_poke_descs(new_prog, off, len); 20371 return new_prog; 20372 } 20373 20374 /* 20375 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the 20376 * jump offset by 'delta'. 20377 */ 20378 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta) 20379 { 20380 struct bpf_insn *insn = prog->insnsi; 20381 u32 insn_cnt = prog->len, i; 20382 s32 imm; 20383 s16 off; 20384 20385 for (i = 0; i < insn_cnt; i++, insn++) { 20386 u8 code = insn->code; 20387 20388 if (tgt_idx <= i && i < tgt_idx + delta) 20389 continue; 20390 20391 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) || 20392 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT) 20393 continue; 20394 20395 if (insn->code == (BPF_JMP32 | BPF_JA)) { 20396 if (i + 1 + insn->imm != tgt_idx) 20397 continue; 20398 if (check_add_overflow(insn->imm, delta, &imm)) 20399 return -ERANGE; 20400 insn->imm = imm; 20401 } else { 20402 if (i + 1 + insn->off != tgt_idx) 20403 continue; 20404 if (check_add_overflow(insn->off, delta, &off)) 20405 return -ERANGE; 20406 insn->off = off; 20407 } 20408 } 20409 return 0; 20410 } 20411 20412 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 20413 u32 off, u32 cnt) 20414 { 20415 int i, j; 20416 20417 /* find first prog starting at or after off (first to remove) */ 20418 for (i = 0; i < env->subprog_cnt; i++) 20419 if (env->subprog_info[i].start >= off) 20420 break; 20421 /* find first prog starting at or after off + cnt (first to stay) */ 20422 for (j = i; j < env->subprog_cnt; j++) 20423 if (env->subprog_info[j].start >= off + cnt) 20424 break; 20425 /* if j doesn't start exactly at off + cnt, we are just removing 20426 * the front of previous prog 20427 */ 20428 if (env->subprog_info[j].start != off + cnt) 20429 j--; 20430 20431 if (j > i) { 20432 struct bpf_prog_aux *aux = env->prog->aux; 20433 int move; 20434 20435 /* move fake 'exit' subprog as well */ 20436 move = env->subprog_cnt + 1 - j; 20437 20438 memmove(env->subprog_info + i, 20439 env->subprog_info + j, 20440 sizeof(*env->subprog_info) * move); 20441 env->subprog_cnt -= j - i; 20442 20443 /* remove func_info */ 20444 if (aux->func_info) { 20445 move = aux->func_info_cnt - j; 20446 20447 memmove(aux->func_info + i, 20448 aux->func_info + j, 20449 sizeof(*aux->func_info) * move); 20450 aux->func_info_cnt -= j - i; 20451 /* func_info->insn_off is set after all code rewrites, 20452 * in adjust_btf_func() - no need to adjust 20453 */ 20454 } 20455 } else { 20456 /* convert i from "first prog to remove" to "first to adjust" */ 20457 if (env->subprog_info[i].start == off) 20458 i++; 20459 } 20460 20461 /* update fake 'exit' subprog as well */ 20462 for (; i <= env->subprog_cnt; i++) 20463 env->subprog_info[i].start -= cnt; 20464 20465 return 0; 20466 } 20467 20468 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 20469 u32 cnt) 20470 { 20471 struct bpf_prog *prog = env->prog; 20472 u32 i, l_off, l_cnt, nr_linfo; 20473 struct bpf_line_info *linfo; 20474 20475 nr_linfo = prog->aux->nr_linfo; 20476 if (!nr_linfo) 20477 return 0; 20478 20479 linfo = prog->aux->linfo; 20480 20481 /* find first line info to remove, count lines to be removed */ 20482 for (i = 0; i < nr_linfo; i++) 20483 if (linfo[i].insn_off >= off) 20484 break; 20485 20486 l_off = i; 20487 l_cnt = 0; 20488 for (; i < nr_linfo; i++) 20489 if (linfo[i].insn_off < off + cnt) 20490 l_cnt++; 20491 else 20492 break; 20493 20494 /* First live insn doesn't match first live linfo, it needs to "inherit" 20495 * last removed linfo. prog is already modified, so prog->len == off 20496 * means no live instructions after (tail of the program was removed). 20497 */ 20498 if (prog->len != off && l_cnt && 20499 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 20500 l_cnt--; 20501 linfo[--i].insn_off = off + cnt; 20502 } 20503 20504 /* remove the line info which refer to the removed instructions */ 20505 if (l_cnt) { 20506 memmove(linfo + l_off, linfo + i, 20507 sizeof(*linfo) * (nr_linfo - i)); 20508 20509 prog->aux->nr_linfo -= l_cnt; 20510 nr_linfo = prog->aux->nr_linfo; 20511 } 20512 20513 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 20514 for (i = l_off; i < nr_linfo; i++) 20515 linfo[i].insn_off -= cnt; 20516 20517 /* fix up all subprogs (incl. 'exit') which start >= off */ 20518 for (i = 0; i <= env->subprog_cnt; i++) 20519 if (env->subprog_info[i].linfo_idx > l_off) { 20520 /* program may have started in the removed region but 20521 * may not be fully removed 20522 */ 20523 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 20524 env->subprog_info[i].linfo_idx -= l_cnt; 20525 else 20526 env->subprog_info[i].linfo_idx = l_off; 20527 } 20528 20529 return 0; 20530 } 20531 20532 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 20533 { 20534 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 20535 unsigned int orig_prog_len = env->prog->len; 20536 int err; 20537 20538 if (bpf_prog_is_offloaded(env->prog->aux)) 20539 bpf_prog_offload_remove_insns(env, off, cnt); 20540 20541 err = bpf_remove_insns(env->prog, off, cnt); 20542 if (err) 20543 return err; 20544 20545 err = adjust_subprog_starts_after_remove(env, off, cnt); 20546 if (err) 20547 return err; 20548 20549 err = bpf_adj_linfo_after_remove(env, off, cnt); 20550 if (err) 20551 return err; 20552 20553 memmove(aux_data + off, aux_data + off + cnt, 20554 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 20555 20556 return 0; 20557 } 20558 20559 /* The verifier does more data flow analysis than llvm and will not 20560 * explore branches that are dead at run time. Malicious programs can 20561 * have dead code too. Therefore replace all dead at-run-time code 20562 * with 'ja -1'. 20563 * 20564 * Just nops are not optimal, e.g. if they would sit at the end of the 20565 * program and through another bug we would manage to jump there, then 20566 * we'd execute beyond program memory otherwise. Returning exception 20567 * code also wouldn't work since we can have subprogs where the dead 20568 * code could be located. 20569 */ 20570 static void sanitize_dead_code(struct bpf_verifier_env *env) 20571 { 20572 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 20573 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 20574 struct bpf_insn *insn = env->prog->insnsi; 20575 const int insn_cnt = env->prog->len; 20576 int i; 20577 20578 for (i = 0; i < insn_cnt; i++) { 20579 if (aux_data[i].seen) 20580 continue; 20581 memcpy(insn + i, &trap, sizeof(trap)); 20582 aux_data[i].zext_dst = false; 20583 } 20584 } 20585 20586 static bool insn_is_cond_jump(u8 code) 20587 { 20588 u8 op; 20589 20590 op = BPF_OP(code); 20591 if (BPF_CLASS(code) == BPF_JMP32) 20592 return op != BPF_JA; 20593 20594 if (BPF_CLASS(code) != BPF_JMP) 20595 return false; 20596 20597 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 20598 } 20599 20600 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 20601 { 20602 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 20603 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 20604 struct bpf_insn *insn = env->prog->insnsi; 20605 const int insn_cnt = env->prog->len; 20606 int i; 20607 20608 for (i = 0; i < insn_cnt; i++, insn++) { 20609 if (!insn_is_cond_jump(insn->code)) 20610 continue; 20611 20612 if (!aux_data[i + 1].seen) 20613 ja.off = insn->off; 20614 else if (!aux_data[i + 1 + insn->off].seen) 20615 ja.off = 0; 20616 else 20617 continue; 20618 20619 if (bpf_prog_is_offloaded(env->prog->aux)) 20620 bpf_prog_offload_replace_insn(env, i, &ja); 20621 20622 memcpy(insn, &ja, sizeof(ja)); 20623 } 20624 } 20625 20626 static int opt_remove_dead_code(struct bpf_verifier_env *env) 20627 { 20628 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 20629 int insn_cnt = env->prog->len; 20630 int i, err; 20631 20632 for (i = 0; i < insn_cnt; i++) { 20633 int j; 20634 20635 j = 0; 20636 while (i + j < insn_cnt && !aux_data[i + j].seen) 20637 j++; 20638 if (!j) 20639 continue; 20640 20641 err = verifier_remove_insns(env, i, j); 20642 if (err) 20643 return err; 20644 insn_cnt = env->prog->len; 20645 } 20646 20647 return 0; 20648 } 20649 20650 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 20651 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0); 20652 20653 static int opt_remove_nops(struct bpf_verifier_env *env) 20654 { 20655 struct bpf_insn *insn = env->prog->insnsi; 20656 int insn_cnt = env->prog->len; 20657 bool is_may_goto_0, is_ja; 20658 int i, err; 20659 20660 for (i = 0; i < insn_cnt; i++) { 20661 is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0)); 20662 is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP)); 20663 20664 if (!is_may_goto_0 && !is_ja) 20665 continue; 20666 20667 err = verifier_remove_insns(env, i, 1); 20668 if (err) 20669 return err; 20670 insn_cnt--; 20671 /* Go back one insn to catch may_goto +1; may_goto +0 sequence */ 20672 i -= (is_may_goto_0 && i > 0) ? 2 : 1; 20673 } 20674 20675 return 0; 20676 } 20677 20678 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 20679 const union bpf_attr *attr) 20680 { 20681 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 20682 struct bpf_insn_aux_data *aux = env->insn_aux_data; 20683 int i, patch_len, delta = 0, len = env->prog->len; 20684 struct bpf_insn *insns = env->prog->insnsi; 20685 struct bpf_prog *new_prog; 20686 bool rnd_hi32; 20687 20688 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 20689 zext_patch[1] = BPF_ZEXT_REG(0); 20690 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 20691 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 20692 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 20693 for (i = 0; i < len; i++) { 20694 int adj_idx = i + delta; 20695 struct bpf_insn insn; 20696 int load_reg; 20697 20698 insn = insns[adj_idx]; 20699 load_reg = insn_def_regno(&insn); 20700 if (!aux[adj_idx].zext_dst) { 20701 u8 code, class; 20702 u32 imm_rnd; 20703 20704 if (!rnd_hi32) 20705 continue; 20706 20707 code = insn.code; 20708 class = BPF_CLASS(code); 20709 if (load_reg == -1) 20710 continue; 20711 20712 /* NOTE: arg "reg" (the fourth one) is only used for 20713 * BPF_STX + SRC_OP, so it is safe to pass NULL 20714 * here. 20715 */ 20716 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 20717 if (class == BPF_LD && 20718 BPF_MODE(code) == BPF_IMM) 20719 i++; 20720 continue; 20721 } 20722 20723 /* ctx load could be transformed into wider load. */ 20724 if (class == BPF_LDX && 20725 aux[adj_idx].ptr_type == PTR_TO_CTX) 20726 continue; 20727 20728 imm_rnd = get_random_u32(); 20729 rnd_hi32_patch[0] = insn; 20730 rnd_hi32_patch[1].imm = imm_rnd; 20731 rnd_hi32_patch[3].dst_reg = load_reg; 20732 patch = rnd_hi32_patch; 20733 patch_len = 4; 20734 goto apply_patch_buffer; 20735 } 20736 20737 /* Add in an zero-extend instruction if a) the JIT has requested 20738 * it or b) it's a CMPXCHG. 20739 * 20740 * The latter is because: BPF_CMPXCHG always loads a value into 20741 * R0, therefore always zero-extends. However some archs' 20742 * equivalent instruction only does this load when the 20743 * comparison is successful. This detail of CMPXCHG is 20744 * orthogonal to the general zero-extension behaviour of the 20745 * CPU, so it's treated independently of bpf_jit_needs_zext. 20746 */ 20747 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 20748 continue; 20749 20750 /* Zero-extension is done by the caller. */ 20751 if (bpf_pseudo_kfunc_call(&insn)) 20752 continue; 20753 20754 if (verifier_bug_if(load_reg == -1, env, 20755 "zext_dst is set, but no reg is defined")) 20756 return -EFAULT; 20757 20758 zext_patch[0] = insn; 20759 zext_patch[1].dst_reg = load_reg; 20760 zext_patch[1].src_reg = load_reg; 20761 patch = zext_patch; 20762 patch_len = 2; 20763 apply_patch_buffer: 20764 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 20765 if (!new_prog) 20766 return -ENOMEM; 20767 env->prog = new_prog; 20768 insns = new_prog->insnsi; 20769 aux = env->insn_aux_data; 20770 delta += patch_len - 1; 20771 } 20772 20773 return 0; 20774 } 20775 20776 /* convert load instructions that access fields of a context type into a 20777 * sequence of instructions that access fields of the underlying structure: 20778 * struct __sk_buff -> struct sk_buff 20779 * struct bpf_sock_ops -> struct sock 20780 */ 20781 static int convert_ctx_accesses(struct bpf_verifier_env *env) 20782 { 20783 struct bpf_subprog_info *subprogs = env->subprog_info; 20784 const struct bpf_verifier_ops *ops = env->ops; 20785 int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0; 20786 const int insn_cnt = env->prog->len; 20787 struct bpf_insn *epilogue_buf = env->epilogue_buf; 20788 struct bpf_insn *insn_buf = env->insn_buf; 20789 struct bpf_insn *insn; 20790 u32 target_size, size_default, off; 20791 struct bpf_prog *new_prog; 20792 enum bpf_access_type type; 20793 bool is_narrower_load; 20794 int epilogue_idx = 0; 20795 20796 if (ops->gen_epilogue) { 20797 epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog, 20798 -(subprogs[0].stack_depth + 8)); 20799 if (epilogue_cnt >= INSN_BUF_SIZE) { 20800 verbose(env, "bpf verifier is misconfigured\n"); 20801 return -EINVAL; 20802 } else if (epilogue_cnt) { 20803 /* Save the ARG_PTR_TO_CTX for the epilogue to use */ 20804 cnt = 0; 20805 subprogs[0].stack_depth += 8; 20806 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1, 20807 -subprogs[0].stack_depth); 20808 insn_buf[cnt++] = env->prog->insnsi[0]; 20809 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 20810 if (!new_prog) 20811 return -ENOMEM; 20812 env->prog = new_prog; 20813 delta += cnt - 1; 20814 20815 ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1); 20816 if (ret < 0) 20817 return ret; 20818 } 20819 } 20820 20821 if (ops->gen_prologue || env->seen_direct_write) { 20822 if (!ops->gen_prologue) { 20823 verbose(env, "bpf verifier is misconfigured\n"); 20824 return -EINVAL; 20825 } 20826 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 20827 env->prog); 20828 if (cnt >= INSN_BUF_SIZE) { 20829 verbose(env, "bpf verifier is misconfigured\n"); 20830 return -EINVAL; 20831 } else if (cnt) { 20832 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 20833 if (!new_prog) 20834 return -ENOMEM; 20835 20836 env->prog = new_prog; 20837 delta += cnt - 1; 20838 20839 ret = add_kfunc_in_insns(env, insn_buf, cnt - 1); 20840 if (ret < 0) 20841 return ret; 20842 } 20843 } 20844 20845 if (delta) 20846 WARN_ON(adjust_jmp_off(env->prog, 0, delta)); 20847 20848 if (bpf_prog_is_offloaded(env->prog->aux)) 20849 return 0; 20850 20851 insn = env->prog->insnsi + delta; 20852 20853 for (i = 0; i < insn_cnt; i++, insn++) { 20854 bpf_convert_ctx_access_t convert_ctx_access; 20855 u8 mode; 20856 20857 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 20858 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 20859 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 20860 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 20861 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 20862 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 20863 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 20864 type = BPF_READ; 20865 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 20866 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 20867 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 20868 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 20869 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 20870 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 20871 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 20872 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 20873 type = BPF_WRITE; 20874 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) || 20875 insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) || 20876 insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) || 20877 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) && 20878 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) { 20879 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code); 20880 env->prog->aux->num_exentries++; 20881 continue; 20882 } else if (insn->code == (BPF_JMP | BPF_EXIT) && 20883 epilogue_cnt && 20884 i + delta < subprogs[1].start) { 20885 /* Generate epilogue for the main prog */ 20886 if (epilogue_idx) { 20887 /* jump back to the earlier generated epilogue */ 20888 insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1); 20889 cnt = 1; 20890 } else { 20891 memcpy(insn_buf, epilogue_buf, 20892 epilogue_cnt * sizeof(*epilogue_buf)); 20893 cnt = epilogue_cnt; 20894 /* epilogue_idx cannot be 0. It must have at 20895 * least one ctx ptr saving insn before the 20896 * epilogue. 20897 */ 20898 epilogue_idx = i + delta; 20899 } 20900 goto patch_insn_buf; 20901 } else { 20902 continue; 20903 } 20904 20905 if (type == BPF_WRITE && 20906 env->insn_aux_data[i + delta].sanitize_stack_spill) { 20907 struct bpf_insn patch[] = { 20908 *insn, 20909 BPF_ST_NOSPEC(), 20910 }; 20911 20912 cnt = ARRAY_SIZE(patch); 20913 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 20914 if (!new_prog) 20915 return -ENOMEM; 20916 20917 delta += cnt - 1; 20918 env->prog = new_prog; 20919 insn = new_prog->insnsi + i + delta; 20920 continue; 20921 } 20922 20923 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 20924 case PTR_TO_CTX: 20925 if (!ops->convert_ctx_access) 20926 continue; 20927 convert_ctx_access = ops->convert_ctx_access; 20928 break; 20929 case PTR_TO_SOCKET: 20930 case PTR_TO_SOCK_COMMON: 20931 convert_ctx_access = bpf_sock_convert_ctx_access; 20932 break; 20933 case PTR_TO_TCP_SOCK: 20934 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 20935 break; 20936 case PTR_TO_XDP_SOCK: 20937 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 20938 break; 20939 case PTR_TO_BTF_ID: 20940 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 20941 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 20942 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 20943 * be said once it is marked PTR_UNTRUSTED, hence we must handle 20944 * any faults for loads into such types. BPF_WRITE is disallowed 20945 * for this case. 20946 */ 20947 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 20948 if (type == BPF_READ) { 20949 if (BPF_MODE(insn->code) == BPF_MEM) 20950 insn->code = BPF_LDX | BPF_PROBE_MEM | 20951 BPF_SIZE((insn)->code); 20952 else 20953 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 20954 BPF_SIZE((insn)->code); 20955 env->prog->aux->num_exentries++; 20956 } 20957 continue; 20958 case PTR_TO_ARENA: 20959 if (BPF_MODE(insn->code) == BPF_MEMSX) { 20960 verbose(env, "sign extending loads from arena are not supported yet\n"); 20961 return -EOPNOTSUPP; 20962 } 20963 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 20964 env->prog->aux->num_exentries++; 20965 continue; 20966 default: 20967 continue; 20968 } 20969 20970 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 20971 size = BPF_LDST_BYTES(insn); 20972 mode = BPF_MODE(insn->code); 20973 20974 /* If the read access is a narrower load of the field, 20975 * convert to a 4/8-byte load, to minimum program type specific 20976 * convert_ctx_access changes. If conversion is successful, 20977 * we will apply proper mask to the result. 20978 */ 20979 is_narrower_load = size < ctx_field_size; 20980 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 20981 off = insn->off; 20982 if (is_narrower_load) { 20983 u8 size_code; 20984 20985 if (type == BPF_WRITE) { 20986 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 20987 return -EINVAL; 20988 } 20989 20990 size_code = BPF_H; 20991 if (ctx_field_size == 4) 20992 size_code = BPF_W; 20993 else if (ctx_field_size == 8) 20994 size_code = BPF_DW; 20995 20996 insn->off = off & ~(size_default - 1); 20997 insn->code = BPF_LDX | BPF_MEM | size_code; 20998 } 20999 21000 target_size = 0; 21001 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 21002 &target_size); 21003 if (cnt == 0 || cnt >= INSN_BUF_SIZE || 21004 (ctx_field_size && !target_size)) { 21005 verbose(env, "bpf verifier is misconfigured\n"); 21006 return -EINVAL; 21007 } 21008 21009 if (is_narrower_load && size < target_size) { 21010 u8 shift = bpf_ctx_narrow_access_offset( 21011 off, size, size_default) * 8; 21012 if (shift && cnt + 1 >= INSN_BUF_SIZE) { 21013 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 21014 return -EINVAL; 21015 } 21016 if (ctx_field_size <= 4) { 21017 if (shift) 21018 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 21019 insn->dst_reg, 21020 shift); 21021 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 21022 (1 << size * 8) - 1); 21023 } else { 21024 if (shift) 21025 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 21026 insn->dst_reg, 21027 shift); 21028 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 21029 (1ULL << size * 8) - 1); 21030 } 21031 } 21032 if (mode == BPF_MEMSX) 21033 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 21034 insn->dst_reg, insn->dst_reg, 21035 size * 8, 0); 21036 21037 patch_insn_buf: 21038 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21039 if (!new_prog) 21040 return -ENOMEM; 21041 21042 delta += cnt - 1; 21043 21044 /* keep walking new program and skip insns we just inserted */ 21045 env->prog = new_prog; 21046 insn = new_prog->insnsi + i + delta; 21047 } 21048 21049 return 0; 21050 } 21051 21052 static int jit_subprogs(struct bpf_verifier_env *env) 21053 { 21054 struct bpf_prog *prog = env->prog, **func, *tmp; 21055 int i, j, subprog_start, subprog_end = 0, len, subprog; 21056 struct bpf_map *map_ptr; 21057 struct bpf_insn *insn; 21058 void *old_bpf_func; 21059 int err, num_exentries; 21060 21061 if (env->subprog_cnt <= 1) 21062 return 0; 21063 21064 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21065 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 21066 continue; 21067 21068 /* Upon error here we cannot fall back to interpreter but 21069 * need a hard reject of the program. Thus -EFAULT is 21070 * propagated in any case. 21071 */ 21072 subprog = find_subprog(env, i + insn->imm + 1); 21073 if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d", 21074 i + insn->imm + 1)) 21075 return -EFAULT; 21076 /* temporarily remember subprog id inside insn instead of 21077 * aux_data, since next loop will split up all insns into funcs 21078 */ 21079 insn->off = subprog; 21080 /* remember original imm in case JIT fails and fallback 21081 * to interpreter will be needed 21082 */ 21083 env->insn_aux_data[i].call_imm = insn->imm; 21084 /* point imm to __bpf_call_base+1 from JITs point of view */ 21085 insn->imm = 1; 21086 if (bpf_pseudo_func(insn)) { 21087 #if defined(MODULES_VADDR) 21088 u64 addr = MODULES_VADDR; 21089 #else 21090 u64 addr = VMALLOC_START; 21091 #endif 21092 /* jit (e.g. x86_64) may emit fewer instructions 21093 * if it learns a u32 imm is the same as a u64 imm. 21094 * Set close enough to possible prog address. 21095 */ 21096 insn[0].imm = (u32)addr; 21097 insn[1].imm = addr >> 32; 21098 } 21099 } 21100 21101 err = bpf_prog_alloc_jited_linfo(prog); 21102 if (err) 21103 goto out_undo_insn; 21104 21105 err = -ENOMEM; 21106 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 21107 if (!func) 21108 goto out_undo_insn; 21109 21110 for (i = 0; i < env->subprog_cnt; i++) { 21111 subprog_start = subprog_end; 21112 subprog_end = env->subprog_info[i + 1].start; 21113 21114 len = subprog_end - subprog_start; 21115 /* bpf_prog_run() doesn't call subprogs directly, 21116 * hence main prog stats include the runtime of subprogs. 21117 * subprogs don't have IDs and not reachable via prog_get_next_id 21118 * func[i]->stats will never be accessed and stays NULL 21119 */ 21120 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 21121 if (!func[i]) 21122 goto out_free; 21123 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 21124 len * sizeof(struct bpf_insn)); 21125 func[i]->type = prog->type; 21126 func[i]->len = len; 21127 if (bpf_prog_calc_tag(func[i])) 21128 goto out_free; 21129 func[i]->is_func = 1; 21130 func[i]->sleepable = prog->sleepable; 21131 func[i]->aux->func_idx = i; 21132 /* Below members will be freed only at prog->aux */ 21133 func[i]->aux->btf = prog->aux->btf; 21134 func[i]->aux->func_info = prog->aux->func_info; 21135 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 21136 func[i]->aux->poke_tab = prog->aux->poke_tab; 21137 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 21138 21139 for (j = 0; j < prog->aux->size_poke_tab; j++) { 21140 struct bpf_jit_poke_descriptor *poke; 21141 21142 poke = &prog->aux->poke_tab[j]; 21143 if (poke->insn_idx < subprog_end && 21144 poke->insn_idx >= subprog_start) 21145 poke->aux = func[i]->aux; 21146 } 21147 21148 func[i]->aux->name[0] = 'F'; 21149 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 21150 if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) 21151 func[i]->aux->jits_use_priv_stack = true; 21152 21153 func[i]->jit_requested = 1; 21154 func[i]->blinding_requested = prog->blinding_requested; 21155 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 21156 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 21157 func[i]->aux->linfo = prog->aux->linfo; 21158 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 21159 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 21160 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 21161 func[i]->aux->arena = prog->aux->arena; 21162 num_exentries = 0; 21163 insn = func[i]->insnsi; 21164 for (j = 0; j < func[i]->len; j++, insn++) { 21165 if (BPF_CLASS(insn->code) == BPF_LDX && 21166 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 21167 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 21168 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 21169 num_exentries++; 21170 if ((BPF_CLASS(insn->code) == BPF_STX || 21171 BPF_CLASS(insn->code) == BPF_ST) && 21172 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 21173 num_exentries++; 21174 if (BPF_CLASS(insn->code) == BPF_STX && 21175 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 21176 num_exentries++; 21177 } 21178 func[i]->aux->num_exentries = num_exentries; 21179 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 21180 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 21181 func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data; 21182 func[i]->aux->might_sleep = env->subprog_info[i].might_sleep; 21183 if (!i) 21184 func[i]->aux->exception_boundary = env->seen_exception; 21185 func[i] = bpf_int_jit_compile(func[i]); 21186 if (!func[i]->jited) { 21187 err = -ENOTSUPP; 21188 goto out_free; 21189 } 21190 cond_resched(); 21191 } 21192 21193 /* at this point all bpf functions were successfully JITed 21194 * now populate all bpf_calls with correct addresses and 21195 * run last pass of JIT 21196 */ 21197 for (i = 0; i < env->subprog_cnt; i++) { 21198 insn = func[i]->insnsi; 21199 for (j = 0; j < func[i]->len; j++, insn++) { 21200 if (bpf_pseudo_func(insn)) { 21201 subprog = insn->off; 21202 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 21203 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 21204 continue; 21205 } 21206 if (!bpf_pseudo_call(insn)) 21207 continue; 21208 subprog = insn->off; 21209 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 21210 } 21211 21212 /* we use the aux data to keep a list of the start addresses 21213 * of the JITed images for each function in the program 21214 * 21215 * for some architectures, such as powerpc64, the imm field 21216 * might not be large enough to hold the offset of the start 21217 * address of the callee's JITed image from __bpf_call_base 21218 * 21219 * in such cases, we can lookup the start address of a callee 21220 * by using its subprog id, available from the off field of 21221 * the call instruction, as an index for this list 21222 */ 21223 func[i]->aux->func = func; 21224 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 21225 func[i]->aux->real_func_cnt = env->subprog_cnt; 21226 } 21227 for (i = 0; i < env->subprog_cnt; i++) { 21228 old_bpf_func = func[i]->bpf_func; 21229 tmp = bpf_int_jit_compile(func[i]); 21230 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 21231 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 21232 err = -ENOTSUPP; 21233 goto out_free; 21234 } 21235 cond_resched(); 21236 } 21237 21238 /* finally lock prog and jit images for all functions and 21239 * populate kallsysm. Begin at the first subprogram, since 21240 * bpf_prog_load will add the kallsyms for the main program. 21241 */ 21242 for (i = 1; i < env->subprog_cnt; i++) { 21243 err = bpf_prog_lock_ro(func[i]); 21244 if (err) 21245 goto out_free; 21246 } 21247 21248 for (i = 1; i < env->subprog_cnt; i++) 21249 bpf_prog_kallsyms_add(func[i]); 21250 21251 /* Last step: make now unused interpreter insns from main 21252 * prog consistent for later dump requests, so they can 21253 * later look the same as if they were interpreted only. 21254 */ 21255 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21256 if (bpf_pseudo_func(insn)) { 21257 insn[0].imm = env->insn_aux_data[i].call_imm; 21258 insn[1].imm = insn->off; 21259 insn->off = 0; 21260 continue; 21261 } 21262 if (!bpf_pseudo_call(insn)) 21263 continue; 21264 insn->off = env->insn_aux_data[i].call_imm; 21265 subprog = find_subprog(env, i + insn->off + 1); 21266 insn->imm = subprog; 21267 } 21268 21269 prog->jited = 1; 21270 prog->bpf_func = func[0]->bpf_func; 21271 prog->jited_len = func[0]->jited_len; 21272 prog->aux->extable = func[0]->aux->extable; 21273 prog->aux->num_exentries = func[0]->aux->num_exentries; 21274 prog->aux->func = func; 21275 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 21276 prog->aux->real_func_cnt = env->subprog_cnt; 21277 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 21278 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 21279 bpf_prog_jit_attempt_done(prog); 21280 return 0; 21281 out_free: 21282 /* We failed JIT'ing, so at this point we need to unregister poke 21283 * descriptors from subprogs, so that kernel is not attempting to 21284 * patch it anymore as we're freeing the subprog JIT memory. 21285 */ 21286 for (i = 0; i < prog->aux->size_poke_tab; i++) { 21287 map_ptr = prog->aux->poke_tab[i].tail_call.map; 21288 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 21289 } 21290 /* At this point we're guaranteed that poke descriptors are not 21291 * live anymore. We can just unlink its descriptor table as it's 21292 * released with the main prog. 21293 */ 21294 for (i = 0; i < env->subprog_cnt; i++) { 21295 if (!func[i]) 21296 continue; 21297 func[i]->aux->poke_tab = NULL; 21298 bpf_jit_free(func[i]); 21299 } 21300 kfree(func); 21301 out_undo_insn: 21302 /* cleanup main prog to be interpreted */ 21303 prog->jit_requested = 0; 21304 prog->blinding_requested = 0; 21305 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21306 if (!bpf_pseudo_call(insn)) 21307 continue; 21308 insn->off = 0; 21309 insn->imm = env->insn_aux_data[i].call_imm; 21310 } 21311 bpf_prog_jit_attempt_done(prog); 21312 return err; 21313 } 21314 21315 static int fixup_call_args(struct bpf_verifier_env *env) 21316 { 21317 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 21318 struct bpf_prog *prog = env->prog; 21319 struct bpf_insn *insn = prog->insnsi; 21320 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 21321 int i, depth; 21322 #endif 21323 int err = 0; 21324 21325 if (env->prog->jit_requested && 21326 !bpf_prog_is_offloaded(env->prog->aux)) { 21327 err = jit_subprogs(env); 21328 if (err == 0) 21329 return 0; 21330 if (err == -EFAULT) 21331 return err; 21332 } 21333 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 21334 if (has_kfunc_call) { 21335 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 21336 return -EINVAL; 21337 } 21338 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 21339 /* When JIT fails the progs with bpf2bpf calls and tail_calls 21340 * have to be rejected, since interpreter doesn't support them yet. 21341 */ 21342 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 21343 return -EINVAL; 21344 } 21345 for (i = 0; i < prog->len; i++, insn++) { 21346 if (bpf_pseudo_func(insn)) { 21347 /* When JIT fails the progs with callback calls 21348 * have to be rejected, since interpreter doesn't support them yet. 21349 */ 21350 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 21351 return -EINVAL; 21352 } 21353 21354 if (!bpf_pseudo_call(insn)) 21355 continue; 21356 depth = get_callee_stack_depth(env, insn, i); 21357 if (depth < 0) 21358 return depth; 21359 bpf_patch_call_args(insn, depth); 21360 } 21361 err = 0; 21362 #endif 21363 return err; 21364 } 21365 21366 /* replace a generic kfunc with a specialized version if necessary */ 21367 static void specialize_kfunc(struct bpf_verifier_env *env, 21368 u32 func_id, u16 offset, unsigned long *addr) 21369 { 21370 struct bpf_prog *prog = env->prog; 21371 bool seen_direct_write; 21372 void *xdp_kfunc; 21373 bool is_rdonly; 21374 21375 if (bpf_dev_bound_kfunc_id(func_id)) { 21376 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 21377 if (xdp_kfunc) { 21378 *addr = (unsigned long)xdp_kfunc; 21379 return; 21380 } 21381 /* fallback to default kfunc when not supported by netdev */ 21382 } 21383 21384 if (offset) 21385 return; 21386 21387 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 21388 seen_direct_write = env->seen_direct_write; 21389 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 21390 21391 if (is_rdonly) 21392 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 21393 21394 /* restore env->seen_direct_write to its original value, since 21395 * may_access_direct_pkt_data mutates it 21396 */ 21397 env->seen_direct_write = seen_direct_write; 21398 } 21399 21400 if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] && 21401 bpf_lsm_has_d_inode_locked(prog)) 21402 *addr = (unsigned long)bpf_set_dentry_xattr_locked; 21403 21404 if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] && 21405 bpf_lsm_has_d_inode_locked(prog)) 21406 *addr = (unsigned long)bpf_remove_dentry_xattr_locked; 21407 } 21408 21409 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 21410 u16 struct_meta_reg, 21411 u16 node_offset_reg, 21412 struct bpf_insn *insn, 21413 struct bpf_insn *insn_buf, 21414 int *cnt) 21415 { 21416 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 21417 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 21418 21419 insn_buf[0] = addr[0]; 21420 insn_buf[1] = addr[1]; 21421 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 21422 insn_buf[3] = *insn; 21423 *cnt = 4; 21424 } 21425 21426 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 21427 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 21428 { 21429 const struct bpf_kfunc_desc *desc; 21430 21431 if (!insn->imm) { 21432 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 21433 return -EINVAL; 21434 } 21435 21436 *cnt = 0; 21437 21438 /* insn->imm has the btf func_id. Replace it with an offset relative to 21439 * __bpf_call_base, unless the JIT needs to call functions that are 21440 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 21441 */ 21442 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 21443 if (!desc) { 21444 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 21445 insn->imm); 21446 return -EFAULT; 21447 } 21448 21449 if (!bpf_jit_supports_far_kfunc_call()) 21450 insn->imm = BPF_CALL_IMM(desc->addr); 21451 if (insn->off) 21452 return 0; 21453 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 21454 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 21455 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21456 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 21457 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 21458 21459 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 21460 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 21461 insn_idx); 21462 return -EFAULT; 21463 } 21464 21465 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 21466 insn_buf[1] = addr[0]; 21467 insn_buf[2] = addr[1]; 21468 insn_buf[3] = *insn; 21469 *cnt = 4; 21470 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 21471 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 21472 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 21473 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21474 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 21475 21476 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 21477 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 21478 insn_idx); 21479 return -EFAULT; 21480 } 21481 21482 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 21483 !kptr_struct_meta) { 21484 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 21485 insn_idx); 21486 return -EFAULT; 21487 } 21488 21489 insn_buf[0] = addr[0]; 21490 insn_buf[1] = addr[1]; 21491 insn_buf[2] = *insn; 21492 *cnt = 3; 21493 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 21494 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 21495 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 21496 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21497 int struct_meta_reg = BPF_REG_3; 21498 int node_offset_reg = BPF_REG_4; 21499 21500 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 21501 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 21502 struct_meta_reg = BPF_REG_4; 21503 node_offset_reg = BPF_REG_5; 21504 } 21505 21506 if (!kptr_struct_meta) { 21507 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 21508 insn_idx); 21509 return -EFAULT; 21510 } 21511 21512 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 21513 node_offset_reg, insn, insn_buf, cnt); 21514 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 21515 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 21516 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 21517 *cnt = 1; 21518 } 21519 21520 if (env->insn_aux_data[insn_idx].arg_prog) { 21521 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 21522 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 21523 int idx = *cnt; 21524 21525 insn_buf[idx++] = ld_addrs[0]; 21526 insn_buf[idx++] = ld_addrs[1]; 21527 insn_buf[idx++] = *insn; 21528 *cnt = idx; 21529 } 21530 return 0; 21531 } 21532 21533 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 21534 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 21535 { 21536 struct bpf_subprog_info *info = env->subprog_info; 21537 int cnt = env->subprog_cnt; 21538 struct bpf_prog *prog; 21539 21540 /* We only reserve one slot for hidden subprogs in subprog_info. */ 21541 if (env->hidden_subprog_cnt) { 21542 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 21543 return -EFAULT; 21544 } 21545 /* We're not patching any existing instruction, just appending the new 21546 * ones for the hidden subprog. Hence all of the adjustment operations 21547 * in bpf_patch_insn_data are no-ops. 21548 */ 21549 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 21550 if (!prog) 21551 return -ENOMEM; 21552 env->prog = prog; 21553 info[cnt + 1].start = info[cnt].start; 21554 info[cnt].start = prog->len - len + 1; 21555 env->subprog_cnt++; 21556 env->hidden_subprog_cnt++; 21557 return 0; 21558 } 21559 21560 /* Do various post-verification rewrites in a single program pass. 21561 * These rewrites simplify JIT and interpreter implementations. 21562 */ 21563 static int do_misc_fixups(struct bpf_verifier_env *env) 21564 { 21565 struct bpf_prog *prog = env->prog; 21566 enum bpf_attach_type eatype = prog->expected_attach_type; 21567 enum bpf_prog_type prog_type = resolve_prog_type(prog); 21568 struct bpf_insn *insn = prog->insnsi; 21569 const struct bpf_func_proto *fn; 21570 const int insn_cnt = prog->len; 21571 const struct bpf_map_ops *ops; 21572 struct bpf_insn_aux_data *aux; 21573 struct bpf_insn *insn_buf = env->insn_buf; 21574 struct bpf_prog *new_prog; 21575 struct bpf_map *map_ptr; 21576 int i, ret, cnt, delta = 0, cur_subprog = 0; 21577 struct bpf_subprog_info *subprogs = env->subprog_info; 21578 u16 stack_depth = subprogs[cur_subprog].stack_depth; 21579 u16 stack_depth_extra = 0; 21580 21581 if (env->seen_exception && !env->exception_callback_subprog) { 21582 struct bpf_insn patch[] = { 21583 env->prog->insnsi[insn_cnt - 1], 21584 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 21585 BPF_EXIT_INSN(), 21586 }; 21587 21588 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 21589 if (ret < 0) 21590 return ret; 21591 prog = env->prog; 21592 insn = prog->insnsi; 21593 21594 env->exception_callback_subprog = env->subprog_cnt - 1; 21595 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 21596 mark_subprog_exc_cb(env, env->exception_callback_subprog); 21597 } 21598 21599 for (i = 0; i < insn_cnt;) { 21600 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 21601 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 21602 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 21603 /* convert to 32-bit mov that clears upper 32-bit */ 21604 insn->code = BPF_ALU | BPF_MOV | BPF_X; 21605 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 21606 insn->off = 0; 21607 insn->imm = 0; 21608 } /* cast from as(0) to as(1) should be handled by JIT */ 21609 goto next_insn; 21610 } 21611 21612 if (env->insn_aux_data[i + delta].needs_zext) 21613 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 21614 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 21615 21616 /* Make sdiv/smod divide-by-minus-one exceptions impossible. */ 21617 if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) || 21618 insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) || 21619 insn->code == (BPF_ALU | BPF_MOD | BPF_K) || 21620 insn->code == (BPF_ALU | BPF_DIV | BPF_K)) && 21621 insn->off == 1 && insn->imm == -1) { 21622 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 21623 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 21624 struct bpf_insn *patchlet; 21625 struct bpf_insn chk_and_sdiv[] = { 21626 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 21627 BPF_NEG | BPF_K, insn->dst_reg, 21628 0, 0, 0), 21629 }; 21630 struct bpf_insn chk_and_smod[] = { 21631 BPF_MOV32_IMM(insn->dst_reg, 0), 21632 }; 21633 21634 patchlet = isdiv ? chk_and_sdiv : chk_and_smod; 21635 cnt = isdiv ? ARRAY_SIZE(chk_and_sdiv) : ARRAY_SIZE(chk_and_smod); 21636 21637 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 21638 if (!new_prog) 21639 return -ENOMEM; 21640 21641 delta += cnt - 1; 21642 env->prog = prog = new_prog; 21643 insn = new_prog->insnsi + i + delta; 21644 goto next_insn; 21645 } 21646 21647 /* Make divide-by-zero and divide-by-minus-one exceptions impossible. */ 21648 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 21649 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 21650 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 21651 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 21652 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 21653 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 21654 bool is_sdiv = isdiv && insn->off == 1; 21655 bool is_smod = !isdiv && insn->off == 1; 21656 struct bpf_insn *patchlet; 21657 struct bpf_insn chk_and_div[] = { 21658 /* [R,W]x div 0 -> 0 */ 21659 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 21660 BPF_JNE | BPF_K, insn->src_reg, 21661 0, 2, 0), 21662 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 21663 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 21664 *insn, 21665 }; 21666 struct bpf_insn chk_and_mod[] = { 21667 /* [R,W]x mod 0 -> [R,W]x */ 21668 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 21669 BPF_JEQ | BPF_K, insn->src_reg, 21670 0, 1 + (is64 ? 0 : 1), 0), 21671 *insn, 21672 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 21673 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 21674 }; 21675 struct bpf_insn chk_and_sdiv[] = { 21676 /* [R,W]x sdiv 0 -> 0 21677 * LLONG_MIN sdiv -1 -> LLONG_MIN 21678 * INT_MIN sdiv -1 -> INT_MIN 21679 */ 21680 BPF_MOV64_REG(BPF_REG_AX, insn->src_reg), 21681 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 21682 BPF_ADD | BPF_K, BPF_REG_AX, 21683 0, 0, 1), 21684 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 21685 BPF_JGT | BPF_K, BPF_REG_AX, 21686 0, 4, 1), 21687 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 21688 BPF_JEQ | BPF_K, BPF_REG_AX, 21689 0, 1, 0), 21690 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 21691 BPF_MOV | BPF_K, insn->dst_reg, 21692 0, 0, 0), 21693 /* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */ 21694 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 21695 BPF_NEG | BPF_K, insn->dst_reg, 21696 0, 0, 0), 21697 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 21698 *insn, 21699 }; 21700 struct bpf_insn chk_and_smod[] = { 21701 /* [R,W]x mod 0 -> [R,W]x */ 21702 /* [R,W]x mod -1 -> 0 */ 21703 BPF_MOV64_REG(BPF_REG_AX, insn->src_reg), 21704 BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 21705 BPF_ADD | BPF_K, BPF_REG_AX, 21706 0, 0, 1), 21707 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 21708 BPF_JGT | BPF_K, BPF_REG_AX, 21709 0, 3, 1), 21710 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 21711 BPF_JEQ | BPF_K, BPF_REG_AX, 21712 0, 3 + (is64 ? 0 : 1), 1), 21713 BPF_MOV32_IMM(insn->dst_reg, 0), 21714 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 21715 *insn, 21716 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 21717 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 21718 }; 21719 21720 if (is_sdiv) { 21721 patchlet = chk_and_sdiv; 21722 cnt = ARRAY_SIZE(chk_and_sdiv); 21723 } else if (is_smod) { 21724 patchlet = chk_and_smod; 21725 cnt = ARRAY_SIZE(chk_and_smod) - (is64 ? 2 : 0); 21726 } else { 21727 patchlet = isdiv ? chk_and_div : chk_and_mod; 21728 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 21729 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 21730 } 21731 21732 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 21733 if (!new_prog) 21734 return -ENOMEM; 21735 21736 delta += cnt - 1; 21737 env->prog = prog = new_prog; 21738 insn = new_prog->insnsi + i + delta; 21739 goto next_insn; 21740 } 21741 21742 /* Make it impossible to de-reference a userspace address */ 21743 if (BPF_CLASS(insn->code) == BPF_LDX && 21744 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 21745 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) { 21746 struct bpf_insn *patch = &insn_buf[0]; 21747 u64 uaddress_limit = bpf_arch_uaddress_limit(); 21748 21749 if (!uaddress_limit) 21750 goto next_insn; 21751 21752 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 21753 if (insn->off) 21754 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off); 21755 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32); 21756 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2); 21757 *patch++ = *insn; 21758 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 21759 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0); 21760 21761 cnt = patch - insn_buf; 21762 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21763 if (!new_prog) 21764 return -ENOMEM; 21765 21766 delta += cnt - 1; 21767 env->prog = prog = new_prog; 21768 insn = new_prog->insnsi + i + delta; 21769 goto next_insn; 21770 } 21771 21772 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 21773 if (BPF_CLASS(insn->code) == BPF_LD && 21774 (BPF_MODE(insn->code) == BPF_ABS || 21775 BPF_MODE(insn->code) == BPF_IND)) { 21776 cnt = env->ops->gen_ld_abs(insn, insn_buf); 21777 if (cnt == 0 || cnt >= INSN_BUF_SIZE) { 21778 verbose(env, "bpf verifier is misconfigured\n"); 21779 return -EINVAL; 21780 } 21781 21782 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21783 if (!new_prog) 21784 return -ENOMEM; 21785 21786 delta += cnt - 1; 21787 env->prog = prog = new_prog; 21788 insn = new_prog->insnsi + i + delta; 21789 goto next_insn; 21790 } 21791 21792 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 21793 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 21794 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 21795 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 21796 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 21797 struct bpf_insn *patch = &insn_buf[0]; 21798 bool issrc, isneg, isimm; 21799 u32 off_reg; 21800 21801 aux = &env->insn_aux_data[i + delta]; 21802 if (!aux->alu_state || 21803 aux->alu_state == BPF_ALU_NON_POINTER) 21804 goto next_insn; 21805 21806 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 21807 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 21808 BPF_ALU_SANITIZE_SRC; 21809 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 21810 21811 off_reg = issrc ? insn->src_reg : insn->dst_reg; 21812 if (isimm) { 21813 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 21814 } else { 21815 if (isneg) 21816 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 21817 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 21818 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 21819 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 21820 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 21821 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 21822 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 21823 } 21824 if (!issrc) 21825 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 21826 insn->src_reg = BPF_REG_AX; 21827 if (isneg) 21828 insn->code = insn->code == code_add ? 21829 code_sub : code_add; 21830 *patch++ = *insn; 21831 if (issrc && isneg && !isimm) 21832 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 21833 cnt = patch - insn_buf; 21834 21835 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21836 if (!new_prog) 21837 return -ENOMEM; 21838 21839 delta += cnt - 1; 21840 env->prog = prog = new_prog; 21841 insn = new_prog->insnsi + i + delta; 21842 goto next_insn; 21843 } 21844 21845 if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) { 21846 int stack_off_cnt = -stack_depth - 16; 21847 21848 /* 21849 * Two 8 byte slots, depth-16 stores the count, and 21850 * depth-8 stores the start timestamp of the loop. 21851 * 21852 * The starting value of count is BPF_MAX_TIMED_LOOPS 21853 * (0xffff). Every iteration loads it and subs it by 1, 21854 * until the value becomes 0 in AX (thus, 1 in stack), 21855 * after which we call arch_bpf_timed_may_goto, which 21856 * either sets AX to 0xffff to keep looping, or to 0 21857 * upon timeout. AX is then stored into the stack. In 21858 * the next iteration, we either see 0 and break out, or 21859 * continue iterating until the next time value is 0 21860 * after subtraction, rinse and repeat. 21861 */ 21862 stack_depth_extra = 16; 21863 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt); 21864 if (insn->off >= 0) 21865 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5); 21866 else 21867 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 21868 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 21869 insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2); 21870 /* 21871 * AX is used as an argument to pass in stack_off_cnt 21872 * (to add to r10/fp), and also as the return value of 21873 * the call to arch_bpf_timed_may_goto. 21874 */ 21875 insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt); 21876 insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto); 21877 insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt); 21878 cnt = 7; 21879 21880 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21881 if (!new_prog) 21882 return -ENOMEM; 21883 21884 delta += cnt - 1; 21885 env->prog = prog = new_prog; 21886 insn = new_prog->insnsi + i + delta; 21887 goto next_insn; 21888 } else if (is_may_goto_insn(insn)) { 21889 int stack_off = -stack_depth - 8; 21890 21891 stack_depth_extra = 8; 21892 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 21893 if (insn->off >= 0) 21894 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 21895 else 21896 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 21897 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 21898 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 21899 cnt = 4; 21900 21901 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21902 if (!new_prog) 21903 return -ENOMEM; 21904 21905 delta += cnt - 1; 21906 env->prog = prog = new_prog; 21907 insn = new_prog->insnsi + i + delta; 21908 goto next_insn; 21909 } 21910 21911 if (insn->code != (BPF_JMP | BPF_CALL)) 21912 goto next_insn; 21913 if (insn->src_reg == BPF_PSEUDO_CALL) 21914 goto next_insn; 21915 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 21916 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 21917 if (ret) 21918 return ret; 21919 if (cnt == 0) 21920 goto next_insn; 21921 21922 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21923 if (!new_prog) 21924 return -ENOMEM; 21925 21926 delta += cnt - 1; 21927 env->prog = prog = new_prog; 21928 insn = new_prog->insnsi + i + delta; 21929 goto next_insn; 21930 } 21931 21932 /* Skip inlining the helper call if the JIT does it. */ 21933 if (bpf_jit_inlines_helper_call(insn->imm)) 21934 goto next_insn; 21935 21936 if (insn->imm == BPF_FUNC_get_route_realm) 21937 prog->dst_needed = 1; 21938 if (insn->imm == BPF_FUNC_get_prandom_u32) 21939 bpf_user_rnd_init_once(); 21940 if (insn->imm == BPF_FUNC_override_return) 21941 prog->kprobe_override = 1; 21942 if (insn->imm == BPF_FUNC_tail_call) { 21943 /* If we tail call into other programs, we 21944 * cannot make any assumptions since they can 21945 * be replaced dynamically during runtime in 21946 * the program array. 21947 */ 21948 prog->cb_access = 1; 21949 if (!allow_tail_call_in_subprogs(env)) 21950 prog->aux->stack_depth = MAX_BPF_STACK; 21951 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 21952 21953 /* mark bpf_tail_call as different opcode to avoid 21954 * conditional branch in the interpreter for every normal 21955 * call and to prevent accidental JITing by JIT compiler 21956 * that doesn't support bpf_tail_call yet 21957 */ 21958 insn->imm = 0; 21959 insn->code = BPF_JMP | BPF_TAIL_CALL; 21960 21961 aux = &env->insn_aux_data[i + delta]; 21962 if (env->bpf_capable && !prog->blinding_requested && 21963 prog->jit_requested && 21964 !bpf_map_key_poisoned(aux) && 21965 !bpf_map_ptr_poisoned(aux) && 21966 !bpf_map_ptr_unpriv(aux)) { 21967 struct bpf_jit_poke_descriptor desc = { 21968 .reason = BPF_POKE_REASON_TAIL_CALL, 21969 .tail_call.map = aux->map_ptr_state.map_ptr, 21970 .tail_call.key = bpf_map_key_immediate(aux), 21971 .insn_idx = i + delta, 21972 }; 21973 21974 ret = bpf_jit_add_poke_descriptor(prog, &desc); 21975 if (ret < 0) { 21976 verbose(env, "adding tail call poke descriptor failed\n"); 21977 return ret; 21978 } 21979 21980 insn->imm = ret + 1; 21981 goto next_insn; 21982 } 21983 21984 if (!bpf_map_ptr_unpriv(aux)) 21985 goto next_insn; 21986 21987 /* instead of changing every JIT dealing with tail_call 21988 * emit two extra insns: 21989 * if (index >= max_entries) goto out; 21990 * index &= array->index_mask; 21991 * to avoid out-of-bounds cpu speculation 21992 */ 21993 if (bpf_map_ptr_poisoned(aux)) { 21994 verbose(env, "tail_call abusing map_ptr\n"); 21995 return -EINVAL; 21996 } 21997 21998 map_ptr = aux->map_ptr_state.map_ptr; 21999 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 22000 map_ptr->max_entries, 2); 22001 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 22002 container_of(map_ptr, 22003 struct bpf_array, 22004 map)->index_mask); 22005 insn_buf[2] = *insn; 22006 cnt = 3; 22007 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22008 if (!new_prog) 22009 return -ENOMEM; 22010 22011 delta += cnt - 1; 22012 env->prog = prog = new_prog; 22013 insn = new_prog->insnsi + i + delta; 22014 goto next_insn; 22015 } 22016 22017 if (insn->imm == BPF_FUNC_timer_set_callback) { 22018 /* The verifier will process callback_fn as many times as necessary 22019 * with different maps and the register states prepared by 22020 * set_timer_callback_state will be accurate. 22021 * 22022 * The following use case is valid: 22023 * map1 is shared by prog1, prog2, prog3. 22024 * prog1 calls bpf_timer_init for some map1 elements 22025 * prog2 calls bpf_timer_set_callback for some map1 elements. 22026 * Those that were not bpf_timer_init-ed will return -EINVAL. 22027 * prog3 calls bpf_timer_start for some map1 elements. 22028 * Those that were not both bpf_timer_init-ed and 22029 * bpf_timer_set_callback-ed will return -EINVAL. 22030 */ 22031 struct bpf_insn ld_addrs[2] = { 22032 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 22033 }; 22034 22035 insn_buf[0] = ld_addrs[0]; 22036 insn_buf[1] = ld_addrs[1]; 22037 insn_buf[2] = *insn; 22038 cnt = 3; 22039 22040 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22041 if (!new_prog) 22042 return -ENOMEM; 22043 22044 delta += cnt - 1; 22045 env->prog = prog = new_prog; 22046 insn = new_prog->insnsi + i + delta; 22047 goto patch_call_imm; 22048 } 22049 22050 if (is_storage_get_function(insn->imm)) { 22051 if (!in_sleepable(env) || 22052 env->insn_aux_data[i + delta].storage_get_func_atomic) 22053 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 22054 else 22055 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 22056 insn_buf[1] = *insn; 22057 cnt = 2; 22058 22059 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22060 if (!new_prog) 22061 return -ENOMEM; 22062 22063 delta += cnt - 1; 22064 env->prog = prog = new_prog; 22065 insn = new_prog->insnsi + i + delta; 22066 goto patch_call_imm; 22067 } 22068 22069 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 22070 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 22071 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 22072 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 22073 */ 22074 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 22075 insn_buf[1] = *insn; 22076 cnt = 2; 22077 22078 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22079 if (!new_prog) 22080 return -ENOMEM; 22081 22082 delta += cnt - 1; 22083 env->prog = prog = new_prog; 22084 insn = new_prog->insnsi + i + delta; 22085 goto patch_call_imm; 22086 } 22087 22088 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 22089 * and other inlining handlers are currently limited to 64 bit 22090 * only. 22091 */ 22092 if (prog->jit_requested && BITS_PER_LONG == 64 && 22093 (insn->imm == BPF_FUNC_map_lookup_elem || 22094 insn->imm == BPF_FUNC_map_update_elem || 22095 insn->imm == BPF_FUNC_map_delete_elem || 22096 insn->imm == BPF_FUNC_map_push_elem || 22097 insn->imm == BPF_FUNC_map_pop_elem || 22098 insn->imm == BPF_FUNC_map_peek_elem || 22099 insn->imm == BPF_FUNC_redirect_map || 22100 insn->imm == BPF_FUNC_for_each_map_elem || 22101 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 22102 aux = &env->insn_aux_data[i + delta]; 22103 if (bpf_map_ptr_poisoned(aux)) 22104 goto patch_call_imm; 22105 22106 map_ptr = aux->map_ptr_state.map_ptr; 22107 ops = map_ptr->ops; 22108 if (insn->imm == BPF_FUNC_map_lookup_elem && 22109 ops->map_gen_lookup) { 22110 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 22111 if (cnt == -EOPNOTSUPP) 22112 goto patch_map_ops_generic; 22113 if (cnt <= 0 || cnt >= INSN_BUF_SIZE) { 22114 verbose(env, "bpf verifier is misconfigured\n"); 22115 return -EINVAL; 22116 } 22117 22118 new_prog = bpf_patch_insn_data(env, i + delta, 22119 insn_buf, cnt); 22120 if (!new_prog) 22121 return -ENOMEM; 22122 22123 delta += cnt - 1; 22124 env->prog = prog = new_prog; 22125 insn = new_prog->insnsi + i + delta; 22126 goto next_insn; 22127 } 22128 22129 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 22130 (void *(*)(struct bpf_map *map, void *key))NULL)); 22131 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 22132 (long (*)(struct bpf_map *map, void *key))NULL)); 22133 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 22134 (long (*)(struct bpf_map *map, void *key, void *value, 22135 u64 flags))NULL)); 22136 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 22137 (long (*)(struct bpf_map *map, void *value, 22138 u64 flags))NULL)); 22139 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 22140 (long (*)(struct bpf_map *map, void *value))NULL)); 22141 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 22142 (long (*)(struct bpf_map *map, void *value))NULL)); 22143 BUILD_BUG_ON(!__same_type(ops->map_redirect, 22144 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 22145 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 22146 (long (*)(struct bpf_map *map, 22147 bpf_callback_t callback_fn, 22148 void *callback_ctx, 22149 u64 flags))NULL)); 22150 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 22151 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 22152 22153 patch_map_ops_generic: 22154 switch (insn->imm) { 22155 case BPF_FUNC_map_lookup_elem: 22156 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 22157 goto next_insn; 22158 case BPF_FUNC_map_update_elem: 22159 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 22160 goto next_insn; 22161 case BPF_FUNC_map_delete_elem: 22162 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 22163 goto next_insn; 22164 case BPF_FUNC_map_push_elem: 22165 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 22166 goto next_insn; 22167 case BPF_FUNC_map_pop_elem: 22168 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 22169 goto next_insn; 22170 case BPF_FUNC_map_peek_elem: 22171 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 22172 goto next_insn; 22173 case BPF_FUNC_redirect_map: 22174 insn->imm = BPF_CALL_IMM(ops->map_redirect); 22175 goto next_insn; 22176 case BPF_FUNC_for_each_map_elem: 22177 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 22178 goto next_insn; 22179 case BPF_FUNC_map_lookup_percpu_elem: 22180 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 22181 goto next_insn; 22182 } 22183 22184 goto patch_call_imm; 22185 } 22186 22187 /* Implement bpf_jiffies64 inline. */ 22188 if (prog->jit_requested && BITS_PER_LONG == 64 && 22189 insn->imm == BPF_FUNC_jiffies64) { 22190 struct bpf_insn ld_jiffies_addr[2] = { 22191 BPF_LD_IMM64(BPF_REG_0, 22192 (unsigned long)&jiffies), 22193 }; 22194 22195 insn_buf[0] = ld_jiffies_addr[0]; 22196 insn_buf[1] = ld_jiffies_addr[1]; 22197 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 22198 BPF_REG_0, 0); 22199 cnt = 3; 22200 22201 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 22202 cnt); 22203 if (!new_prog) 22204 return -ENOMEM; 22205 22206 delta += cnt - 1; 22207 env->prog = prog = new_prog; 22208 insn = new_prog->insnsi + i + delta; 22209 goto next_insn; 22210 } 22211 22212 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML) 22213 /* Implement bpf_get_smp_processor_id() inline. */ 22214 if (insn->imm == BPF_FUNC_get_smp_processor_id && 22215 verifier_inlines_helper_call(env, insn->imm)) { 22216 /* BPF_FUNC_get_smp_processor_id inlining is an 22217 * optimization, so if cpu_number is ever 22218 * changed in some incompatible and hard to support 22219 * way, it's fine to back out this inlining logic 22220 */ 22221 #ifdef CONFIG_SMP 22222 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number); 22223 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 22224 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0); 22225 cnt = 3; 22226 #else 22227 insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0); 22228 cnt = 1; 22229 #endif 22230 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22231 if (!new_prog) 22232 return -ENOMEM; 22233 22234 delta += cnt - 1; 22235 env->prog = prog = new_prog; 22236 insn = new_prog->insnsi + i + delta; 22237 goto next_insn; 22238 } 22239 #endif 22240 /* Implement bpf_get_func_arg inline. */ 22241 if (prog_type == BPF_PROG_TYPE_TRACING && 22242 insn->imm == BPF_FUNC_get_func_arg) { 22243 /* Load nr_args from ctx - 8 */ 22244 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22245 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 22246 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 22247 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 22248 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 22249 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 22250 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 22251 insn_buf[7] = BPF_JMP_A(1); 22252 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 22253 cnt = 9; 22254 22255 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22256 if (!new_prog) 22257 return -ENOMEM; 22258 22259 delta += cnt - 1; 22260 env->prog = prog = new_prog; 22261 insn = new_prog->insnsi + i + delta; 22262 goto next_insn; 22263 } 22264 22265 /* Implement bpf_get_func_ret inline. */ 22266 if (prog_type == BPF_PROG_TYPE_TRACING && 22267 insn->imm == BPF_FUNC_get_func_ret) { 22268 if (eatype == BPF_TRACE_FEXIT || 22269 eatype == BPF_MODIFY_RETURN) { 22270 /* Load nr_args from ctx - 8 */ 22271 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22272 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 22273 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 22274 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 22275 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 22276 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 22277 cnt = 6; 22278 } else { 22279 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 22280 cnt = 1; 22281 } 22282 22283 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22284 if (!new_prog) 22285 return -ENOMEM; 22286 22287 delta += cnt - 1; 22288 env->prog = prog = new_prog; 22289 insn = new_prog->insnsi + i + delta; 22290 goto next_insn; 22291 } 22292 22293 /* Implement get_func_arg_cnt inline. */ 22294 if (prog_type == BPF_PROG_TYPE_TRACING && 22295 insn->imm == BPF_FUNC_get_func_arg_cnt) { 22296 /* Load nr_args from ctx - 8 */ 22297 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22298 22299 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 22300 if (!new_prog) 22301 return -ENOMEM; 22302 22303 env->prog = prog = new_prog; 22304 insn = new_prog->insnsi + i + delta; 22305 goto next_insn; 22306 } 22307 22308 /* Implement bpf_get_func_ip inline. */ 22309 if (prog_type == BPF_PROG_TYPE_TRACING && 22310 insn->imm == BPF_FUNC_get_func_ip) { 22311 /* Load IP address from ctx - 16 */ 22312 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 22313 22314 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 22315 if (!new_prog) 22316 return -ENOMEM; 22317 22318 env->prog = prog = new_prog; 22319 insn = new_prog->insnsi + i + delta; 22320 goto next_insn; 22321 } 22322 22323 /* Implement bpf_get_branch_snapshot inline. */ 22324 if (IS_ENABLED(CONFIG_PERF_EVENTS) && 22325 prog->jit_requested && BITS_PER_LONG == 64 && 22326 insn->imm == BPF_FUNC_get_branch_snapshot) { 22327 /* We are dealing with the following func protos: 22328 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags); 22329 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt); 22330 */ 22331 const u32 br_entry_size = sizeof(struct perf_branch_entry); 22332 22333 /* struct perf_branch_entry is part of UAPI and is 22334 * used as an array element, so extremely unlikely to 22335 * ever grow or shrink 22336 */ 22337 BUILD_BUG_ON(br_entry_size != 24); 22338 22339 /* if (unlikely(flags)) return -EINVAL */ 22340 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7); 22341 22342 /* Transform size (bytes) into number of entries (cnt = size / 24). 22343 * But to avoid expensive division instruction, we implement 22344 * divide-by-3 through multiplication, followed by further 22345 * division by 8 through 3-bit right shift. 22346 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr., 22347 * p. 227, chapter "Unsigned Division by 3" for details and proofs. 22348 * 22349 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab. 22350 */ 22351 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab); 22352 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0); 22353 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36); 22354 22355 /* call perf_snapshot_branch_stack implementation */ 22356 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack)); 22357 /* if (entry_cnt == 0) return -ENOENT */ 22358 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4); 22359 /* return entry_cnt * sizeof(struct perf_branch_entry) */ 22360 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size); 22361 insn_buf[7] = BPF_JMP_A(3); 22362 /* return -EINVAL; */ 22363 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 22364 insn_buf[9] = BPF_JMP_A(1); 22365 /* return -ENOENT; */ 22366 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT); 22367 cnt = 11; 22368 22369 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22370 if (!new_prog) 22371 return -ENOMEM; 22372 22373 delta += cnt - 1; 22374 env->prog = prog = new_prog; 22375 insn = new_prog->insnsi + i + delta; 22376 goto next_insn; 22377 } 22378 22379 /* Implement bpf_kptr_xchg inline */ 22380 if (prog->jit_requested && BITS_PER_LONG == 64 && 22381 insn->imm == BPF_FUNC_kptr_xchg && 22382 bpf_jit_supports_ptr_xchg()) { 22383 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 22384 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 22385 cnt = 2; 22386 22387 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22388 if (!new_prog) 22389 return -ENOMEM; 22390 22391 delta += cnt - 1; 22392 env->prog = prog = new_prog; 22393 insn = new_prog->insnsi + i + delta; 22394 goto next_insn; 22395 } 22396 patch_call_imm: 22397 fn = env->ops->get_func_proto(insn->imm, env->prog); 22398 /* all functions that have prototype and verifier allowed 22399 * programs to call them, must be real in-kernel functions 22400 */ 22401 if (!fn->func) { 22402 verbose(env, 22403 "kernel subsystem misconfigured func %s#%d\n", 22404 func_id_name(insn->imm), insn->imm); 22405 return -EFAULT; 22406 } 22407 insn->imm = fn->func - __bpf_call_base; 22408 next_insn: 22409 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 22410 subprogs[cur_subprog].stack_depth += stack_depth_extra; 22411 subprogs[cur_subprog].stack_extra = stack_depth_extra; 22412 22413 stack_depth = subprogs[cur_subprog].stack_depth; 22414 if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) { 22415 verbose(env, "stack size %d(extra %d) is too large\n", 22416 stack_depth, stack_depth_extra); 22417 return -EINVAL; 22418 } 22419 cur_subprog++; 22420 stack_depth = subprogs[cur_subprog].stack_depth; 22421 stack_depth_extra = 0; 22422 } 22423 i++; 22424 insn++; 22425 } 22426 22427 env->prog->aux->stack_depth = subprogs[0].stack_depth; 22428 for (i = 0; i < env->subprog_cnt; i++) { 22429 int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1; 22430 int subprog_start = subprogs[i].start; 22431 int stack_slots = subprogs[i].stack_extra / 8; 22432 int slots = delta, cnt = 0; 22433 22434 if (!stack_slots) 22435 continue; 22436 /* We need two slots in case timed may_goto is supported. */ 22437 if (stack_slots > slots) { 22438 verifier_bug(env, "stack_slots supports may_goto only"); 22439 return -EFAULT; 22440 } 22441 22442 stack_depth = subprogs[i].stack_depth; 22443 if (bpf_jit_supports_timed_may_goto()) { 22444 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth, 22445 BPF_MAX_TIMED_LOOPS); 22446 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0); 22447 } else { 22448 /* Add ST insn to subprog prologue to init extra stack */ 22449 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth, 22450 BPF_MAX_LOOPS); 22451 } 22452 /* Copy first actual insn to preserve it */ 22453 insn_buf[cnt++] = env->prog->insnsi[subprog_start]; 22454 22455 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt); 22456 if (!new_prog) 22457 return -ENOMEM; 22458 env->prog = prog = new_prog; 22459 /* 22460 * If may_goto is a first insn of a prog there could be a jmp 22461 * insn that points to it, hence adjust all such jmps to point 22462 * to insn after BPF_ST that inits may_goto count. 22463 * Adjustment will succeed because bpf_patch_insn_data() didn't fail. 22464 */ 22465 WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta)); 22466 } 22467 22468 /* Since poke tab is now finalized, publish aux to tracker. */ 22469 for (i = 0; i < prog->aux->size_poke_tab; i++) { 22470 map_ptr = prog->aux->poke_tab[i].tail_call.map; 22471 if (!map_ptr->ops->map_poke_track || 22472 !map_ptr->ops->map_poke_untrack || 22473 !map_ptr->ops->map_poke_run) { 22474 verbose(env, "bpf verifier is misconfigured\n"); 22475 return -EINVAL; 22476 } 22477 22478 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 22479 if (ret < 0) { 22480 verbose(env, "tracking tail call prog failed\n"); 22481 return ret; 22482 } 22483 } 22484 22485 sort_kfunc_descs_by_imm_off(env->prog); 22486 22487 return 0; 22488 } 22489 22490 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 22491 int position, 22492 s32 stack_base, 22493 u32 callback_subprogno, 22494 u32 *total_cnt) 22495 { 22496 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 22497 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 22498 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 22499 int reg_loop_max = BPF_REG_6; 22500 int reg_loop_cnt = BPF_REG_7; 22501 int reg_loop_ctx = BPF_REG_8; 22502 22503 struct bpf_insn *insn_buf = env->insn_buf; 22504 struct bpf_prog *new_prog; 22505 u32 callback_start; 22506 u32 call_insn_offset; 22507 s32 callback_offset; 22508 u32 cnt = 0; 22509 22510 /* This represents an inlined version of bpf_iter.c:bpf_loop, 22511 * be careful to modify this code in sync. 22512 */ 22513 22514 /* Return error and jump to the end of the patch if 22515 * expected number of iterations is too big. 22516 */ 22517 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2); 22518 insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG); 22519 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16); 22520 /* spill R6, R7, R8 to use these as loop vars */ 22521 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset); 22522 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset); 22523 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset); 22524 /* initialize loop vars */ 22525 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1); 22526 insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0); 22527 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3); 22528 /* loop header, 22529 * if reg_loop_cnt >= reg_loop_max skip the loop body 22530 */ 22531 insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5); 22532 /* callback call, 22533 * correct callback offset would be set after patching 22534 */ 22535 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt); 22536 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx); 22537 insn_buf[cnt++] = BPF_CALL_REL(0); 22538 /* increment loop counter */ 22539 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1); 22540 /* jump to loop header if callback returned 0 */ 22541 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6); 22542 /* return value of bpf_loop, 22543 * set R0 to the number of iterations 22544 */ 22545 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt); 22546 /* restore original values of R6, R7, R8 */ 22547 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset); 22548 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset); 22549 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset); 22550 22551 *total_cnt = cnt; 22552 new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt); 22553 if (!new_prog) 22554 return new_prog; 22555 22556 /* callback start is known only after patching */ 22557 callback_start = env->subprog_info[callback_subprogno].start; 22558 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 22559 call_insn_offset = position + 12; 22560 callback_offset = callback_start - call_insn_offset - 1; 22561 new_prog->insnsi[call_insn_offset].imm = callback_offset; 22562 22563 return new_prog; 22564 } 22565 22566 static bool is_bpf_loop_call(struct bpf_insn *insn) 22567 { 22568 return insn->code == (BPF_JMP | BPF_CALL) && 22569 insn->src_reg == 0 && 22570 insn->imm == BPF_FUNC_loop; 22571 } 22572 22573 /* For all sub-programs in the program (including main) check 22574 * insn_aux_data to see if there are bpf_loop calls that require 22575 * inlining. If such calls are found the calls are replaced with a 22576 * sequence of instructions produced by `inline_bpf_loop` function and 22577 * subprog stack_depth is increased by the size of 3 registers. 22578 * This stack space is used to spill values of the R6, R7, R8. These 22579 * registers are used to store the loop bound, counter and context 22580 * variables. 22581 */ 22582 static int optimize_bpf_loop(struct bpf_verifier_env *env) 22583 { 22584 struct bpf_subprog_info *subprogs = env->subprog_info; 22585 int i, cur_subprog = 0, cnt, delta = 0; 22586 struct bpf_insn *insn = env->prog->insnsi; 22587 int insn_cnt = env->prog->len; 22588 u16 stack_depth = subprogs[cur_subprog].stack_depth; 22589 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 22590 u16 stack_depth_extra = 0; 22591 22592 for (i = 0; i < insn_cnt; i++, insn++) { 22593 struct bpf_loop_inline_state *inline_state = 22594 &env->insn_aux_data[i + delta].loop_inline_state; 22595 22596 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 22597 struct bpf_prog *new_prog; 22598 22599 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 22600 new_prog = inline_bpf_loop(env, 22601 i + delta, 22602 -(stack_depth + stack_depth_extra), 22603 inline_state->callback_subprogno, 22604 &cnt); 22605 if (!new_prog) 22606 return -ENOMEM; 22607 22608 delta += cnt - 1; 22609 env->prog = new_prog; 22610 insn = new_prog->insnsi + i + delta; 22611 } 22612 22613 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 22614 subprogs[cur_subprog].stack_depth += stack_depth_extra; 22615 cur_subprog++; 22616 stack_depth = subprogs[cur_subprog].stack_depth; 22617 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 22618 stack_depth_extra = 0; 22619 } 22620 } 22621 22622 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 22623 22624 return 0; 22625 } 22626 22627 /* Remove unnecessary spill/fill pairs, members of fastcall pattern, 22628 * adjust subprograms stack depth when possible. 22629 */ 22630 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env) 22631 { 22632 struct bpf_subprog_info *subprog = env->subprog_info; 22633 struct bpf_insn_aux_data *aux = env->insn_aux_data; 22634 struct bpf_insn *insn = env->prog->insnsi; 22635 int insn_cnt = env->prog->len; 22636 u32 spills_num; 22637 bool modified = false; 22638 int i, j; 22639 22640 for (i = 0; i < insn_cnt; i++, insn++) { 22641 if (aux[i].fastcall_spills_num > 0) { 22642 spills_num = aux[i].fastcall_spills_num; 22643 /* NOPs would be removed by opt_remove_nops() */ 22644 for (j = 1; j <= spills_num; ++j) { 22645 *(insn - j) = NOP; 22646 *(insn + j) = NOP; 22647 } 22648 modified = true; 22649 } 22650 if ((subprog + 1)->start == i + 1) { 22651 if (modified && !subprog->keep_fastcall_stack) 22652 subprog->stack_depth = -subprog->fastcall_stack_off; 22653 subprog++; 22654 modified = false; 22655 } 22656 } 22657 22658 return 0; 22659 } 22660 22661 static void free_states(struct bpf_verifier_env *env) 22662 { 22663 struct bpf_verifier_state_list *sl; 22664 struct list_head *head, *pos, *tmp; 22665 int i; 22666 22667 list_for_each_safe(pos, tmp, &env->free_list) { 22668 sl = container_of(pos, struct bpf_verifier_state_list, node); 22669 free_verifier_state(&sl->state, false); 22670 kfree(sl); 22671 } 22672 INIT_LIST_HEAD(&env->free_list); 22673 22674 if (!env->explored_states) 22675 return; 22676 22677 for (i = 0; i < state_htab_size(env); i++) { 22678 head = &env->explored_states[i]; 22679 22680 list_for_each_safe(pos, tmp, head) { 22681 sl = container_of(pos, struct bpf_verifier_state_list, node); 22682 free_verifier_state(&sl->state, false); 22683 kfree(sl); 22684 } 22685 INIT_LIST_HEAD(&env->explored_states[i]); 22686 } 22687 } 22688 22689 static int do_check_common(struct bpf_verifier_env *env, int subprog) 22690 { 22691 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 22692 struct bpf_subprog_info *sub = subprog_info(env, subprog); 22693 struct bpf_prog_aux *aux = env->prog->aux; 22694 struct bpf_verifier_state *state; 22695 struct bpf_reg_state *regs; 22696 int ret, i; 22697 22698 env->prev_linfo = NULL; 22699 env->pass_cnt++; 22700 22701 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 22702 if (!state) 22703 return -ENOMEM; 22704 state->curframe = 0; 22705 state->speculative = false; 22706 state->branches = 1; 22707 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 22708 if (!state->frame[0]) { 22709 kfree(state); 22710 return -ENOMEM; 22711 } 22712 env->cur_state = state; 22713 init_func_state(env, state->frame[0], 22714 BPF_MAIN_FUNC /* callsite */, 22715 0 /* frameno */, 22716 subprog); 22717 state->first_insn_idx = env->subprog_info[subprog].start; 22718 state->last_insn_idx = -1; 22719 22720 regs = state->frame[state->curframe]->regs; 22721 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 22722 const char *sub_name = subprog_name(env, subprog); 22723 struct bpf_subprog_arg_info *arg; 22724 struct bpf_reg_state *reg; 22725 22726 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 22727 ret = btf_prepare_func_args(env, subprog); 22728 if (ret) 22729 goto out; 22730 22731 if (subprog_is_exc_cb(env, subprog)) { 22732 state->frame[0]->in_exception_callback_fn = true; 22733 /* We have already ensured that the callback returns an integer, just 22734 * like all global subprogs. We need to determine it only has a single 22735 * scalar argument. 22736 */ 22737 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 22738 verbose(env, "exception cb only supports single integer argument\n"); 22739 ret = -EINVAL; 22740 goto out; 22741 } 22742 } 22743 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 22744 arg = &sub->args[i - BPF_REG_1]; 22745 reg = ®s[i]; 22746 22747 if (arg->arg_type == ARG_PTR_TO_CTX) { 22748 reg->type = PTR_TO_CTX; 22749 mark_reg_known_zero(env, regs, i); 22750 } else if (arg->arg_type == ARG_ANYTHING) { 22751 reg->type = SCALAR_VALUE; 22752 mark_reg_unknown(env, regs, i); 22753 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 22754 /* assume unspecial LOCAL dynptr type */ 22755 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 22756 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 22757 reg->type = PTR_TO_MEM; 22758 if (arg->arg_type & PTR_MAYBE_NULL) 22759 reg->type |= PTR_MAYBE_NULL; 22760 mark_reg_known_zero(env, regs, i); 22761 reg->mem_size = arg->mem_size; 22762 reg->id = ++env->id_gen; 22763 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 22764 reg->type = PTR_TO_BTF_ID; 22765 if (arg->arg_type & PTR_MAYBE_NULL) 22766 reg->type |= PTR_MAYBE_NULL; 22767 if (arg->arg_type & PTR_UNTRUSTED) 22768 reg->type |= PTR_UNTRUSTED; 22769 if (arg->arg_type & PTR_TRUSTED) 22770 reg->type |= PTR_TRUSTED; 22771 mark_reg_known_zero(env, regs, i); 22772 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 22773 reg->btf_id = arg->btf_id; 22774 reg->id = ++env->id_gen; 22775 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 22776 /* caller can pass either PTR_TO_ARENA or SCALAR */ 22777 mark_reg_unknown(env, regs, i); 22778 } else { 22779 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 22780 i - BPF_REG_1, arg->arg_type); 22781 ret = -EFAULT; 22782 goto out; 22783 } 22784 } 22785 } else { 22786 /* if main BPF program has associated BTF info, validate that 22787 * it's matching expected signature, and otherwise mark BTF 22788 * info for main program as unreliable 22789 */ 22790 if (env->prog->aux->func_info_aux) { 22791 ret = btf_prepare_func_args(env, 0); 22792 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 22793 env->prog->aux->func_info_aux[0].unreliable = true; 22794 } 22795 22796 /* 1st arg to a function */ 22797 regs[BPF_REG_1].type = PTR_TO_CTX; 22798 mark_reg_known_zero(env, regs, BPF_REG_1); 22799 } 22800 22801 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 22802 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 22803 for (i = 0; i < aux->ctx_arg_info_size; i++) 22804 aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ? 22805 acquire_reference(env, 0) : 0; 22806 } 22807 22808 ret = do_check(env); 22809 out: 22810 /* check for NULL is necessary, since cur_state can be freed inside 22811 * do_check() under memory pressure. 22812 */ 22813 if (env->cur_state) { 22814 free_verifier_state(env->cur_state, true); 22815 env->cur_state = NULL; 22816 } 22817 while (!pop_stack(env, NULL, NULL, false)); 22818 if (!ret && pop_log) 22819 bpf_vlog_reset(&env->log, 0); 22820 free_states(env); 22821 return ret; 22822 } 22823 22824 /* Lazily verify all global functions based on their BTF, if they are called 22825 * from main BPF program or any of subprograms transitively. 22826 * BPF global subprogs called from dead code are not validated. 22827 * All callable global functions must pass verification. 22828 * Otherwise the whole program is rejected. 22829 * Consider: 22830 * int bar(int); 22831 * int foo(int f) 22832 * { 22833 * return bar(f); 22834 * } 22835 * int bar(int b) 22836 * { 22837 * ... 22838 * } 22839 * foo() will be verified first for R1=any_scalar_value. During verification it 22840 * will be assumed that bar() already verified successfully and call to bar() 22841 * from foo() will be checked for type match only. Later bar() will be verified 22842 * independently to check that it's safe for R1=any_scalar_value. 22843 */ 22844 static int do_check_subprogs(struct bpf_verifier_env *env) 22845 { 22846 struct bpf_prog_aux *aux = env->prog->aux; 22847 struct bpf_func_info_aux *sub_aux; 22848 int i, ret, new_cnt; 22849 22850 if (!aux->func_info) 22851 return 0; 22852 22853 /* exception callback is presumed to be always called */ 22854 if (env->exception_callback_subprog) 22855 subprog_aux(env, env->exception_callback_subprog)->called = true; 22856 22857 again: 22858 new_cnt = 0; 22859 for (i = 1; i < env->subprog_cnt; i++) { 22860 if (!subprog_is_global(env, i)) 22861 continue; 22862 22863 sub_aux = subprog_aux(env, i); 22864 if (!sub_aux->called || sub_aux->verified) 22865 continue; 22866 22867 env->insn_idx = env->subprog_info[i].start; 22868 WARN_ON_ONCE(env->insn_idx == 0); 22869 ret = do_check_common(env, i); 22870 if (ret) { 22871 return ret; 22872 } else if (env->log.level & BPF_LOG_LEVEL) { 22873 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 22874 i, subprog_name(env, i)); 22875 } 22876 22877 /* We verified new global subprog, it might have called some 22878 * more global subprogs that we haven't verified yet, so we 22879 * need to do another pass over subprogs to verify those. 22880 */ 22881 sub_aux->verified = true; 22882 new_cnt++; 22883 } 22884 22885 /* We can't loop forever as we verify at least one global subprog on 22886 * each pass. 22887 */ 22888 if (new_cnt) 22889 goto again; 22890 22891 return 0; 22892 } 22893 22894 static int do_check_main(struct bpf_verifier_env *env) 22895 { 22896 int ret; 22897 22898 env->insn_idx = 0; 22899 ret = do_check_common(env, 0); 22900 if (!ret) 22901 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 22902 return ret; 22903 } 22904 22905 22906 static void print_verification_stats(struct bpf_verifier_env *env) 22907 { 22908 int i; 22909 22910 if (env->log.level & BPF_LOG_STATS) { 22911 verbose(env, "verification time %lld usec\n", 22912 div_u64(env->verification_time, 1000)); 22913 verbose(env, "stack depth "); 22914 for (i = 0; i < env->subprog_cnt; i++) { 22915 u32 depth = env->subprog_info[i].stack_depth; 22916 22917 verbose(env, "%d", depth); 22918 if (i + 1 < env->subprog_cnt) 22919 verbose(env, "+"); 22920 } 22921 verbose(env, "\n"); 22922 } 22923 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 22924 "total_states %d peak_states %d mark_read %d\n", 22925 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 22926 env->max_states_per_insn, env->total_states, 22927 env->peak_states, env->longest_mark_read_walk); 22928 } 22929 22930 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 22931 const struct bpf_ctx_arg_aux *info, u32 cnt) 22932 { 22933 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL); 22934 prog->aux->ctx_arg_info_size = cnt; 22935 22936 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 22937 } 22938 22939 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 22940 { 22941 const struct btf_type *t, *func_proto; 22942 const struct bpf_struct_ops_desc *st_ops_desc; 22943 const struct bpf_struct_ops *st_ops; 22944 const struct btf_member *member; 22945 struct bpf_prog *prog = env->prog; 22946 bool has_refcounted_arg = false; 22947 u32 btf_id, member_idx, member_off; 22948 struct btf *btf; 22949 const char *mname; 22950 int i, err; 22951 22952 if (!prog->gpl_compatible) { 22953 verbose(env, "struct ops programs must have a GPL compatible license\n"); 22954 return -EINVAL; 22955 } 22956 22957 if (!prog->aux->attach_btf_id) 22958 return -ENOTSUPP; 22959 22960 btf = prog->aux->attach_btf; 22961 if (btf_is_module(btf)) { 22962 /* Make sure st_ops is valid through the lifetime of env */ 22963 env->attach_btf_mod = btf_try_get_module(btf); 22964 if (!env->attach_btf_mod) { 22965 verbose(env, "struct_ops module %s is not found\n", 22966 btf_get_name(btf)); 22967 return -ENOTSUPP; 22968 } 22969 } 22970 22971 btf_id = prog->aux->attach_btf_id; 22972 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 22973 if (!st_ops_desc) { 22974 verbose(env, "attach_btf_id %u is not a supported struct\n", 22975 btf_id); 22976 return -ENOTSUPP; 22977 } 22978 st_ops = st_ops_desc->st_ops; 22979 22980 t = st_ops_desc->type; 22981 member_idx = prog->expected_attach_type; 22982 if (member_idx >= btf_type_vlen(t)) { 22983 verbose(env, "attach to invalid member idx %u of struct %s\n", 22984 member_idx, st_ops->name); 22985 return -EINVAL; 22986 } 22987 22988 member = &btf_type_member(t)[member_idx]; 22989 mname = btf_name_by_offset(btf, member->name_off); 22990 func_proto = btf_type_resolve_func_ptr(btf, member->type, 22991 NULL); 22992 if (!func_proto) { 22993 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 22994 mname, member_idx, st_ops->name); 22995 return -EINVAL; 22996 } 22997 22998 member_off = __btf_member_bit_offset(t, member) / 8; 22999 err = bpf_struct_ops_supported(st_ops, member_off); 23000 if (err) { 23001 verbose(env, "attach to unsupported member %s of struct %s\n", 23002 mname, st_ops->name); 23003 return err; 23004 } 23005 23006 if (st_ops->check_member) { 23007 err = st_ops->check_member(t, member, prog); 23008 23009 if (err) { 23010 verbose(env, "attach to unsupported member %s of struct %s\n", 23011 mname, st_ops->name); 23012 return err; 23013 } 23014 } 23015 23016 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 23017 verbose(env, "Private stack not supported by jit\n"); 23018 return -EACCES; 23019 } 23020 23021 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) { 23022 if (st_ops_desc->arg_info[member_idx].info->refcounted) { 23023 has_refcounted_arg = true; 23024 break; 23025 } 23026 } 23027 23028 /* Tail call is not allowed for programs with refcounted arguments since we 23029 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 23030 */ 23031 for (i = 0; i < env->subprog_cnt; i++) { 23032 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 23033 verbose(env, "program with __ref argument cannot tail call\n"); 23034 return -EINVAL; 23035 } 23036 } 23037 23038 prog->aux->st_ops = st_ops; 23039 prog->aux->attach_st_ops_member_off = member_off; 23040 23041 prog->aux->attach_func_proto = func_proto; 23042 prog->aux->attach_func_name = mname; 23043 env->ops = st_ops->verifier_ops; 23044 23045 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info, 23046 st_ops_desc->arg_info[member_idx].cnt); 23047 } 23048 #define SECURITY_PREFIX "security_" 23049 23050 static int check_attach_modify_return(unsigned long addr, const char *func_name) 23051 { 23052 if (within_error_injection_list(addr) || 23053 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 23054 return 0; 23055 23056 return -EINVAL; 23057 } 23058 23059 /* list of non-sleepable functions that are otherwise on 23060 * ALLOW_ERROR_INJECTION list 23061 */ 23062 BTF_SET_START(btf_non_sleepable_error_inject) 23063 /* Three functions below can be called from sleepable and non-sleepable context. 23064 * Assume non-sleepable from bpf safety point of view. 23065 */ 23066 BTF_ID(func, __filemap_add_folio) 23067 #ifdef CONFIG_FAIL_PAGE_ALLOC 23068 BTF_ID(func, should_fail_alloc_page) 23069 #endif 23070 #ifdef CONFIG_FAILSLAB 23071 BTF_ID(func, should_failslab) 23072 #endif 23073 BTF_SET_END(btf_non_sleepable_error_inject) 23074 23075 static int check_non_sleepable_error_inject(u32 btf_id) 23076 { 23077 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 23078 } 23079 23080 int bpf_check_attach_target(struct bpf_verifier_log *log, 23081 const struct bpf_prog *prog, 23082 const struct bpf_prog *tgt_prog, 23083 u32 btf_id, 23084 struct bpf_attach_target_info *tgt_info) 23085 { 23086 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 23087 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 23088 char trace_symbol[KSYM_SYMBOL_LEN]; 23089 const char prefix[] = "btf_trace_"; 23090 struct bpf_raw_event_map *btp; 23091 int ret = 0, subprog = -1, i; 23092 const struct btf_type *t; 23093 bool conservative = true; 23094 const char *tname, *fname; 23095 struct btf *btf; 23096 long addr = 0; 23097 struct module *mod = NULL; 23098 23099 if (!btf_id) { 23100 bpf_log(log, "Tracing programs must provide btf_id\n"); 23101 return -EINVAL; 23102 } 23103 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 23104 if (!btf) { 23105 bpf_log(log, 23106 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 23107 return -EINVAL; 23108 } 23109 t = btf_type_by_id(btf, btf_id); 23110 if (!t) { 23111 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 23112 return -EINVAL; 23113 } 23114 tname = btf_name_by_offset(btf, t->name_off); 23115 if (!tname) { 23116 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 23117 return -EINVAL; 23118 } 23119 if (tgt_prog) { 23120 struct bpf_prog_aux *aux = tgt_prog->aux; 23121 bool tgt_changes_pkt_data; 23122 bool tgt_might_sleep; 23123 23124 if (bpf_prog_is_dev_bound(prog->aux) && 23125 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 23126 bpf_log(log, "Target program bound device mismatch"); 23127 return -EINVAL; 23128 } 23129 23130 for (i = 0; i < aux->func_info_cnt; i++) 23131 if (aux->func_info[i].type_id == btf_id) { 23132 subprog = i; 23133 break; 23134 } 23135 if (subprog == -1) { 23136 bpf_log(log, "Subprog %s doesn't exist\n", tname); 23137 return -EINVAL; 23138 } 23139 if (aux->func && aux->func[subprog]->aux->exception_cb) { 23140 bpf_log(log, 23141 "%s programs cannot attach to exception callback\n", 23142 prog_extension ? "Extension" : "FENTRY/FEXIT"); 23143 return -EINVAL; 23144 } 23145 conservative = aux->func_info_aux[subprog].unreliable; 23146 if (prog_extension) { 23147 if (conservative) { 23148 bpf_log(log, 23149 "Cannot replace static functions\n"); 23150 return -EINVAL; 23151 } 23152 if (!prog->jit_requested) { 23153 bpf_log(log, 23154 "Extension programs should be JITed\n"); 23155 return -EINVAL; 23156 } 23157 tgt_changes_pkt_data = aux->func 23158 ? aux->func[subprog]->aux->changes_pkt_data 23159 : aux->changes_pkt_data; 23160 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 23161 bpf_log(log, 23162 "Extension program changes packet data, while original does not\n"); 23163 return -EINVAL; 23164 } 23165 23166 tgt_might_sleep = aux->func 23167 ? aux->func[subprog]->aux->might_sleep 23168 : aux->might_sleep; 23169 if (prog->aux->might_sleep && !tgt_might_sleep) { 23170 bpf_log(log, 23171 "Extension program may sleep, while original does not\n"); 23172 return -EINVAL; 23173 } 23174 } 23175 if (!tgt_prog->jited) { 23176 bpf_log(log, "Can attach to only JITed progs\n"); 23177 return -EINVAL; 23178 } 23179 if (prog_tracing) { 23180 if (aux->attach_tracing_prog) { 23181 /* 23182 * Target program is an fentry/fexit which is already attached 23183 * to another tracing program. More levels of nesting 23184 * attachment are not allowed. 23185 */ 23186 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 23187 return -EINVAL; 23188 } 23189 } else if (tgt_prog->type == prog->type) { 23190 /* 23191 * To avoid potential call chain cycles, prevent attaching of a 23192 * program extension to another extension. It's ok to attach 23193 * fentry/fexit to extension program. 23194 */ 23195 bpf_log(log, "Cannot recursively attach\n"); 23196 return -EINVAL; 23197 } 23198 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 23199 prog_extension && 23200 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 23201 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 23202 /* Program extensions can extend all program types 23203 * except fentry/fexit. The reason is the following. 23204 * The fentry/fexit programs are used for performance 23205 * analysis, stats and can be attached to any program 23206 * type. When extension program is replacing XDP function 23207 * it is necessary to allow performance analysis of all 23208 * functions. Both original XDP program and its program 23209 * extension. Hence attaching fentry/fexit to 23210 * BPF_PROG_TYPE_EXT is allowed. If extending of 23211 * fentry/fexit was allowed it would be possible to create 23212 * long call chain fentry->extension->fentry->extension 23213 * beyond reasonable stack size. Hence extending fentry 23214 * is not allowed. 23215 */ 23216 bpf_log(log, "Cannot extend fentry/fexit\n"); 23217 return -EINVAL; 23218 } 23219 } else { 23220 if (prog_extension) { 23221 bpf_log(log, "Cannot replace kernel functions\n"); 23222 return -EINVAL; 23223 } 23224 } 23225 23226 switch (prog->expected_attach_type) { 23227 case BPF_TRACE_RAW_TP: 23228 if (tgt_prog) { 23229 bpf_log(log, 23230 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 23231 return -EINVAL; 23232 } 23233 if (!btf_type_is_typedef(t)) { 23234 bpf_log(log, "attach_btf_id %u is not a typedef\n", 23235 btf_id); 23236 return -EINVAL; 23237 } 23238 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 23239 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 23240 btf_id, tname); 23241 return -EINVAL; 23242 } 23243 tname += sizeof(prefix) - 1; 23244 23245 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 23246 * names. Thus using bpf_raw_event_map to get argument names. 23247 */ 23248 btp = bpf_get_raw_tracepoint(tname); 23249 if (!btp) 23250 return -EINVAL; 23251 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 23252 trace_symbol); 23253 bpf_put_raw_tracepoint(btp); 23254 23255 if (fname) 23256 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 23257 23258 if (!fname || ret < 0) { 23259 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 23260 prefix, tname); 23261 t = btf_type_by_id(btf, t->type); 23262 if (!btf_type_is_ptr(t)) 23263 /* should never happen in valid vmlinux build */ 23264 return -EINVAL; 23265 } else { 23266 t = btf_type_by_id(btf, ret); 23267 if (!btf_type_is_func(t)) 23268 /* should never happen in valid vmlinux build */ 23269 return -EINVAL; 23270 } 23271 23272 t = btf_type_by_id(btf, t->type); 23273 if (!btf_type_is_func_proto(t)) 23274 /* should never happen in valid vmlinux build */ 23275 return -EINVAL; 23276 23277 break; 23278 case BPF_TRACE_ITER: 23279 if (!btf_type_is_func(t)) { 23280 bpf_log(log, "attach_btf_id %u is not a function\n", 23281 btf_id); 23282 return -EINVAL; 23283 } 23284 t = btf_type_by_id(btf, t->type); 23285 if (!btf_type_is_func_proto(t)) 23286 return -EINVAL; 23287 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 23288 if (ret) 23289 return ret; 23290 break; 23291 default: 23292 if (!prog_extension) 23293 return -EINVAL; 23294 fallthrough; 23295 case BPF_MODIFY_RETURN: 23296 case BPF_LSM_MAC: 23297 case BPF_LSM_CGROUP: 23298 case BPF_TRACE_FENTRY: 23299 case BPF_TRACE_FEXIT: 23300 if (!btf_type_is_func(t)) { 23301 bpf_log(log, "attach_btf_id %u is not a function\n", 23302 btf_id); 23303 return -EINVAL; 23304 } 23305 if (prog_extension && 23306 btf_check_type_match(log, prog, btf, t)) 23307 return -EINVAL; 23308 t = btf_type_by_id(btf, t->type); 23309 if (!btf_type_is_func_proto(t)) 23310 return -EINVAL; 23311 23312 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 23313 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 23314 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 23315 return -EINVAL; 23316 23317 if (tgt_prog && conservative) 23318 t = NULL; 23319 23320 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 23321 if (ret < 0) 23322 return ret; 23323 23324 if (tgt_prog) { 23325 if (subprog == 0) 23326 addr = (long) tgt_prog->bpf_func; 23327 else 23328 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 23329 } else { 23330 if (btf_is_module(btf)) { 23331 mod = btf_try_get_module(btf); 23332 if (mod) 23333 addr = find_kallsyms_symbol_value(mod, tname); 23334 else 23335 addr = 0; 23336 } else { 23337 addr = kallsyms_lookup_name(tname); 23338 } 23339 if (!addr) { 23340 module_put(mod); 23341 bpf_log(log, 23342 "The address of function %s cannot be found\n", 23343 tname); 23344 return -ENOENT; 23345 } 23346 } 23347 23348 if (prog->sleepable) { 23349 ret = -EINVAL; 23350 switch (prog->type) { 23351 case BPF_PROG_TYPE_TRACING: 23352 23353 /* fentry/fexit/fmod_ret progs can be sleepable if they are 23354 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 23355 */ 23356 if (!check_non_sleepable_error_inject(btf_id) && 23357 within_error_injection_list(addr)) 23358 ret = 0; 23359 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 23360 * in the fmodret id set with the KF_SLEEPABLE flag. 23361 */ 23362 else { 23363 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 23364 prog); 23365 23366 if (flags && (*flags & KF_SLEEPABLE)) 23367 ret = 0; 23368 } 23369 break; 23370 case BPF_PROG_TYPE_LSM: 23371 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 23372 * Only some of them are sleepable. 23373 */ 23374 if (bpf_lsm_is_sleepable_hook(btf_id)) 23375 ret = 0; 23376 break; 23377 default: 23378 break; 23379 } 23380 if (ret) { 23381 module_put(mod); 23382 bpf_log(log, "%s is not sleepable\n", tname); 23383 return ret; 23384 } 23385 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 23386 if (tgt_prog) { 23387 module_put(mod); 23388 bpf_log(log, "can't modify return codes of BPF programs\n"); 23389 return -EINVAL; 23390 } 23391 ret = -EINVAL; 23392 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 23393 !check_attach_modify_return(addr, tname)) 23394 ret = 0; 23395 if (ret) { 23396 module_put(mod); 23397 bpf_log(log, "%s() is not modifiable\n", tname); 23398 return ret; 23399 } 23400 } 23401 23402 break; 23403 } 23404 tgt_info->tgt_addr = addr; 23405 tgt_info->tgt_name = tname; 23406 tgt_info->tgt_type = t; 23407 tgt_info->tgt_mod = mod; 23408 return 0; 23409 } 23410 23411 BTF_SET_START(btf_id_deny) 23412 BTF_ID_UNUSED 23413 #ifdef CONFIG_SMP 23414 BTF_ID(func, migrate_disable) 23415 BTF_ID(func, migrate_enable) 23416 #endif 23417 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 23418 BTF_ID(func, rcu_read_unlock_strict) 23419 #endif 23420 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 23421 BTF_ID(func, preempt_count_add) 23422 BTF_ID(func, preempt_count_sub) 23423 #endif 23424 #ifdef CONFIG_PREEMPT_RCU 23425 BTF_ID(func, __rcu_read_lock) 23426 BTF_ID(func, __rcu_read_unlock) 23427 #endif 23428 BTF_SET_END(btf_id_deny) 23429 23430 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 23431 * Currently, we must manually list all __noreturn functions here. Once a more 23432 * robust solution is implemented, this workaround can be removed. 23433 */ 23434 BTF_SET_START(noreturn_deny) 23435 #ifdef CONFIG_IA32_EMULATION 23436 BTF_ID(func, __ia32_sys_exit) 23437 BTF_ID(func, __ia32_sys_exit_group) 23438 #endif 23439 #ifdef CONFIG_KUNIT 23440 BTF_ID(func, __kunit_abort) 23441 BTF_ID(func, kunit_try_catch_throw) 23442 #endif 23443 #ifdef CONFIG_MODULES 23444 BTF_ID(func, __module_put_and_kthread_exit) 23445 #endif 23446 #ifdef CONFIG_X86_64 23447 BTF_ID(func, __x64_sys_exit) 23448 BTF_ID(func, __x64_sys_exit_group) 23449 #endif 23450 BTF_ID(func, do_exit) 23451 BTF_ID(func, do_group_exit) 23452 BTF_ID(func, kthread_complete_and_exit) 23453 BTF_ID(func, kthread_exit) 23454 BTF_ID(func, make_task_dead) 23455 BTF_SET_END(noreturn_deny) 23456 23457 static bool can_be_sleepable(struct bpf_prog *prog) 23458 { 23459 if (prog->type == BPF_PROG_TYPE_TRACING) { 23460 switch (prog->expected_attach_type) { 23461 case BPF_TRACE_FENTRY: 23462 case BPF_TRACE_FEXIT: 23463 case BPF_MODIFY_RETURN: 23464 case BPF_TRACE_ITER: 23465 return true; 23466 default: 23467 return false; 23468 } 23469 } 23470 return prog->type == BPF_PROG_TYPE_LSM || 23471 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 23472 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 23473 } 23474 23475 static int check_attach_btf_id(struct bpf_verifier_env *env) 23476 { 23477 struct bpf_prog *prog = env->prog; 23478 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 23479 struct bpf_attach_target_info tgt_info = {}; 23480 u32 btf_id = prog->aux->attach_btf_id; 23481 struct bpf_trampoline *tr; 23482 int ret; 23483 u64 key; 23484 23485 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 23486 if (prog->sleepable) 23487 /* attach_btf_id checked to be zero already */ 23488 return 0; 23489 verbose(env, "Syscall programs can only be sleepable\n"); 23490 return -EINVAL; 23491 } 23492 23493 if (prog->sleepable && !can_be_sleepable(prog)) { 23494 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 23495 return -EINVAL; 23496 } 23497 23498 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 23499 return check_struct_ops_btf_id(env); 23500 23501 if (prog->type != BPF_PROG_TYPE_TRACING && 23502 prog->type != BPF_PROG_TYPE_LSM && 23503 prog->type != BPF_PROG_TYPE_EXT) 23504 return 0; 23505 23506 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 23507 if (ret) 23508 return ret; 23509 23510 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 23511 /* to make freplace equivalent to their targets, they need to 23512 * inherit env->ops and expected_attach_type for the rest of the 23513 * verification 23514 */ 23515 env->ops = bpf_verifier_ops[tgt_prog->type]; 23516 prog->expected_attach_type = tgt_prog->expected_attach_type; 23517 } 23518 23519 /* store info about the attachment target that will be used later */ 23520 prog->aux->attach_func_proto = tgt_info.tgt_type; 23521 prog->aux->attach_func_name = tgt_info.tgt_name; 23522 prog->aux->mod = tgt_info.tgt_mod; 23523 23524 if (tgt_prog) { 23525 prog->aux->saved_dst_prog_type = tgt_prog->type; 23526 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 23527 } 23528 23529 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 23530 prog->aux->attach_btf_trace = true; 23531 return 0; 23532 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 23533 return bpf_iter_prog_supported(prog); 23534 } 23535 23536 if (prog->type == BPF_PROG_TYPE_LSM) { 23537 ret = bpf_lsm_verify_prog(&env->log, prog); 23538 if (ret < 0) 23539 return ret; 23540 } else if (prog->type == BPF_PROG_TYPE_TRACING && 23541 btf_id_set_contains(&btf_id_deny, btf_id)) { 23542 return -EINVAL; 23543 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 23544 prog->expected_attach_type == BPF_MODIFY_RETURN) && 23545 btf_id_set_contains(&noreturn_deny, btf_id)) { 23546 verbose(env, "Attaching fexit/fmod_ret to __noreturn functions is rejected.\n"); 23547 return -EINVAL; 23548 } 23549 23550 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 23551 tr = bpf_trampoline_get(key, &tgt_info); 23552 if (!tr) 23553 return -ENOMEM; 23554 23555 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 23556 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 23557 23558 prog->aux->dst_trampoline = tr; 23559 return 0; 23560 } 23561 23562 struct btf *bpf_get_btf_vmlinux(void) 23563 { 23564 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 23565 mutex_lock(&bpf_verifier_lock); 23566 if (!btf_vmlinux) 23567 btf_vmlinux = btf_parse_vmlinux(); 23568 mutex_unlock(&bpf_verifier_lock); 23569 } 23570 return btf_vmlinux; 23571 } 23572 23573 /* 23574 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 23575 * this case expect that every file descriptor in the array is either a map or 23576 * a BTF. Everything else is considered to be trash. 23577 */ 23578 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) 23579 { 23580 struct bpf_map *map; 23581 struct btf *btf; 23582 CLASS(fd, f)(fd); 23583 int err; 23584 23585 map = __bpf_map_get(f); 23586 if (!IS_ERR(map)) { 23587 err = __add_used_map(env, map); 23588 if (err < 0) 23589 return err; 23590 return 0; 23591 } 23592 23593 btf = __btf_get_by_fd(f); 23594 if (!IS_ERR(btf)) { 23595 err = __add_used_btf(env, btf); 23596 if (err < 0) 23597 return err; 23598 return 0; 23599 } 23600 23601 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 23602 return PTR_ERR(map); 23603 } 23604 23605 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr) 23606 { 23607 size_t size = sizeof(int); 23608 int ret; 23609 int fd; 23610 u32 i; 23611 23612 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 23613 23614 /* 23615 * The only difference between old (no fd_array_cnt is given) and new 23616 * APIs is that in the latter case the fd_array is expected to be 23617 * continuous and is scanned for map fds right away 23618 */ 23619 if (!attr->fd_array_cnt) 23620 return 0; 23621 23622 /* Check for integer overflow */ 23623 if (attr->fd_array_cnt >= (U32_MAX / size)) { 23624 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt); 23625 return -EINVAL; 23626 } 23627 23628 for (i = 0; i < attr->fd_array_cnt; i++) { 23629 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size)) 23630 return -EFAULT; 23631 23632 ret = add_fd_from_fd_array(env, fd); 23633 if (ret) 23634 return ret; 23635 } 23636 23637 return 0; 23638 } 23639 23640 static bool can_fallthrough(struct bpf_insn *insn) 23641 { 23642 u8 class = BPF_CLASS(insn->code); 23643 u8 opcode = BPF_OP(insn->code); 23644 23645 if (class != BPF_JMP && class != BPF_JMP32) 23646 return true; 23647 23648 if (opcode == BPF_EXIT || opcode == BPF_JA) 23649 return false; 23650 23651 return true; 23652 } 23653 23654 static bool can_jump(struct bpf_insn *insn) 23655 { 23656 u8 class = BPF_CLASS(insn->code); 23657 u8 opcode = BPF_OP(insn->code); 23658 23659 if (class != BPF_JMP && class != BPF_JMP32) 23660 return false; 23661 23662 switch (opcode) { 23663 case BPF_JA: 23664 case BPF_JEQ: 23665 case BPF_JNE: 23666 case BPF_JLT: 23667 case BPF_JLE: 23668 case BPF_JGT: 23669 case BPF_JGE: 23670 case BPF_JSGT: 23671 case BPF_JSGE: 23672 case BPF_JSLT: 23673 case BPF_JSLE: 23674 case BPF_JCOND: 23675 return true; 23676 } 23677 23678 return false; 23679 } 23680 23681 static int insn_successors(struct bpf_prog *prog, u32 idx, u32 succ[2]) 23682 { 23683 struct bpf_insn *insn = &prog->insnsi[idx]; 23684 int i = 0, insn_sz; 23685 u32 dst; 23686 23687 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 23688 if (can_fallthrough(insn) && idx + 1 < prog->len) 23689 succ[i++] = idx + insn_sz; 23690 23691 if (can_jump(insn)) { 23692 dst = idx + jmp_offset(insn) + 1; 23693 if (i == 0 || succ[0] != dst) 23694 succ[i++] = dst; 23695 } 23696 23697 return i; 23698 } 23699 23700 /* Each field is a register bitmask */ 23701 struct insn_live_regs { 23702 u16 use; /* registers read by instruction */ 23703 u16 def; /* registers written by instruction */ 23704 u16 in; /* registers that may be alive before instruction */ 23705 u16 out; /* registers that may be alive after instruction */ 23706 }; 23707 23708 /* Bitmask with 1s for all caller saved registers */ 23709 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 23710 23711 /* Compute info->{use,def} fields for the instruction */ 23712 static void compute_insn_live_regs(struct bpf_verifier_env *env, 23713 struct bpf_insn *insn, 23714 struct insn_live_regs *info) 23715 { 23716 struct call_summary cs; 23717 u8 class = BPF_CLASS(insn->code); 23718 u8 code = BPF_OP(insn->code); 23719 u8 mode = BPF_MODE(insn->code); 23720 u16 src = BIT(insn->src_reg); 23721 u16 dst = BIT(insn->dst_reg); 23722 u16 r0 = BIT(0); 23723 u16 def = 0; 23724 u16 use = 0xffff; 23725 23726 switch (class) { 23727 case BPF_LD: 23728 switch (mode) { 23729 case BPF_IMM: 23730 if (BPF_SIZE(insn->code) == BPF_DW) { 23731 def = dst; 23732 use = 0; 23733 } 23734 break; 23735 case BPF_LD | BPF_ABS: 23736 case BPF_LD | BPF_IND: 23737 /* stick with defaults */ 23738 break; 23739 } 23740 break; 23741 case BPF_LDX: 23742 switch (mode) { 23743 case BPF_MEM: 23744 case BPF_MEMSX: 23745 def = dst; 23746 use = src; 23747 break; 23748 } 23749 break; 23750 case BPF_ST: 23751 switch (mode) { 23752 case BPF_MEM: 23753 def = 0; 23754 use = dst; 23755 break; 23756 } 23757 break; 23758 case BPF_STX: 23759 switch (mode) { 23760 case BPF_MEM: 23761 def = 0; 23762 use = dst | src; 23763 break; 23764 case BPF_ATOMIC: 23765 switch (insn->imm) { 23766 case BPF_CMPXCHG: 23767 use = r0 | dst | src; 23768 def = r0; 23769 break; 23770 case BPF_LOAD_ACQ: 23771 def = dst; 23772 use = src; 23773 break; 23774 case BPF_STORE_REL: 23775 def = 0; 23776 use = dst | src; 23777 break; 23778 default: 23779 use = dst | src; 23780 if (insn->imm & BPF_FETCH) 23781 def = src; 23782 else 23783 def = 0; 23784 } 23785 break; 23786 } 23787 break; 23788 case BPF_ALU: 23789 case BPF_ALU64: 23790 switch (code) { 23791 case BPF_END: 23792 use = dst; 23793 def = dst; 23794 break; 23795 case BPF_MOV: 23796 def = dst; 23797 if (BPF_SRC(insn->code) == BPF_K) 23798 use = 0; 23799 else 23800 use = src; 23801 break; 23802 default: 23803 def = dst; 23804 if (BPF_SRC(insn->code) == BPF_K) 23805 use = dst; 23806 else 23807 use = dst | src; 23808 } 23809 break; 23810 case BPF_JMP: 23811 case BPF_JMP32: 23812 switch (code) { 23813 case BPF_JA: 23814 case BPF_JCOND: 23815 def = 0; 23816 use = 0; 23817 break; 23818 case BPF_EXIT: 23819 def = 0; 23820 use = r0; 23821 break; 23822 case BPF_CALL: 23823 def = ALL_CALLER_SAVED_REGS; 23824 use = def & ~BIT(BPF_REG_0); 23825 if (get_call_summary(env, insn, &cs)) 23826 use = GENMASK(cs.num_params, 1); 23827 break; 23828 default: 23829 def = 0; 23830 if (BPF_SRC(insn->code) == BPF_K) 23831 use = dst; 23832 else 23833 use = dst | src; 23834 } 23835 break; 23836 } 23837 23838 info->def = def; 23839 info->use = use; 23840 } 23841 23842 /* Compute may-live registers after each instruction in the program. 23843 * The register is live after the instruction I if it is read by some 23844 * instruction S following I during program execution and is not 23845 * overwritten between I and S. 23846 * 23847 * Store result in env->insn_aux_data[i].live_regs. 23848 */ 23849 static int compute_live_registers(struct bpf_verifier_env *env) 23850 { 23851 struct bpf_insn_aux_data *insn_aux = env->insn_aux_data; 23852 struct bpf_insn *insns = env->prog->insnsi; 23853 struct insn_live_regs *state; 23854 int insn_cnt = env->prog->len; 23855 int err = 0, i, j; 23856 bool changed; 23857 23858 /* Use the following algorithm: 23859 * - define the following: 23860 * - I.use : a set of all registers read by instruction I; 23861 * - I.def : a set of all registers written by instruction I; 23862 * - I.in : a set of all registers that may be alive before I execution; 23863 * - I.out : a set of all registers that may be alive after I execution; 23864 * - insn_successors(I): a set of instructions S that might immediately 23865 * follow I for some program execution; 23866 * - associate separate empty sets 'I.in' and 'I.out' with each instruction; 23867 * - visit each instruction in a postorder and update 23868 * state[i].in, state[i].out as follows: 23869 * 23870 * state[i].out = U [state[s].in for S in insn_successors(i)] 23871 * state[i].in = (state[i].out / state[i].def) U state[i].use 23872 * 23873 * (where U stands for set union, / stands for set difference) 23874 * - repeat the computation while {in,out} fields changes for 23875 * any instruction. 23876 */ 23877 state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL); 23878 if (!state) { 23879 err = -ENOMEM; 23880 goto out; 23881 } 23882 23883 for (i = 0; i < insn_cnt; ++i) 23884 compute_insn_live_regs(env, &insns[i], &state[i]); 23885 23886 changed = true; 23887 while (changed) { 23888 changed = false; 23889 for (i = 0; i < env->cfg.cur_postorder; ++i) { 23890 int insn_idx = env->cfg.insn_postorder[i]; 23891 struct insn_live_regs *live = &state[insn_idx]; 23892 int succ_num; 23893 u32 succ[2]; 23894 u16 new_out = 0; 23895 u16 new_in = 0; 23896 23897 succ_num = insn_successors(env->prog, insn_idx, succ); 23898 for (int s = 0; s < succ_num; ++s) 23899 new_out |= state[succ[s]].in; 23900 new_in = (new_out & ~live->def) | live->use; 23901 if (new_out != live->out || new_in != live->in) { 23902 live->in = new_in; 23903 live->out = new_out; 23904 changed = true; 23905 } 23906 } 23907 } 23908 23909 for (i = 0; i < insn_cnt; ++i) 23910 insn_aux[i].live_regs_before = state[i].in; 23911 23912 if (env->log.level & BPF_LOG_LEVEL2) { 23913 verbose(env, "Live regs before insn:\n"); 23914 for (i = 0; i < insn_cnt; ++i) { 23915 verbose(env, "%3d: ", i); 23916 for (j = BPF_REG_0; j < BPF_REG_10; ++j) 23917 if (insn_aux[i].live_regs_before & BIT(j)) 23918 verbose(env, "%d", j); 23919 else 23920 verbose(env, "."); 23921 verbose(env, " "); 23922 verbose_insn(env, &insns[i]); 23923 if (bpf_is_ldimm64(&insns[i])) 23924 i++; 23925 } 23926 } 23927 23928 out: 23929 kvfree(state); 23930 kvfree(env->cfg.insn_postorder); 23931 env->cfg.insn_postorder = NULL; 23932 env->cfg.cur_postorder = 0; 23933 return err; 23934 } 23935 23936 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 23937 { 23938 u64 start_time = ktime_get_ns(); 23939 struct bpf_verifier_env *env; 23940 int i, len, ret = -EINVAL, err; 23941 u32 log_true_size; 23942 bool is_priv; 23943 23944 /* no program is valid */ 23945 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 23946 return -EINVAL; 23947 23948 /* 'struct bpf_verifier_env' can be global, but since it's not small, 23949 * allocate/free it every time bpf_check() is called 23950 */ 23951 env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 23952 if (!env) 23953 return -ENOMEM; 23954 23955 env->bt.env = env; 23956 23957 len = (*prog)->len; 23958 env->insn_aux_data = 23959 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 23960 ret = -ENOMEM; 23961 if (!env->insn_aux_data) 23962 goto err_free_env; 23963 for (i = 0; i < len; i++) 23964 env->insn_aux_data[i].orig_idx = i; 23965 env->prog = *prog; 23966 env->ops = bpf_verifier_ops[env->prog->type]; 23967 23968 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 23969 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 23970 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 23971 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 23972 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 23973 23974 bpf_get_btf_vmlinux(); 23975 23976 /* grab the mutex to protect few globals used by verifier */ 23977 if (!is_priv) 23978 mutex_lock(&bpf_verifier_lock); 23979 23980 /* user could have requested verbose verifier output 23981 * and supplied buffer to store the verification trace 23982 */ 23983 ret = bpf_vlog_init(&env->log, attr->log_level, 23984 (char __user *) (unsigned long) attr->log_buf, 23985 attr->log_size); 23986 if (ret) 23987 goto err_unlock; 23988 23989 ret = process_fd_array(env, attr, uattr); 23990 if (ret) 23991 goto skip_full_check; 23992 23993 mark_verifier_state_clean(env); 23994 23995 if (IS_ERR(btf_vmlinux)) { 23996 /* Either gcc or pahole or kernel are broken. */ 23997 verbose(env, "in-kernel BTF is malformed\n"); 23998 ret = PTR_ERR(btf_vmlinux); 23999 goto skip_full_check; 24000 } 24001 24002 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 24003 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 24004 env->strict_alignment = true; 24005 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 24006 env->strict_alignment = false; 24007 24008 if (is_priv) 24009 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 24010 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 24011 24012 env->explored_states = kvcalloc(state_htab_size(env), 24013 sizeof(struct list_head), 24014 GFP_USER); 24015 ret = -ENOMEM; 24016 if (!env->explored_states) 24017 goto skip_full_check; 24018 24019 for (i = 0; i < state_htab_size(env); i++) 24020 INIT_LIST_HEAD(&env->explored_states[i]); 24021 INIT_LIST_HEAD(&env->free_list); 24022 24023 ret = check_btf_info_early(env, attr, uattr); 24024 if (ret < 0) 24025 goto skip_full_check; 24026 24027 ret = add_subprog_and_kfunc(env); 24028 if (ret < 0) 24029 goto skip_full_check; 24030 24031 ret = check_subprogs(env); 24032 if (ret < 0) 24033 goto skip_full_check; 24034 24035 ret = check_btf_info(env, attr, uattr); 24036 if (ret < 0) 24037 goto skip_full_check; 24038 24039 ret = resolve_pseudo_ldimm64(env); 24040 if (ret < 0) 24041 goto skip_full_check; 24042 24043 if (bpf_prog_is_offloaded(env->prog->aux)) { 24044 ret = bpf_prog_offload_verifier_prep(env->prog); 24045 if (ret) 24046 goto skip_full_check; 24047 } 24048 24049 ret = check_cfg(env); 24050 if (ret < 0) 24051 goto skip_full_check; 24052 24053 ret = check_attach_btf_id(env); 24054 if (ret) 24055 goto skip_full_check; 24056 24057 ret = compute_live_registers(env); 24058 if (ret < 0) 24059 goto skip_full_check; 24060 24061 ret = mark_fastcall_patterns(env); 24062 if (ret < 0) 24063 goto skip_full_check; 24064 24065 ret = do_check_main(env); 24066 ret = ret ?: do_check_subprogs(env); 24067 24068 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 24069 ret = bpf_prog_offload_finalize(env); 24070 24071 skip_full_check: 24072 kvfree(env->explored_states); 24073 24074 /* might decrease stack depth, keep it before passes that 24075 * allocate additional slots. 24076 */ 24077 if (ret == 0) 24078 ret = remove_fastcall_spills_fills(env); 24079 24080 if (ret == 0) 24081 ret = check_max_stack_depth(env); 24082 24083 /* instruction rewrites happen after this point */ 24084 if (ret == 0) 24085 ret = optimize_bpf_loop(env); 24086 24087 if (is_priv) { 24088 if (ret == 0) 24089 opt_hard_wire_dead_code_branches(env); 24090 if (ret == 0) 24091 ret = opt_remove_dead_code(env); 24092 if (ret == 0) 24093 ret = opt_remove_nops(env); 24094 } else { 24095 if (ret == 0) 24096 sanitize_dead_code(env); 24097 } 24098 24099 if (ret == 0) 24100 /* program is valid, convert *(u32*)(ctx + off) accesses */ 24101 ret = convert_ctx_accesses(env); 24102 24103 if (ret == 0) 24104 ret = do_misc_fixups(env); 24105 24106 /* do 32-bit optimization after insn patching has done so those patched 24107 * insns could be handled correctly. 24108 */ 24109 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 24110 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 24111 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 24112 : false; 24113 } 24114 24115 if (ret == 0) 24116 ret = fixup_call_args(env); 24117 24118 env->verification_time = ktime_get_ns() - start_time; 24119 print_verification_stats(env); 24120 env->prog->aux->verified_insns = env->insn_processed; 24121 24122 /* preserve original error even if log finalization is successful */ 24123 err = bpf_vlog_finalize(&env->log, &log_true_size); 24124 if (err) 24125 ret = err; 24126 24127 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 24128 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 24129 &log_true_size, sizeof(log_true_size))) { 24130 ret = -EFAULT; 24131 goto err_release_maps; 24132 } 24133 24134 if (ret) 24135 goto err_release_maps; 24136 24137 if (env->used_map_cnt) { 24138 /* if program passed verifier, update used_maps in bpf_prog_info */ 24139 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 24140 sizeof(env->used_maps[0]), 24141 GFP_KERNEL); 24142 24143 if (!env->prog->aux->used_maps) { 24144 ret = -ENOMEM; 24145 goto err_release_maps; 24146 } 24147 24148 memcpy(env->prog->aux->used_maps, env->used_maps, 24149 sizeof(env->used_maps[0]) * env->used_map_cnt); 24150 env->prog->aux->used_map_cnt = env->used_map_cnt; 24151 } 24152 if (env->used_btf_cnt) { 24153 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 24154 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 24155 sizeof(env->used_btfs[0]), 24156 GFP_KERNEL); 24157 if (!env->prog->aux->used_btfs) { 24158 ret = -ENOMEM; 24159 goto err_release_maps; 24160 } 24161 24162 memcpy(env->prog->aux->used_btfs, env->used_btfs, 24163 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 24164 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 24165 } 24166 if (env->used_map_cnt || env->used_btf_cnt) { 24167 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 24168 * bpf_ld_imm64 instructions 24169 */ 24170 convert_pseudo_ld_imm64(env); 24171 } 24172 24173 adjust_btf_func(env); 24174 24175 err_release_maps: 24176 if (!env->prog->aux->used_maps) 24177 /* if we didn't copy map pointers into bpf_prog_info, release 24178 * them now. Otherwise free_used_maps() will release them. 24179 */ 24180 release_maps(env); 24181 if (!env->prog->aux->used_btfs) 24182 release_btfs(env); 24183 24184 /* extension progs temporarily inherit the attach_type of their targets 24185 for verification purposes, so set it back to zero before returning 24186 */ 24187 if (env->prog->type == BPF_PROG_TYPE_EXT) 24188 env->prog->expected_attach_type = 0; 24189 24190 *prog = env->prog; 24191 24192 module_put(env->attach_btf_mod); 24193 err_unlock: 24194 if (!is_priv) 24195 mutex_unlock(&bpf_verifier_lock); 24196 vfree(env->insn_aux_data); 24197 kvfree(env->insn_hist); 24198 err_free_env: 24199 kvfree(env->cfg.insn_postorder); 24200 kvfree(env); 24201 return ret; 24202 } 24203