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 enum bpf_features { 48 BPF_FEAT_RDONLY_CAST_TO_VOID = 0, 49 BPF_FEAT_STREAMS = 1, 50 __MAX_BPF_FEAT, 51 }; 52 53 struct bpf_mem_alloc bpf_global_percpu_ma; 54 static bool bpf_global_percpu_ma_set; 55 56 /* bpf_check() is a static code analyzer that walks eBPF program 57 * instruction by instruction and updates register/stack state. 58 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 59 * 60 * The first pass is depth-first-search to check that the program is a DAG. 61 * It rejects the following programs: 62 * - larger than BPF_MAXINSNS insns 63 * - if loop is present (detected via back-edge) 64 * - unreachable insns exist (shouldn't be a forest. program = one function) 65 * - out of bounds or malformed jumps 66 * The second pass is all possible path descent from the 1st insn. 67 * Since it's analyzing all paths through the program, the length of the 68 * analysis is limited to 64k insn, which may be hit even if total number of 69 * insn is less then 4K, but there are too many branches that change stack/regs. 70 * Number of 'branches to be analyzed' is limited to 1k 71 * 72 * On entry to each instruction, each register has a type, and the instruction 73 * changes the types of the registers depending on instruction semantics. 74 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 75 * copied to R1. 76 * 77 * All registers are 64-bit. 78 * R0 - return register 79 * R1-R5 argument passing registers 80 * R6-R9 callee saved registers 81 * R10 - frame pointer read-only 82 * 83 * At the start of BPF program the register R1 contains a pointer to bpf_context 84 * and has type PTR_TO_CTX. 85 * 86 * Verifier tracks arithmetic operations on pointers in case: 87 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 88 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 89 * 1st insn copies R10 (which has FRAME_PTR) type into R1 90 * and 2nd arithmetic instruction is pattern matched to recognize 91 * that it wants to construct a pointer to some element within stack. 92 * So after 2nd insn, the register R1 has type PTR_TO_STACK 93 * (and -20 constant is saved for further stack bounds checking). 94 * Meaning that this reg is a pointer to stack plus known immediate constant. 95 * 96 * Most of the time the registers have SCALAR_VALUE type, which 97 * means the register has some value, but it's not a valid pointer. 98 * (like pointer plus pointer becomes SCALAR_VALUE type) 99 * 100 * When verifier sees load or store instructions the type of base register 101 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 102 * four pointer types recognized by check_mem_access() function. 103 * 104 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 105 * and the range of [ptr, ptr + map's value_size) is accessible. 106 * 107 * registers used to pass values to function calls are checked against 108 * function argument constraints. 109 * 110 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 111 * It means that the register type passed to this function must be 112 * PTR_TO_STACK and it will be used inside the function as 113 * 'pointer to map element key' 114 * 115 * For example the argument constraints for bpf_map_lookup_elem(): 116 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 117 * .arg1_type = ARG_CONST_MAP_PTR, 118 * .arg2_type = ARG_PTR_TO_MAP_KEY, 119 * 120 * ret_type says that this function returns 'pointer to map elem value or null' 121 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 122 * 2nd argument should be a pointer to stack, which will be used inside 123 * the helper function as a pointer to map element key. 124 * 125 * On the kernel side the helper function looks like: 126 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 127 * { 128 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 129 * void *key = (void *) (unsigned long) r2; 130 * void *value; 131 * 132 * here kernel can access 'key' and 'map' pointers safely, knowing that 133 * [key, key + map->key_size) bytes are valid and were initialized on 134 * the stack of eBPF program. 135 * } 136 * 137 * Corresponding eBPF program may look like: 138 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 139 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 140 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 141 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 142 * here verifier looks at prototype of map_lookup_elem() and sees: 143 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 144 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 145 * 146 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 147 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 148 * and were initialized prior to this call. 149 * If it's ok, then verifier allows this BPF_CALL insn and looks at 150 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 151 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 152 * returns either pointer to map value or NULL. 153 * 154 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 155 * insn, the register holding that pointer in the true branch changes state to 156 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 157 * branch. See check_cond_jmp_op(). 158 * 159 * After the call R0 is set to return type of the function and registers R1-R5 160 * are set to NOT_INIT to indicate that they are no longer readable. 161 * 162 * The following reference types represent a potential reference to a kernel 163 * resource which, after first being allocated, must be checked and freed by 164 * the BPF program: 165 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 166 * 167 * When the verifier sees a helper call return a reference type, it allocates a 168 * pointer id for the reference and stores it in the current function state. 169 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 170 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 171 * passes through a NULL-check conditional. For the branch wherein the state is 172 * changed to CONST_IMM, the verifier releases the reference. 173 * 174 * For each helper function that allocates a reference, such as 175 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 176 * bpf_sk_release(). When a reference type passes into the release function, 177 * the verifier also releases the reference. If any unchecked or unreleased 178 * reference remains at the end of the program, the verifier rejects it. 179 */ 180 181 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 182 struct bpf_verifier_stack_elem { 183 /* verifier state is 'st' 184 * before processing instruction 'insn_idx' 185 * and after processing instruction 'prev_insn_idx' 186 */ 187 struct bpf_verifier_state st; 188 int insn_idx; 189 int prev_insn_idx; 190 struct bpf_verifier_stack_elem *next; 191 /* length of verifier log at the time this state was pushed on stack */ 192 u32 log_pos; 193 }; 194 195 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 196 #define BPF_COMPLEXITY_LIMIT_STATES 64 197 198 #define BPF_MAP_KEY_POISON (1ULL << 63) 199 #define BPF_MAP_KEY_SEEN (1ULL << 62) 200 201 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 202 203 #define BPF_PRIV_STACK_MIN_SIZE 64 204 205 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx); 206 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id); 207 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 208 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 209 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 210 static int ref_set_non_owning(struct bpf_verifier_env *env, 211 struct bpf_reg_state *reg); 212 static void specialize_kfunc(struct bpf_verifier_env *env, 213 u32 func_id, u16 offset, unsigned long *addr); 214 static bool is_trusted_reg(const struct bpf_reg_state *reg); 215 216 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 217 { 218 return aux->map_ptr_state.poison; 219 } 220 221 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 222 { 223 return aux->map_ptr_state.unpriv; 224 } 225 226 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 227 struct bpf_map *map, 228 bool unpriv, bool poison) 229 { 230 unpriv |= bpf_map_ptr_unpriv(aux); 231 aux->map_ptr_state.unpriv = unpriv; 232 aux->map_ptr_state.poison = poison; 233 aux->map_ptr_state.map_ptr = map; 234 } 235 236 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 237 { 238 return aux->map_key_state & BPF_MAP_KEY_POISON; 239 } 240 241 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 242 { 243 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 244 } 245 246 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 247 { 248 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 249 } 250 251 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 252 { 253 bool poisoned = bpf_map_key_poisoned(aux); 254 255 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 256 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 257 } 258 259 static bool bpf_helper_call(const struct bpf_insn *insn) 260 { 261 return insn->code == (BPF_JMP | BPF_CALL) && 262 insn->src_reg == 0; 263 } 264 265 static bool bpf_pseudo_call(const struct bpf_insn *insn) 266 { 267 return insn->code == (BPF_JMP | BPF_CALL) && 268 insn->src_reg == BPF_PSEUDO_CALL; 269 } 270 271 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 272 { 273 return insn->code == (BPF_JMP | BPF_CALL) && 274 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 275 } 276 277 struct bpf_call_arg_meta { 278 struct bpf_map *map_ptr; 279 bool raw_mode; 280 bool pkt_access; 281 u8 release_regno; 282 int regno; 283 int access_size; 284 int mem_size; 285 u64 msize_max_value; 286 int ref_obj_id; 287 int dynptr_id; 288 int map_uid; 289 int func_id; 290 struct btf *btf; 291 u32 btf_id; 292 struct btf *ret_btf; 293 u32 ret_btf_id; 294 u32 subprogno; 295 struct btf_field *kptr_field; 296 s64 const_map_key; 297 }; 298 299 struct bpf_kfunc_call_arg_meta { 300 /* In parameters */ 301 struct btf *btf; 302 u32 func_id; 303 u32 kfunc_flags; 304 const struct btf_type *func_proto; 305 const char *func_name; 306 /* Out parameters */ 307 u32 ref_obj_id; 308 u8 release_regno; 309 bool r0_rdonly; 310 u32 ret_btf_id; 311 u64 r0_size; 312 u32 subprogno; 313 struct { 314 u64 value; 315 bool found; 316 } arg_constant; 317 318 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 319 * generally to pass info about user-defined local kptr types to later 320 * verification logic 321 * bpf_obj_drop/bpf_percpu_obj_drop 322 * Record the local kptr type to be drop'd 323 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 324 * Record the local kptr type to be refcount_incr'd and use 325 * arg_owning_ref to determine whether refcount_acquire should be 326 * fallible 327 */ 328 struct btf *arg_btf; 329 u32 arg_btf_id; 330 bool arg_owning_ref; 331 bool arg_prog; 332 333 struct { 334 struct btf_field *field; 335 } arg_list_head; 336 struct { 337 struct btf_field *field; 338 } arg_rbtree_root; 339 struct { 340 enum bpf_dynptr_type type; 341 u32 id; 342 u32 ref_obj_id; 343 } initialized_dynptr; 344 struct { 345 u8 spi; 346 u8 frameno; 347 } iter; 348 struct { 349 struct bpf_map *ptr; 350 int uid; 351 } map; 352 u64 mem_size; 353 }; 354 355 struct btf *btf_vmlinux; 356 357 static const char *btf_type_name(const struct btf *btf, u32 id) 358 { 359 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 360 } 361 362 static DEFINE_MUTEX(bpf_verifier_lock); 363 static DEFINE_MUTEX(bpf_percpu_ma_lock); 364 365 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 366 { 367 struct bpf_verifier_env *env = private_data; 368 va_list args; 369 370 if (!bpf_verifier_log_needed(&env->log)) 371 return; 372 373 va_start(args, fmt); 374 bpf_verifier_vlog(&env->log, fmt, args); 375 va_end(args); 376 } 377 378 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 379 struct bpf_reg_state *reg, 380 struct bpf_retval_range range, const char *ctx, 381 const char *reg_name) 382 { 383 bool unknown = true; 384 385 verbose(env, "%s the register %s has", ctx, reg_name); 386 if (reg->smin_value > S64_MIN) { 387 verbose(env, " smin=%lld", reg->smin_value); 388 unknown = false; 389 } 390 if (reg->smax_value < S64_MAX) { 391 verbose(env, " smax=%lld", reg->smax_value); 392 unknown = false; 393 } 394 if (unknown) 395 verbose(env, " unknown scalar value"); 396 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 397 } 398 399 static bool reg_not_null(const struct bpf_reg_state *reg) 400 { 401 enum bpf_reg_type type; 402 403 type = reg->type; 404 if (type_may_be_null(type)) 405 return false; 406 407 type = base_type(type); 408 return type == PTR_TO_SOCKET || 409 type == PTR_TO_TCP_SOCK || 410 type == PTR_TO_MAP_VALUE || 411 type == PTR_TO_MAP_KEY || 412 type == PTR_TO_SOCK_COMMON || 413 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 414 (type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) || 415 type == CONST_PTR_TO_MAP; 416 } 417 418 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 419 { 420 struct btf_record *rec = NULL; 421 struct btf_struct_meta *meta; 422 423 if (reg->type == PTR_TO_MAP_VALUE) { 424 rec = reg->map_ptr->record; 425 } else if (type_is_ptr_alloc_obj(reg->type)) { 426 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 427 if (meta) 428 rec = meta->record; 429 } 430 return rec; 431 } 432 433 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 434 { 435 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 436 437 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 438 } 439 440 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 441 { 442 struct bpf_func_info *info; 443 444 if (!env->prog->aux->func_info) 445 return ""; 446 447 info = &env->prog->aux->func_info[subprog]; 448 return btf_type_name(env->prog->aux->btf, info->type_id); 449 } 450 451 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 452 { 453 struct bpf_subprog_info *info = subprog_info(env, subprog); 454 455 info->is_cb = true; 456 info->is_async_cb = true; 457 info->is_exception_cb = true; 458 } 459 460 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 461 { 462 return subprog_info(env, subprog)->is_exception_cb; 463 } 464 465 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 466 { 467 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK); 468 } 469 470 static bool type_is_rdonly_mem(u32 type) 471 { 472 return type & MEM_RDONLY; 473 } 474 475 static bool is_acquire_function(enum bpf_func_id func_id, 476 const struct bpf_map *map) 477 { 478 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 479 480 if (func_id == BPF_FUNC_sk_lookup_tcp || 481 func_id == BPF_FUNC_sk_lookup_udp || 482 func_id == BPF_FUNC_skc_lookup_tcp || 483 func_id == BPF_FUNC_ringbuf_reserve || 484 func_id == BPF_FUNC_kptr_xchg) 485 return true; 486 487 if (func_id == BPF_FUNC_map_lookup_elem && 488 (map_type == BPF_MAP_TYPE_SOCKMAP || 489 map_type == BPF_MAP_TYPE_SOCKHASH)) 490 return true; 491 492 return false; 493 } 494 495 static bool is_ptr_cast_function(enum bpf_func_id func_id) 496 { 497 return func_id == BPF_FUNC_tcp_sock || 498 func_id == BPF_FUNC_sk_fullsock || 499 func_id == BPF_FUNC_skc_to_tcp_sock || 500 func_id == BPF_FUNC_skc_to_tcp6_sock || 501 func_id == BPF_FUNC_skc_to_udp6_sock || 502 func_id == BPF_FUNC_skc_to_mptcp_sock || 503 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 504 func_id == BPF_FUNC_skc_to_tcp_request_sock; 505 } 506 507 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 508 { 509 return func_id == BPF_FUNC_dynptr_data; 510 } 511 512 static bool is_sync_callback_calling_kfunc(u32 btf_id); 513 static bool is_async_callback_calling_kfunc(u32 btf_id); 514 static bool is_callback_calling_kfunc(u32 btf_id); 515 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 516 517 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id); 518 519 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 520 { 521 return func_id == BPF_FUNC_for_each_map_elem || 522 func_id == BPF_FUNC_find_vma || 523 func_id == BPF_FUNC_loop || 524 func_id == BPF_FUNC_user_ringbuf_drain; 525 } 526 527 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 528 { 529 return func_id == BPF_FUNC_timer_set_callback; 530 } 531 532 static bool is_callback_calling_function(enum bpf_func_id func_id) 533 { 534 return is_sync_callback_calling_function(func_id) || 535 is_async_callback_calling_function(func_id); 536 } 537 538 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 539 { 540 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 541 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 542 } 543 544 static bool is_async_callback_calling_insn(struct bpf_insn *insn) 545 { 546 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 547 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 548 } 549 550 static bool is_may_goto_insn(struct bpf_insn *insn) 551 { 552 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 553 } 554 555 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx) 556 { 557 return is_may_goto_insn(&env->prog->insnsi[insn_idx]); 558 } 559 560 static bool is_storage_get_function(enum bpf_func_id func_id) 561 { 562 return func_id == BPF_FUNC_sk_storage_get || 563 func_id == BPF_FUNC_inode_storage_get || 564 func_id == BPF_FUNC_task_storage_get || 565 func_id == BPF_FUNC_cgrp_storage_get; 566 } 567 568 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 569 const struct bpf_map *map) 570 { 571 int ref_obj_uses = 0; 572 573 if (is_ptr_cast_function(func_id)) 574 ref_obj_uses++; 575 if (is_acquire_function(func_id, map)) 576 ref_obj_uses++; 577 if (is_dynptr_ref_function(func_id)) 578 ref_obj_uses++; 579 580 return ref_obj_uses > 1; 581 } 582 583 static bool is_cmpxchg_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_CMPXCHG; 588 } 589 590 static bool is_atomic_load_insn(const struct bpf_insn *insn) 591 { 592 return BPF_CLASS(insn->code) == BPF_STX && 593 BPF_MODE(insn->code) == BPF_ATOMIC && 594 insn->imm == BPF_LOAD_ACQ; 595 } 596 597 static int __get_spi(s32 off) 598 { 599 return (-off - 1) / BPF_REG_SIZE; 600 } 601 602 static struct bpf_func_state *func(struct bpf_verifier_env *env, 603 const struct bpf_reg_state *reg) 604 { 605 struct bpf_verifier_state *cur = env->cur_state; 606 607 return cur->frame[reg->frameno]; 608 } 609 610 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 611 { 612 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 613 614 /* We need to check that slots between [spi - nr_slots + 1, spi] are 615 * within [0, allocated_stack). 616 * 617 * Please note that the spi grows downwards. For example, a dynptr 618 * takes the size of two stack slots; the first slot will be at 619 * spi and the second slot will be at spi - 1. 620 */ 621 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 622 } 623 624 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 625 const char *obj_kind, int nr_slots) 626 { 627 int off, spi; 628 629 if (!tnum_is_const(reg->var_off)) { 630 verbose(env, "%s has to be at a constant offset\n", obj_kind); 631 return -EINVAL; 632 } 633 634 off = reg->off + reg->var_off.value; 635 if (off % BPF_REG_SIZE) { 636 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 637 return -EINVAL; 638 } 639 640 spi = __get_spi(off); 641 if (spi + 1 < nr_slots) { 642 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 643 return -EINVAL; 644 } 645 646 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 647 return -ERANGE; 648 return spi; 649 } 650 651 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 652 { 653 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 654 } 655 656 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 657 { 658 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 659 } 660 661 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 662 { 663 return stack_slot_obj_get_spi(env, reg, "irq_flag", 1); 664 } 665 666 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 667 { 668 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 669 case DYNPTR_TYPE_LOCAL: 670 return BPF_DYNPTR_TYPE_LOCAL; 671 case DYNPTR_TYPE_RINGBUF: 672 return BPF_DYNPTR_TYPE_RINGBUF; 673 case DYNPTR_TYPE_SKB: 674 return BPF_DYNPTR_TYPE_SKB; 675 case DYNPTR_TYPE_XDP: 676 return BPF_DYNPTR_TYPE_XDP; 677 default: 678 return BPF_DYNPTR_TYPE_INVALID; 679 } 680 } 681 682 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 683 { 684 switch (type) { 685 case BPF_DYNPTR_TYPE_LOCAL: 686 return DYNPTR_TYPE_LOCAL; 687 case BPF_DYNPTR_TYPE_RINGBUF: 688 return DYNPTR_TYPE_RINGBUF; 689 case BPF_DYNPTR_TYPE_SKB: 690 return DYNPTR_TYPE_SKB; 691 case BPF_DYNPTR_TYPE_XDP: 692 return DYNPTR_TYPE_XDP; 693 default: 694 return 0; 695 } 696 } 697 698 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 699 { 700 return type == BPF_DYNPTR_TYPE_RINGBUF; 701 } 702 703 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 704 enum bpf_dynptr_type type, 705 bool first_slot, int dynptr_id); 706 707 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 708 struct bpf_reg_state *reg); 709 710 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 711 struct bpf_reg_state *sreg1, 712 struct bpf_reg_state *sreg2, 713 enum bpf_dynptr_type type) 714 { 715 int id = ++env->id_gen; 716 717 __mark_dynptr_reg(sreg1, type, true, id); 718 __mark_dynptr_reg(sreg2, type, false, id); 719 } 720 721 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 722 struct bpf_reg_state *reg, 723 enum bpf_dynptr_type type) 724 { 725 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 726 } 727 728 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 729 struct bpf_func_state *state, int spi); 730 731 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 732 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 733 { 734 struct bpf_func_state *state = func(env, reg); 735 enum bpf_dynptr_type type; 736 int spi, i, err; 737 738 spi = dynptr_get_spi(env, reg); 739 if (spi < 0) 740 return spi; 741 742 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 743 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 744 * to ensure that for the following example: 745 * [d1][d1][d2][d2] 746 * spi 3 2 1 0 747 * So marking spi = 2 should lead to destruction of both d1 and d2. In 748 * case they do belong to same dynptr, second call won't see slot_type 749 * as STACK_DYNPTR and will simply skip destruction. 750 */ 751 err = destroy_if_dynptr_stack_slot(env, state, spi); 752 if (err) 753 return err; 754 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 755 if (err) 756 return err; 757 758 for (i = 0; i < BPF_REG_SIZE; i++) { 759 state->stack[spi].slot_type[i] = STACK_DYNPTR; 760 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 761 } 762 763 type = arg_to_dynptr_type(arg_type); 764 if (type == BPF_DYNPTR_TYPE_INVALID) 765 return -EINVAL; 766 767 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 768 &state->stack[spi - 1].spilled_ptr, type); 769 770 if (dynptr_type_refcounted(type)) { 771 /* The id is used to track proper releasing */ 772 int id; 773 774 if (clone_ref_obj_id) 775 id = clone_ref_obj_id; 776 else 777 id = acquire_reference(env, insn_idx); 778 779 if (id < 0) 780 return id; 781 782 state->stack[spi].spilled_ptr.ref_obj_id = id; 783 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 784 } 785 786 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 787 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 788 789 return 0; 790 } 791 792 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 793 { 794 int i; 795 796 for (i = 0; i < BPF_REG_SIZE; i++) { 797 state->stack[spi].slot_type[i] = STACK_INVALID; 798 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 799 } 800 801 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 802 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 803 804 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 805 * 806 * While we don't allow reading STACK_INVALID, it is still possible to 807 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 808 * helpers or insns can do partial read of that part without failing, 809 * but check_stack_range_initialized, check_stack_read_var_off, and 810 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 811 * the slot conservatively. Hence we need to prevent those liveness 812 * marking walks. 813 * 814 * This was not a problem before because STACK_INVALID is only set by 815 * default (where the default reg state has its reg->parent as NULL), or 816 * in clean_live_states after REG_LIVE_DONE (at which point 817 * mark_reg_read won't walk reg->parent chain), but not randomly during 818 * verifier state exploration (like we did above). Hence, for our case 819 * parentage chain will still be live (i.e. reg->parent may be 820 * non-NULL), while earlier reg->parent was NULL, so we need 821 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 822 * done later on reads or by mark_dynptr_read as well to unnecessary 823 * mark registers in verifier state. 824 */ 825 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 826 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 827 } 828 829 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 830 { 831 struct bpf_func_state *state = func(env, reg); 832 int spi, ref_obj_id, i; 833 834 spi = dynptr_get_spi(env, reg); 835 if (spi < 0) 836 return spi; 837 838 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 839 invalidate_dynptr(env, state, spi); 840 return 0; 841 } 842 843 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 844 845 /* If the dynptr has a ref_obj_id, then we need to invalidate 846 * two things: 847 * 848 * 1) Any dynptrs with a matching ref_obj_id (clones) 849 * 2) Any slices derived from this dynptr. 850 */ 851 852 /* Invalidate any slices associated with this dynptr */ 853 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 854 855 /* Invalidate any dynptr clones */ 856 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 857 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 858 continue; 859 860 /* it should always be the case that if the ref obj id 861 * matches then the stack slot also belongs to a 862 * dynptr 863 */ 864 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 865 verifier_bug(env, "misconfigured ref_obj_id"); 866 return -EFAULT; 867 } 868 if (state->stack[i].spilled_ptr.dynptr.first_slot) 869 invalidate_dynptr(env, state, i); 870 } 871 872 return 0; 873 } 874 875 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 876 struct bpf_reg_state *reg); 877 878 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 879 { 880 if (!env->allow_ptr_leaks) 881 __mark_reg_not_init(env, reg); 882 else 883 __mark_reg_unknown(env, reg); 884 } 885 886 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 887 struct bpf_func_state *state, int spi) 888 { 889 struct bpf_func_state *fstate; 890 struct bpf_reg_state *dreg; 891 int i, dynptr_id; 892 893 /* We always ensure that STACK_DYNPTR is never set partially, 894 * hence just checking for slot_type[0] is enough. This is 895 * different for STACK_SPILL, where it may be only set for 896 * 1 byte, so code has to use is_spilled_reg. 897 */ 898 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 899 return 0; 900 901 /* Reposition spi to first slot */ 902 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 903 spi = spi + 1; 904 905 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 906 verbose(env, "cannot overwrite referenced dynptr\n"); 907 return -EINVAL; 908 } 909 910 mark_stack_slot_scratched(env, spi); 911 mark_stack_slot_scratched(env, spi - 1); 912 913 /* Writing partially to one dynptr stack slot destroys both. */ 914 for (i = 0; i < BPF_REG_SIZE; i++) { 915 state->stack[spi].slot_type[i] = STACK_INVALID; 916 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 917 } 918 919 dynptr_id = state->stack[spi].spilled_ptr.id; 920 /* Invalidate any slices associated with this dynptr */ 921 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 922 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 923 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 924 continue; 925 if (dreg->dynptr_id == dynptr_id) 926 mark_reg_invalid(env, dreg); 927 })); 928 929 /* Do not release reference state, we are destroying dynptr on stack, 930 * not using some helper to release it. Just reset register. 931 */ 932 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 933 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 934 935 /* Same reason as unmark_stack_slots_dynptr above */ 936 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 937 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 938 939 return 0; 940 } 941 942 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 943 { 944 int spi; 945 946 if (reg->type == CONST_PTR_TO_DYNPTR) 947 return false; 948 949 spi = dynptr_get_spi(env, reg); 950 951 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 952 * error because this just means the stack state hasn't been updated yet. 953 * We will do check_mem_access to check and update stack bounds later. 954 */ 955 if (spi < 0 && spi != -ERANGE) 956 return false; 957 958 /* We don't need to check if the stack slots are marked by previous 959 * dynptr initializations because we allow overwriting existing unreferenced 960 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 961 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 962 * touching are completely destructed before we reinitialize them for a new 963 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 964 * instead of delaying it until the end where the user will get "Unreleased 965 * reference" error. 966 */ 967 return true; 968 } 969 970 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 971 { 972 struct bpf_func_state *state = func(env, reg); 973 int i, spi; 974 975 /* This already represents first slot of initialized bpf_dynptr. 976 * 977 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 978 * check_func_arg_reg_off's logic, so we don't need to check its 979 * offset and alignment. 980 */ 981 if (reg->type == CONST_PTR_TO_DYNPTR) 982 return true; 983 984 spi = dynptr_get_spi(env, reg); 985 if (spi < 0) 986 return false; 987 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 988 return false; 989 990 for (i = 0; i < BPF_REG_SIZE; i++) { 991 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 992 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 993 return false; 994 } 995 996 return true; 997 } 998 999 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1000 enum bpf_arg_type arg_type) 1001 { 1002 struct bpf_func_state *state = func(env, reg); 1003 enum bpf_dynptr_type dynptr_type; 1004 int spi; 1005 1006 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1007 if (arg_type == ARG_PTR_TO_DYNPTR) 1008 return true; 1009 1010 dynptr_type = arg_to_dynptr_type(arg_type); 1011 if (reg->type == CONST_PTR_TO_DYNPTR) { 1012 return reg->dynptr.type == dynptr_type; 1013 } else { 1014 spi = dynptr_get_spi(env, reg); 1015 if (spi < 0) 1016 return false; 1017 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1018 } 1019 } 1020 1021 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1022 1023 static bool in_rcu_cs(struct bpf_verifier_env *env); 1024 1025 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 1026 1027 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1028 struct bpf_kfunc_call_arg_meta *meta, 1029 struct bpf_reg_state *reg, int insn_idx, 1030 struct btf *btf, u32 btf_id, int nr_slots) 1031 { 1032 struct bpf_func_state *state = func(env, reg); 1033 int spi, i, j, id; 1034 1035 spi = iter_get_spi(env, reg, nr_slots); 1036 if (spi < 0) 1037 return spi; 1038 1039 id = acquire_reference(env, insn_idx); 1040 if (id < 0) 1041 return id; 1042 1043 for (i = 0; i < nr_slots; i++) { 1044 struct bpf_stack_state *slot = &state->stack[spi - i]; 1045 struct bpf_reg_state *st = &slot->spilled_ptr; 1046 1047 __mark_reg_known_zero(st); 1048 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1049 if (is_kfunc_rcu_protected(meta)) { 1050 if (in_rcu_cs(env)) 1051 st->type |= MEM_RCU; 1052 else 1053 st->type |= PTR_UNTRUSTED; 1054 } 1055 st->live |= REG_LIVE_WRITTEN; 1056 st->ref_obj_id = i == 0 ? id : 0; 1057 st->iter.btf = btf; 1058 st->iter.btf_id = btf_id; 1059 st->iter.state = BPF_ITER_STATE_ACTIVE; 1060 st->iter.depth = 0; 1061 1062 for (j = 0; j < BPF_REG_SIZE; j++) 1063 slot->slot_type[j] = STACK_ITER; 1064 1065 mark_stack_slot_scratched(env, spi - i); 1066 } 1067 1068 return 0; 1069 } 1070 1071 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1072 struct bpf_reg_state *reg, int nr_slots) 1073 { 1074 struct bpf_func_state *state = func(env, reg); 1075 int spi, i, j; 1076 1077 spi = iter_get_spi(env, reg, nr_slots); 1078 if (spi < 0) 1079 return spi; 1080 1081 for (i = 0; i < nr_slots; i++) { 1082 struct bpf_stack_state *slot = &state->stack[spi - i]; 1083 struct bpf_reg_state *st = &slot->spilled_ptr; 1084 1085 if (i == 0) 1086 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1087 1088 __mark_reg_not_init(env, st); 1089 1090 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1091 st->live |= REG_LIVE_WRITTEN; 1092 1093 for (j = 0; j < BPF_REG_SIZE; j++) 1094 slot->slot_type[j] = STACK_INVALID; 1095 1096 mark_stack_slot_scratched(env, spi - i); 1097 } 1098 1099 return 0; 1100 } 1101 1102 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1103 struct bpf_reg_state *reg, int nr_slots) 1104 { 1105 struct bpf_func_state *state = func(env, reg); 1106 int spi, i, j; 1107 1108 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1109 * will do check_mem_access to check and update stack bounds later, so 1110 * return true for that case. 1111 */ 1112 spi = iter_get_spi(env, reg, nr_slots); 1113 if (spi == -ERANGE) 1114 return true; 1115 if (spi < 0) 1116 return false; 1117 1118 for (i = 0; i < nr_slots; i++) { 1119 struct bpf_stack_state *slot = &state->stack[spi - i]; 1120 1121 for (j = 0; j < BPF_REG_SIZE; j++) 1122 if (slot->slot_type[j] == STACK_ITER) 1123 return false; 1124 } 1125 1126 return true; 1127 } 1128 1129 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1130 struct btf *btf, u32 btf_id, int nr_slots) 1131 { 1132 struct bpf_func_state *state = func(env, reg); 1133 int spi, i, j; 1134 1135 spi = iter_get_spi(env, reg, nr_slots); 1136 if (spi < 0) 1137 return -EINVAL; 1138 1139 for (i = 0; i < nr_slots; i++) { 1140 struct bpf_stack_state *slot = &state->stack[spi - i]; 1141 struct bpf_reg_state *st = &slot->spilled_ptr; 1142 1143 if (st->type & PTR_UNTRUSTED) 1144 return -EPROTO; 1145 /* only main (first) slot has ref_obj_id set */ 1146 if (i == 0 && !st->ref_obj_id) 1147 return -EINVAL; 1148 if (i != 0 && st->ref_obj_id) 1149 return -EINVAL; 1150 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1151 return -EINVAL; 1152 1153 for (j = 0; j < BPF_REG_SIZE; j++) 1154 if (slot->slot_type[j] != STACK_ITER) 1155 return -EINVAL; 1156 } 1157 1158 return 0; 1159 } 1160 1161 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx); 1162 static int release_irq_state(struct bpf_verifier_state *state, int id); 1163 1164 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env, 1165 struct bpf_kfunc_call_arg_meta *meta, 1166 struct bpf_reg_state *reg, int insn_idx, 1167 int kfunc_class) 1168 { 1169 struct bpf_func_state *state = func(env, reg); 1170 struct bpf_stack_state *slot; 1171 struct bpf_reg_state *st; 1172 int spi, i, id; 1173 1174 spi = irq_flag_get_spi(env, reg); 1175 if (spi < 0) 1176 return spi; 1177 1178 id = acquire_irq_state(env, insn_idx); 1179 if (id < 0) 1180 return id; 1181 1182 slot = &state->stack[spi]; 1183 st = &slot->spilled_ptr; 1184 1185 __mark_reg_known_zero(st); 1186 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1187 st->live |= REG_LIVE_WRITTEN; 1188 st->ref_obj_id = id; 1189 st->irq.kfunc_class = kfunc_class; 1190 1191 for (i = 0; i < BPF_REG_SIZE; i++) 1192 slot->slot_type[i] = STACK_IRQ_FLAG; 1193 1194 mark_stack_slot_scratched(env, spi); 1195 return 0; 1196 } 1197 1198 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1199 int kfunc_class) 1200 { 1201 struct bpf_func_state *state = func(env, reg); 1202 struct bpf_stack_state *slot; 1203 struct bpf_reg_state *st; 1204 int spi, i, err; 1205 1206 spi = irq_flag_get_spi(env, reg); 1207 if (spi < 0) 1208 return spi; 1209 1210 slot = &state->stack[spi]; 1211 st = &slot->spilled_ptr; 1212 1213 if (st->irq.kfunc_class != kfunc_class) { 1214 const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1215 const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1216 1217 verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n", 1218 flag_kfunc, used_kfunc); 1219 return -EINVAL; 1220 } 1221 1222 err = release_irq_state(env->cur_state, st->ref_obj_id); 1223 WARN_ON_ONCE(err && err != -EACCES); 1224 if (err) { 1225 int insn_idx = 0; 1226 1227 for (int i = 0; i < env->cur_state->acquired_refs; i++) { 1228 if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) { 1229 insn_idx = env->cur_state->refs[i].insn_idx; 1230 break; 1231 } 1232 } 1233 1234 verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n", 1235 env->cur_state->active_irq_id, insn_idx); 1236 return err; 1237 } 1238 1239 __mark_reg_not_init(env, st); 1240 1241 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1242 st->live |= REG_LIVE_WRITTEN; 1243 1244 for (i = 0; i < BPF_REG_SIZE; i++) 1245 slot->slot_type[i] = STACK_INVALID; 1246 1247 mark_stack_slot_scratched(env, spi); 1248 return 0; 1249 } 1250 1251 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1252 { 1253 struct bpf_func_state *state = func(env, reg); 1254 struct bpf_stack_state *slot; 1255 int spi, i; 1256 1257 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1258 * will do check_mem_access to check and update stack bounds later, so 1259 * return true for that case. 1260 */ 1261 spi = irq_flag_get_spi(env, reg); 1262 if (spi == -ERANGE) 1263 return true; 1264 if (spi < 0) 1265 return false; 1266 1267 slot = &state->stack[spi]; 1268 1269 for (i = 0; i < BPF_REG_SIZE; i++) 1270 if (slot->slot_type[i] == STACK_IRQ_FLAG) 1271 return false; 1272 return true; 1273 } 1274 1275 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1276 { 1277 struct bpf_func_state *state = func(env, reg); 1278 struct bpf_stack_state *slot; 1279 struct bpf_reg_state *st; 1280 int spi, i; 1281 1282 spi = irq_flag_get_spi(env, reg); 1283 if (spi < 0) 1284 return -EINVAL; 1285 1286 slot = &state->stack[spi]; 1287 st = &slot->spilled_ptr; 1288 1289 if (!st->ref_obj_id) 1290 return -EINVAL; 1291 1292 for (i = 0; i < BPF_REG_SIZE; i++) 1293 if (slot->slot_type[i] != STACK_IRQ_FLAG) 1294 return -EINVAL; 1295 return 0; 1296 } 1297 1298 /* Check if given stack slot is "special": 1299 * - spilled register state (STACK_SPILL); 1300 * - dynptr state (STACK_DYNPTR); 1301 * - iter state (STACK_ITER). 1302 * - irq flag state (STACK_IRQ_FLAG) 1303 */ 1304 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1305 { 1306 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1307 1308 switch (type) { 1309 case STACK_SPILL: 1310 case STACK_DYNPTR: 1311 case STACK_ITER: 1312 case STACK_IRQ_FLAG: 1313 return true; 1314 case STACK_INVALID: 1315 case STACK_MISC: 1316 case STACK_ZERO: 1317 return false; 1318 default: 1319 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1320 return true; 1321 } 1322 } 1323 1324 /* The reg state of a pointer or a bounded scalar was saved when 1325 * it was spilled to the stack. 1326 */ 1327 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1328 { 1329 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1330 } 1331 1332 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1333 { 1334 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1335 stack->spilled_ptr.type == SCALAR_VALUE; 1336 } 1337 1338 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack) 1339 { 1340 return stack->slot_type[0] == STACK_SPILL && 1341 stack->spilled_ptr.type == SCALAR_VALUE; 1342 } 1343 1344 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1345 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1346 * more precise STACK_ZERO. 1347 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged 1348 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is 1349 * unnecessary as both are considered equivalent when loading data and pruning, 1350 * in case of unprivileged mode it will be incorrect to allow reads of invalid 1351 * slots. 1352 */ 1353 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1354 { 1355 if (*stype == STACK_ZERO) 1356 return; 1357 if (*stype == STACK_INVALID) 1358 return; 1359 *stype = STACK_MISC; 1360 } 1361 1362 static void scrub_spilled_slot(u8 *stype) 1363 { 1364 if (*stype != STACK_INVALID) 1365 *stype = STACK_MISC; 1366 } 1367 1368 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1369 * small to hold src. This is different from krealloc since we don't want to preserve 1370 * the contents of dst. 1371 * 1372 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1373 * not be allocated. 1374 */ 1375 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1376 { 1377 size_t alloc_bytes; 1378 void *orig = dst; 1379 size_t bytes; 1380 1381 if (ZERO_OR_NULL_PTR(src)) 1382 goto out; 1383 1384 if (unlikely(check_mul_overflow(n, size, &bytes))) 1385 return NULL; 1386 1387 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1388 dst = krealloc(orig, alloc_bytes, flags); 1389 if (!dst) { 1390 kfree(orig); 1391 return NULL; 1392 } 1393 1394 memcpy(dst, src, bytes); 1395 out: 1396 return dst ? dst : ZERO_SIZE_PTR; 1397 } 1398 1399 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1400 * small to hold new_n items. new items are zeroed out if the array grows. 1401 * 1402 * Contrary to krealloc_array, does not free arr if new_n is zero. 1403 */ 1404 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1405 { 1406 size_t alloc_size; 1407 void *new_arr; 1408 1409 if (!new_n || old_n == new_n) 1410 goto out; 1411 1412 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1413 new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT); 1414 if (!new_arr) { 1415 kfree(arr); 1416 return NULL; 1417 } 1418 arr = new_arr; 1419 1420 if (new_n > old_n) 1421 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1422 1423 out: 1424 return arr ? arr : ZERO_SIZE_PTR; 1425 } 1426 1427 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) 1428 { 1429 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1430 sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT); 1431 if (!dst->refs) 1432 return -ENOMEM; 1433 1434 dst->acquired_refs = src->acquired_refs; 1435 dst->active_locks = src->active_locks; 1436 dst->active_preempt_locks = src->active_preempt_locks; 1437 dst->active_rcu_lock = src->active_rcu_lock; 1438 dst->active_irq_id = src->active_irq_id; 1439 dst->active_lock_id = src->active_lock_id; 1440 dst->active_lock_ptr = src->active_lock_ptr; 1441 return 0; 1442 } 1443 1444 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1445 { 1446 size_t n = src->allocated_stack / BPF_REG_SIZE; 1447 1448 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1449 GFP_KERNEL_ACCOUNT); 1450 if (!dst->stack) 1451 return -ENOMEM; 1452 1453 dst->allocated_stack = src->allocated_stack; 1454 return 0; 1455 } 1456 1457 static int resize_reference_state(struct bpf_verifier_state *state, size_t n) 1458 { 1459 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1460 sizeof(struct bpf_reference_state)); 1461 if (!state->refs) 1462 return -ENOMEM; 1463 1464 state->acquired_refs = n; 1465 return 0; 1466 } 1467 1468 /* Possibly update state->allocated_stack to be at least size bytes. Also 1469 * possibly update the function's high-water mark in its bpf_subprog_info. 1470 */ 1471 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1472 { 1473 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1474 1475 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1476 size = round_up(size, BPF_REG_SIZE); 1477 n = size / BPF_REG_SIZE; 1478 1479 if (old_n >= n) 1480 return 0; 1481 1482 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1483 if (!state->stack) 1484 return -ENOMEM; 1485 1486 state->allocated_stack = size; 1487 1488 /* update known max for given subprogram */ 1489 if (env->subprog_info[state->subprogno].stack_depth < size) 1490 env->subprog_info[state->subprogno].stack_depth = size; 1491 1492 return 0; 1493 } 1494 1495 /* Acquire a pointer id from the env and update the state->refs to include 1496 * this new pointer reference. 1497 * On success, returns a valid pointer id to associate with the register 1498 * On failure, returns a negative errno. 1499 */ 1500 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1501 { 1502 struct bpf_verifier_state *state = env->cur_state; 1503 int new_ofs = state->acquired_refs; 1504 int err; 1505 1506 err = resize_reference_state(state, state->acquired_refs + 1); 1507 if (err) 1508 return NULL; 1509 state->refs[new_ofs].insn_idx = insn_idx; 1510 1511 return &state->refs[new_ofs]; 1512 } 1513 1514 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx) 1515 { 1516 struct bpf_reference_state *s; 1517 1518 s = acquire_reference_state(env, insn_idx); 1519 if (!s) 1520 return -ENOMEM; 1521 s->type = REF_TYPE_PTR; 1522 s->id = ++env->id_gen; 1523 return s->id; 1524 } 1525 1526 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type, 1527 int id, void *ptr) 1528 { 1529 struct bpf_verifier_state *state = env->cur_state; 1530 struct bpf_reference_state *s; 1531 1532 s = acquire_reference_state(env, insn_idx); 1533 if (!s) 1534 return -ENOMEM; 1535 s->type = type; 1536 s->id = id; 1537 s->ptr = ptr; 1538 1539 state->active_locks++; 1540 state->active_lock_id = id; 1541 state->active_lock_ptr = ptr; 1542 return 0; 1543 } 1544 1545 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx) 1546 { 1547 struct bpf_verifier_state *state = env->cur_state; 1548 struct bpf_reference_state *s; 1549 1550 s = acquire_reference_state(env, insn_idx); 1551 if (!s) 1552 return -ENOMEM; 1553 s->type = REF_TYPE_IRQ; 1554 s->id = ++env->id_gen; 1555 1556 state->active_irq_id = s->id; 1557 return s->id; 1558 } 1559 1560 static void release_reference_state(struct bpf_verifier_state *state, int idx) 1561 { 1562 int last_idx; 1563 size_t rem; 1564 1565 /* IRQ state requires the relative ordering of elements remaining the 1566 * same, since it relies on the refs array to behave as a stack, so that 1567 * it can detect out-of-order IRQ restore. Hence use memmove to shift 1568 * the array instead of swapping the final element into the deleted idx. 1569 */ 1570 last_idx = state->acquired_refs - 1; 1571 rem = state->acquired_refs - idx - 1; 1572 if (last_idx && idx != last_idx) 1573 memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem); 1574 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1575 state->acquired_refs--; 1576 return; 1577 } 1578 1579 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id) 1580 { 1581 int i; 1582 1583 for (i = 0; i < state->acquired_refs; i++) 1584 if (state->refs[i].id == ptr_id) 1585 return true; 1586 1587 return false; 1588 } 1589 1590 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr) 1591 { 1592 void *prev_ptr = NULL; 1593 u32 prev_id = 0; 1594 int i; 1595 1596 for (i = 0; i < state->acquired_refs; i++) { 1597 if (state->refs[i].type == type && state->refs[i].id == id && 1598 state->refs[i].ptr == ptr) { 1599 release_reference_state(state, i); 1600 state->active_locks--; 1601 /* Reassign active lock (id, ptr). */ 1602 state->active_lock_id = prev_id; 1603 state->active_lock_ptr = prev_ptr; 1604 return 0; 1605 } 1606 if (state->refs[i].type & REF_TYPE_LOCK_MASK) { 1607 prev_id = state->refs[i].id; 1608 prev_ptr = state->refs[i].ptr; 1609 } 1610 } 1611 return -EINVAL; 1612 } 1613 1614 static int release_irq_state(struct bpf_verifier_state *state, int id) 1615 { 1616 u32 prev_id = 0; 1617 int i; 1618 1619 if (id != state->active_irq_id) 1620 return -EACCES; 1621 1622 for (i = 0; i < state->acquired_refs; i++) { 1623 if (state->refs[i].type != REF_TYPE_IRQ) 1624 continue; 1625 if (state->refs[i].id == id) { 1626 release_reference_state(state, i); 1627 state->active_irq_id = prev_id; 1628 return 0; 1629 } else { 1630 prev_id = state->refs[i].id; 1631 } 1632 } 1633 return -EINVAL; 1634 } 1635 1636 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type, 1637 int id, void *ptr) 1638 { 1639 int i; 1640 1641 for (i = 0; i < state->acquired_refs; i++) { 1642 struct bpf_reference_state *s = &state->refs[i]; 1643 1644 if (!(s->type & type)) 1645 continue; 1646 1647 if (s->id == id && s->ptr == ptr) 1648 return s; 1649 } 1650 return NULL; 1651 } 1652 1653 static void update_peak_states(struct bpf_verifier_env *env) 1654 { 1655 u32 cur_states; 1656 1657 cur_states = env->explored_states_size + env->free_list_size + env->num_backedges; 1658 env->peak_states = max(env->peak_states, cur_states); 1659 } 1660 1661 static void free_func_state(struct bpf_func_state *state) 1662 { 1663 if (!state) 1664 return; 1665 kfree(state->stack); 1666 kfree(state); 1667 } 1668 1669 static void clear_jmp_history(struct bpf_verifier_state *state) 1670 { 1671 kfree(state->jmp_history); 1672 state->jmp_history = NULL; 1673 state->jmp_history_cnt = 0; 1674 } 1675 1676 static void free_verifier_state(struct bpf_verifier_state *state, 1677 bool free_self) 1678 { 1679 int i; 1680 1681 for (i = 0; i <= state->curframe; i++) { 1682 free_func_state(state->frame[i]); 1683 state->frame[i] = NULL; 1684 } 1685 kfree(state->refs); 1686 clear_jmp_history(state); 1687 if (free_self) 1688 kfree(state); 1689 } 1690 1691 /* struct bpf_verifier_state->parent refers to states 1692 * that are in either of env->{expored_states,free_list}. 1693 * In both cases the state is contained in struct bpf_verifier_state_list. 1694 */ 1695 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st) 1696 { 1697 if (st->parent) 1698 return container_of(st->parent, struct bpf_verifier_state_list, state); 1699 return NULL; 1700 } 1701 1702 static bool incomplete_read_marks(struct bpf_verifier_env *env, 1703 struct bpf_verifier_state *st); 1704 1705 /* A state can be freed if it is no longer referenced: 1706 * - is in the env->free_list; 1707 * - has no children states; 1708 */ 1709 static void maybe_free_verifier_state(struct bpf_verifier_env *env, 1710 struct bpf_verifier_state_list *sl) 1711 { 1712 if (!sl->in_free_list 1713 || sl->state.branches != 0 1714 || incomplete_read_marks(env, &sl->state)) 1715 return; 1716 list_del(&sl->node); 1717 free_verifier_state(&sl->state, false); 1718 kfree(sl); 1719 env->free_list_size--; 1720 } 1721 1722 /* copy verifier state from src to dst growing dst stack space 1723 * when necessary to accommodate larger src stack 1724 */ 1725 static int copy_func_state(struct bpf_func_state *dst, 1726 const struct bpf_func_state *src) 1727 { 1728 memcpy(dst, src, offsetof(struct bpf_func_state, stack)); 1729 return copy_stack_state(dst, src); 1730 } 1731 1732 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1733 const struct bpf_verifier_state *src) 1734 { 1735 struct bpf_func_state *dst; 1736 int i, err; 1737 1738 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1739 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1740 GFP_KERNEL_ACCOUNT); 1741 if (!dst_state->jmp_history) 1742 return -ENOMEM; 1743 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1744 1745 /* if dst has more stack frames then src frame, free them, this is also 1746 * necessary in case of exceptional exits using bpf_throw. 1747 */ 1748 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1749 free_func_state(dst_state->frame[i]); 1750 dst_state->frame[i] = NULL; 1751 } 1752 err = copy_reference_state(dst_state, src); 1753 if (err) 1754 return err; 1755 dst_state->speculative = src->speculative; 1756 dst_state->in_sleepable = src->in_sleepable; 1757 dst_state->curframe = src->curframe; 1758 dst_state->branches = src->branches; 1759 dst_state->parent = src->parent; 1760 dst_state->first_insn_idx = src->first_insn_idx; 1761 dst_state->last_insn_idx = src->last_insn_idx; 1762 dst_state->dfs_depth = src->dfs_depth; 1763 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1764 dst_state->may_goto_depth = src->may_goto_depth; 1765 dst_state->equal_state = src->equal_state; 1766 for (i = 0; i <= src->curframe; i++) { 1767 dst = dst_state->frame[i]; 1768 if (!dst) { 1769 dst = kzalloc(sizeof(*dst), GFP_KERNEL_ACCOUNT); 1770 if (!dst) 1771 return -ENOMEM; 1772 dst_state->frame[i] = dst; 1773 } 1774 err = copy_func_state(dst, src->frame[i]); 1775 if (err) 1776 return err; 1777 } 1778 return 0; 1779 } 1780 1781 static u32 state_htab_size(struct bpf_verifier_env *env) 1782 { 1783 return env->prog->len; 1784 } 1785 1786 static struct list_head *explored_state(struct bpf_verifier_env *env, int idx) 1787 { 1788 struct bpf_verifier_state *cur = env->cur_state; 1789 struct bpf_func_state *state = cur->frame[cur->curframe]; 1790 1791 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1792 } 1793 1794 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1795 { 1796 int fr; 1797 1798 if (a->curframe != b->curframe) 1799 return false; 1800 1801 for (fr = a->curframe; fr >= 0; fr--) 1802 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1803 return false; 1804 1805 return true; 1806 } 1807 1808 /* Return IP for a given frame in a call stack */ 1809 static u32 frame_insn_idx(struct bpf_verifier_state *st, u32 frame) 1810 { 1811 return frame == st->curframe 1812 ? st->insn_idx 1813 : st->frame[frame + 1]->callsite; 1814 } 1815 1816 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC, 1817 * if such frame exists form a corresponding @callchain as an array of 1818 * call sites leading to this frame and SCC id. 1819 * E.g.: 1820 * 1821 * void foo() { A: loop {... SCC#1 ...}; } 1822 * void bar() { B: loop { C: foo(); ... SCC#2 ... } 1823 * D: loop { E: foo(); ... SCC#3 ... } } 1824 * void main() { F: bar(); } 1825 * 1826 * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending 1827 * on @st frame call sites being (F,C,A) or (F,E,A). 1828 */ 1829 static bool compute_scc_callchain(struct bpf_verifier_env *env, 1830 struct bpf_verifier_state *st, 1831 struct bpf_scc_callchain *callchain) 1832 { 1833 u32 i, scc, insn_idx; 1834 1835 memset(callchain, 0, sizeof(*callchain)); 1836 for (i = 0; i <= st->curframe; i++) { 1837 insn_idx = frame_insn_idx(st, i); 1838 scc = env->insn_aux_data[insn_idx].scc; 1839 if (scc) { 1840 callchain->scc = scc; 1841 break; 1842 } else if (i < st->curframe) { 1843 callchain->callsites[i] = insn_idx; 1844 } else { 1845 return false; 1846 } 1847 } 1848 return true; 1849 } 1850 1851 /* Check if bpf_scc_visit instance for @callchain exists. */ 1852 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env, 1853 struct bpf_scc_callchain *callchain) 1854 { 1855 struct bpf_scc_info *info = env->scc_info[callchain->scc]; 1856 struct bpf_scc_visit *visits = info->visits; 1857 u32 i; 1858 1859 if (!info) 1860 return NULL; 1861 for (i = 0; i < info->num_visits; i++) 1862 if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0) 1863 return &visits[i]; 1864 return NULL; 1865 } 1866 1867 /* Allocate a new bpf_scc_visit instance corresponding to @callchain. 1868 * Allocated instances are alive for a duration of the do_check_common() 1869 * call and are freed by free_states(). 1870 */ 1871 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env, 1872 struct bpf_scc_callchain *callchain) 1873 { 1874 struct bpf_scc_visit *visit; 1875 struct bpf_scc_info *info; 1876 u32 scc, num_visits; 1877 u64 new_sz; 1878 1879 scc = callchain->scc; 1880 info = env->scc_info[scc]; 1881 num_visits = info ? info->num_visits : 0; 1882 new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1); 1883 info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT); 1884 if (!info) 1885 return NULL; 1886 env->scc_info[scc] = info; 1887 info->num_visits = num_visits + 1; 1888 visit = &info->visits[num_visits]; 1889 memset(visit, 0, sizeof(*visit)); 1890 memcpy(&visit->callchain, callchain, sizeof(*callchain)); 1891 return visit; 1892 } 1893 1894 /* Form a string '(callsite#1,callsite#2,...,scc)' in env->tmp_str_buf */ 1895 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain) 1896 { 1897 char *buf = env->tmp_str_buf; 1898 int i, delta = 0; 1899 1900 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "("); 1901 for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) { 1902 if (!callchain->callsites[i]) 1903 break; 1904 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,", 1905 callchain->callsites[i]); 1906 } 1907 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc); 1908 return env->tmp_str_buf; 1909 } 1910 1911 /* If callchain for @st exists (@st is in some SCC), ensure that 1912 * bpf_scc_visit instance for this callchain exists. 1913 * If instance does not exist or is empty, assign visit->entry_state to @st. 1914 */ 1915 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1916 { 1917 struct bpf_scc_callchain *callchain = &env->callchain_buf; 1918 struct bpf_scc_visit *visit; 1919 1920 if (!compute_scc_callchain(env, st, callchain)) 1921 return 0; 1922 visit = scc_visit_lookup(env, callchain); 1923 visit = visit ?: scc_visit_alloc(env, callchain); 1924 if (!visit) 1925 return -ENOMEM; 1926 if (!visit->entry_state) { 1927 visit->entry_state = st; 1928 if (env->log.level & BPF_LOG_LEVEL2) 1929 verbose(env, "SCC enter %s\n", format_callchain(env, callchain)); 1930 } 1931 return 0; 1932 } 1933 1934 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit); 1935 1936 /* If callchain for @st exists (@st is in some SCC), make it empty: 1937 * - set visit->entry_state to NULL; 1938 * - flush accumulated backedges. 1939 */ 1940 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1941 { 1942 struct bpf_scc_callchain *callchain = &env->callchain_buf; 1943 struct bpf_scc_visit *visit; 1944 1945 if (!compute_scc_callchain(env, st, callchain)) 1946 return 0; 1947 visit = scc_visit_lookup(env, callchain); 1948 if (!visit) { 1949 verifier_bug(env, "scc exit: no visit info for call chain %s", 1950 format_callchain(env, callchain)); 1951 return -EFAULT; 1952 } 1953 if (visit->entry_state != st) 1954 return 0; 1955 if (env->log.level & BPF_LOG_LEVEL2) 1956 verbose(env, "SCC exit %s\n", format_callchain(env, callchain)); 1957 visit->entry_state = NULL; 1958 env->num_backedges -= visit->num_backedges; 1959 visit->num_backedges = 0; 1960 update_peak_states(env); 1961 return propagate_backedges(env, visit); 1962 } 1963 1964 /* Lookup an bpf_scc_visit instance corresponding to @st callchain 1965 * and add @backedge to visit->backedges. @st callchain must exist. 1966 */ 1967 static int add_scc_backedge(struct bpf_verifier_env *env, 1968 struct bpf_verifier_state *st, 1969 struct bpf_scc_backedge *backedge) 1970 { 1971 struct bpf_scc_callchain *callchain = &env->callchain_buf; 1972 struct bpf_scc_visit *visit; 1973 1974 if (!compute_scc_callchain(env, st, callchain)) { 1975 verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d", 1976 st->insn_idx); 1977 return -EFAULT; 1978 } 1979 visit = scc_visit_lookup(env, callchain); 1980 if (!visit) { 1981 verifier_bug(env, "add backedge: no visit info for call chain %s", 1982 format_callchain(env, callchain)); 1983 return -EFAULT; 1984 } 1985 if (env->log.level & BPF_LOG_LEVEL2) 1986 verbose(env, "SCC backedge %s\n", format_callchain(env, callchain)); 1987 backedge->next = visit->backedges; 1988 visit->backedges = backedge; 1989 visit->num_backedges++; 1990 env->num_backedges++; 1991 update_peak_states(env); 1992 return 0; 1993 } 1994 1995 /* bpf_reg_state->live marks for registers in a state @st are incomplete, 1996 * if state @st is in some SCC and not all execution paths starting at this 1997 * SCC are fully explored. 1998 */ 1999 static bool incomplete_read_marks(struct bpf_verifier_env *env, 2000 struct bpf_verifier_state *st) 2001 { 2002 struct bpf_scc_callchain *callchain = &env->callchain_buf; 2003 struct bpf_scc_visit *visit; 2004 2005 if (!compute_scc_callchain(env, st, callchain)) 2006 return false; 2007 visit = scc_visit_lookup(env, callchain); 2008 if (!visit) 2009 return false; 2010 return !!visit->backedges; 2011 } 2012 2013 static void free_backedges(struct bpf_scc_visit *visit) 2014 { 2015 struct bpf_scc_backedge *backedge, *next; 2016 2017 for (backedge = visit->backedges; backedge; backedge = next) { 2018 free_verifier_state(&backedge->state, false); 2019 next = backedge->next; 2020 kvfree(backedge); 2021 } 2022 visit->backedges = NULL; 2023 } 2024 2025 static int update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 2026 { 2027 struct bpf_verifier_state_list *sl = NULL, *parent_sl; 2028 struct bpf_verifier_state *parent; 2029 int err; 2030 2031 while (st) { 2032 u32 br = --st->branches; 2033 2034 /* verifier_bug_if(br > 1, ...) technically makes sense here, 2035 * but see comment in push_stack(), hence: 2036 */ 2037 verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br); 2038 if (br) 2039 break; 2040 err = maybe_exit_scc(env, st); 2041 if (err) 2042 return err; 2043 parent = st->parent; 2044 parent_sl = state_parent_as_list(st); 2045 if (sl) 2046 maybe_free_verifier_state(env, sl); 2047 st = parent; 2048 sl = parent_sl; 2049 } 2050 return 0; 2051 } 2052 2053 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 2054 int *insn_idx, bool pop_log) 2055 { 2056 struct bpf_verifier_state *cur = env->cur_state; 2057 struct bpf_verifier_stack_elem *elem, *head = env->head; 2058 int err; 2059 2060 if (env->head == NULL) 2061 return -ENOENT; 2062 2063 if (cur) { 2064 err = copy_verifier_state(cur, &head->st); 2065 if (err) 2066 return err; 2067 } 2068 if (pop_log) 2069 bpf_vlog_reset(&env->log, head->log_pos); 2070 if (insn_idx) 2071 *insn_idx = head->insn_idx; 2072 if (prev_insn_idx) 2073 *prev_insn_idx = head->prev_insn_idx; 2074 elem = head->next; 2075 free_verifier_state(&head->st, false); 2076 kfree(head); 2077 env->head = elem; 2078 env->stack_size--; 2079 return 0; 2080 } 2081 2082 static bool error_recoverable_with_nospec(int err) 2083 { 2084 /* Should only return true for non-fatal errors that are allowed to 2085 * occur during speculative verification. For these we can insert a 2086 * nospec and the program might still be accepted. Do not include 2087 * something like ENOMEM because it is likely to re-occur for the next 2088 * architectural path once it has been recovered-from in all speculative 2089 * paths. 2090 */ 2091 return err == -EPERM || err == -EACCES || err == -EINVAL; 2092 } 2093 2094 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 2095 int insn_idx, int prev_insn_idx, 2096 bool speculative) 2097 { 2098 struct bpf_verifier_state *cur = env->cur_state; 2099 struct bpf_verifier_stack_elem *elem; 2100 int err; 2101 2102 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT); 2103 if (!elem) 2104 return NULL; 2105 2106 elem->insn_idx = insn_idx; 2107 elem->prev_insn_idx = prev_insn_idx; 2108 elem->next = env->head; 2109 elem->log_pos = env->log.end_pos; 2110 env->head = elem; 2111 env->stack_size++; 2112 err = copy_verifier_state(&elem->st, cur); 2113 if (err) 2114 return NULL; 2115 elem->st.speculative |= speculative; 2116 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2117 verbose(env, "The sequence of %d jumps is too complex.\n", 2118 env->stack_size); 2119 return NULL; 2120 } 2121 if (elem->st.parent) { 2122 ++elem->st.parent->branches; 2123 /* WARN_ON(branches > 2) technically makes sense here, 2124 * but 2125 * 1. speculative states will bump 'branches' for non-branch 2126 * instructions 2127 * 2. is_state_visited() heuristics may decide not to create 2128 * a new state for a sequence of branches and all such current 2129 * and cloned states will be pointing to a single parent state 2130 * which might have large 'branches' count. 2131 */ 2132 } 2133 return &elem->st; 2134 } 2135 2136 #define CALLER_SAVED_REGS 6 2137 static const int caller_saved[CALLER_SAVED_REGS] = { 2138 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 2139 }; 2140 2141 /* This helper doesn't clear reg->id */ 2142 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2143 { 2144 reg->var_off = tnum_const(imm); 2145 reg->smin_value = (s64)imm; 2146 reg->smax_value = (s64)imm; 2147 reg->umin_value = imm; 2148 reg->umax_value = imm; 2149 2150 reg->s32_min_value = (s32)imm; 2151 reg->s32_max_value = (s32)imm; 2152 reg->u32_min_value = (u32)imm; 2153 reg->u32_max_value = (u32)imm; 2154 } 2155 2156 /* Mark the unknown part of a register (variable offset or scalar value) as 2157 * known to have the value @imm. 2158 */ 2159 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 2160 { 2161 /* Clear off and union(map_ptr, range) */ 2162 memset(((u8 *)reg) + sizeof(reg->type), 0, 2163 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 2164 reg->id = 0; 2165 reg->ref_obj_id = 0; 2166 ___mark_reg_known(reg, imm); 2167 } 2168 2169 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 2170 { 2171 reg->var_off = tnum_const_subreg(reg->var_off, imm); 2172 reg->s32_min_value = (s32)imm; 2173 reg->s32_max_value = (s32)imm; 2174 reg->u32_min_value = (u32)imm; 2175 reg->u32_max_value = (u32)imm; 2176 } 2177 2178 /* Mark the 'variable offset' part of a register as zero. This should be 2179 * used only on registers holding a pointer type. 2180 */ 2181 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 2182 { 2183 __mark_reg_known(reg, 0); 2184 } 2185 2186 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 2187 { 2188 __mark_reg_known(reg, 0); 2189 reg->type = SCALAR_VALUE; 2190 /* all scalars are assumed imprecise initially (unless unprivileged, 2191 * in which case everything is forced to be precise) 2192 */ 2193 reg->precise = !env->bpf_capable; 2194 } 2195 2196 static void mark_reg_known_zero(struct bpf_verifier_env *env, 2197 struct bpf_reg_state *regs, u32 regno) 2198 { 2199 if (WARN_ON(regno >= MAX_BPF_REG)) { 2200 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 2201 /* Something bad happened, let's kill all regs */ 2202 for (regno = 0; regno < MAX_BPF_REG; regno++) 2203 __mark_reg_not_init(env, regs + regno); 2204 return; 2205 } 2206 __mark_reg_known_zero(regs + regno); 2207 } 2208 2209 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 2210 bool first_slot, int dynptr_id) 2211 { 2212 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 2213 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 2214 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 2215 */ 2216 __mark_reg_known_zero(reg); 2217 reg->type = CONST_PTR_TO_DYNPTR; 2218 /* Give each dynptr a unique id to uniquely associate slices to it. */ 2219 reg->id = dynptr_id; 2220 reg->dynptr.type = type; 2221 reg->dynptr.first_slot = first_slot; 2222 } 2223 2224 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 2225 { 2226 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 2227 const struct bpf_map *map = reg->map_ptr; 2228 2229 if (map->inner_map_meta) { 2230 reg->type = CONST_PTR_TO_MAP; 2231 reg->map_ptr = map->inner_map_meta; 2232 /* transfer reg's id which is unique for every map_lookup_elem 2233 * as UID of the inner map. 2234 */ 2235 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 2236 reg->map_uid = reg->id; 2237 if (btf_record_has_field(map->inner_map_meta->record, BPF_WORKQUEUE)) 2238 reg->map_uid = reg->id; 2239 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 2240 reg->type = PTR_TO_XDP_SOCK; 2241 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 2242 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 2243 reg->type = PTR_TO_SOCKET; 2244 } else { 2245 reg->type = PTR_TO_MAP_VALUE; 2246 } 2247 return; 2248 } 2249 2250 reg->type &= ~PTR_MAYBE_NULL; 2251 } 2252 2253 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 2254 struct btf_field_graph_root *ds_head) 2255 { 2256 __mark_reg_known_zero(®s[regno]); 2257 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 2258 regs[regno].btf = ds_head->btf; 2259 regs[regno].btf_id = ds_head->value_btf_id; 2260 regs[regno].off = ds_head->node_offset; 2261 } 2262 2263 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 2264 { 2265 return type_is_pkt_pointer(reg->type); 2266 } 2267 2268 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 2269 { 2270 return reg_is_pkt_pointer(reg) || 2271 reg->type == PTR_TO_PACKET_END; 2272 } 2273 2274 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 2275 { 2276 return base_type(reg->type) == PTR_TO_MEM && 2277 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 2278 } 2279 2280 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 2281 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 2282 enum bpf_reg_type which) 2283 { 2284 /* The register can already have a range from prior markings. 2285 * This is fine as long as it hasn't been advanced from its 2286 * origin. 2287 */ 2288 return reg->type == which && 2289 reg->id == 0 && 2290 reg->off == 0 && 2291 tnum_equals_const(reg->var_off, 0); 2292 } 2293 2294 /* Reset the min/max bounds of a register */ 2295 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2296 { 2297 reg->smin_value = S64_MIN; 2298 reg->smax_value = S64_MAX; 2299 reg->umin_value = 0; 2300 reg->umax_value = U64_MAX; 2301 2302 reg->s32_min_value = S32_MIN; 2303 reg->s32_max_value = S32_MAX; 2304 reg->u32_min_value = 0; 2305 reg->u32_max_value = U32_MAX; 2306 } 2307 2308 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2309 { 2310 reg->smin_value = S64_MIN; 2311 reg->smax_value = S64_MAX; 2312 reg->umin_value = 0; 2313 reg->umax_value = U64_MAX; 2314 } 2315 2316 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2317 { 2318 reg->s32_min_value = S32_MIN; 2319 reg->s32_max_value = S32_MAX; 2320 reg->u32_min_value = 0; 2321 reg->u32_max_value = U32_MAX; 2322 } 2323 2324 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2325 { 2326 struct tnum var32_off = tnum_subreg(reg->var_off); 2327 2328 /* min signed is max(sign bit) | min(other bits) */ 2329 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2330 var32_off.value | (var32_off.mask & S32_MIN)); 2331 /* max signed is min(sign bit) | max(other bits) */ 2332 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2333 var32_off.value | (var32_off.mask & S32_MAX)); 2334 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2335 reg->u32_max_value = min(reg->u32_max_value, 2336 (u32)(var32_off.value | var32_off.mask)); 2337 } 2338 2339 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2340 { 2341 /* min signed is max(sign bit) | min(other bits) */ 2342 reg->smin_value = max_t(s64, reg->smin_value, 2343 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2344 /* max signed is min(sign bit) | max(other bits) */ 2345 reg->smax_value = min_t(s64, reg->smax_value, 2346 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2347 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2348 reg->umax_value = min(reg->umax_value, 2349 reg->var_off.value | reg->var_off.mask); 2350 } 2351 2352 static void __update_reg_bounds(struct bpf_reg_state *reg) 2353 { 2354 __update_reg32_bounds(reg); 2355 __update_reg64_bounds(reg); 2356 } 2357 2358 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2359 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2360 { 2361 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 2362 * bits to improve our u32/s32 boundaries. 2363 * 2364 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 2365 * u64) is pretty trivial, it's obvious that in u32 we'll also have 2366 * [10, 20] range. But this property holds for any 64-bit range as 2367 * long as upper 32 bits in that entire range of values stay the same. 2368 * 2369 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 2370 * in decimal) has the same upper 32 bits throughout all the values in 2371 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 2372 * range. 2373 * 2374 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 2375 * following the rules outlined below about u64/s64 correspondence 2376 * (which equally applies to u32 vs s32 correspondence). In general it 2377 * depends on actual hexadecimal values of 32-bit range. They can form 2378 * only valid u32, or only valid s32 ranges in some cases. 2379 * 2380 * So we use all these insights to derive bounds for subregisters here. 2381 */ 2382 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 2383 /* u64 to u32 casting preserves validity of low 32 bits as 2384 * a range, if upper 32 bits are the same 2385 */ 2386 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 2387 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 2388 2389 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 2390 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2391 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2392 } 2393 } 2394 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 2395 /* low 32 bits should form a proper u32 range */ 2396 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 2397 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 2398 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 2399 } 2400 /* low 32 bits should form a proper s32 range */ 2401 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 2402 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2403 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2404 } 2405 } 2406 /* Special case where upper bits form a small sequence of two 2407 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 2408 * 0x00000000 is also valid), while lower bits form a proper s32 range 2409 * going from negative numbers to positive numbers. E.g., let's say we 2410 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 2411 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 2412 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 2413 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 2414 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 2415 * upper 32 bits. As a random example, s64 range 2416 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2417 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2418 */ 2419 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2420 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 2421 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2422 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2423 } 2424 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2425 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2426 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2427 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2428 } 2429 /* if u32 range forms a valid s32 range (due to matching sign bit), 2430 * try to learn from that 2431 */ 2432 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2433 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2434 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2435 } 2436 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2437 * are the same, so combine. This works even in the negative case, e.g. 2438 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2439 */ 2440 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2441 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2442 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2443 } 2444 } 2445 2446 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2447 { 2448 /* If u64 range forms a valid s64 range (due to matching sign bit), 2449 * try to learn from that. Let's do a bit of ASCII art to see when 2450 * this is happening. Let's take u64 range first: 2451 * 2452 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2453 * |-------------------------------|--------------------------------| 2454 * 2455 * Valid u64 range is formed when umin and umax are anywhere in the 2456 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2457 * straightforward. Let's see how s64 range maps onto the same range 2458 * of values, annotated below the line for comparison: 2459 * 2460 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2461 * |-------------------------------|--------------------------------| 2462 * 0 S64_MAX S64_MIN -1 2463 * 2464 * So s64 values basically start in the middle and they are logically 2465 * contiguous to the right of it, wrapping around from -1 to 0, and 2466 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2467 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2468 * more visually as mapped to sign-agnostic range of hex values. 2469 * 2470 * u64 start u64 end 2471 * _______________________________________________________________ 2472 * / \ 2473 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2474 * |-------------------------------|--------------------------------| 2475 * 0 S64_MAX S64_MIN -1 2476 * / \ 2477 * >------------------------------ -------------------------------> 2478 * s64 continues... s64 end s64 start s64 "midpoint" 2479 * 2480 * What this means is that, in general, we can't always derive 2481 * something new about u64 from any random s64 range, and vice versa. 2482 * 2483 * But we can do that in two particular cases. One is when entire 2484 * u64/s64 range is *entirely* contained within left half of the above 2485 * diagram or when it is *entirely* contained in the right half. I.e.: 2486 * 2487 * |-------------------------------|--------------------------------| 2488 * ^ ^ ^ ^ 2489 * A B C D 2490 * 2491 * [A, B] and [C, D] are contained entirely in their respective halves 2492 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2493 * will be non-negative both as u64 and s64 (and in fact it will be 2494 * identical ranges no matter the signedness). [C, D] treated as s64 2495 * will be a range of negative values, while in u64 it will be 2496 * non-negative range of values larger than 0x8000000000000000. 2497 * 2498 * Now, any other range here can't be represented in both u64 and s64 2499 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2500 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2501 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2502 * for example. Similarly, valid s64 range [D, A] (going from negative 2503 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2504 * ranges as u64. Currently reg_state can't represent two segments per 2505 * numeric domain, so in such situations we can only derive maximal 2506 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2507 * 2508 * So we use these facts to derive umin/umax from smin/smax and vice 2509 * versa only if they stay within the same "half". This is equivalent 2510 * to checking sign bit: lower half will have sign bit as zero, upper 2511 * half have sign bit 1. Below in code we simplify this by just 2512 * casting umin/umax as smin/smax and checking if they form valid 2513 * range, and vice versa. Those are equivalent checks. 2514 */ 2515 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2516 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2517 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2518 } 2519 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2520 * are the same, so combine. This works even in the negative case, e.g. 2521 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2522 */ 2523 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2524 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2525 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2526 } else { 2527 /* If the s64 range crosses the sign boundary, then it's split 2528 * between the beginning and end of the U64 domain. In that 2529 * case, we can derive new bounds if the u64 range overlaps 2530 * with only one end of the s64 range. 2531 * 2532 * In the following example, the u64 range overlaps only with 2533 * positive portion of the s64 range. 2534 * 2535 * 0 U64_MAX 2536 * | [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx] | 2537 * |----------------------------|----------------------------| 2538 * |xxxxx s64 range xxxxxxxxx] [xxxxxxx| 2539 * 0 S64_MAX S64_MIN -1 2540 * 2541 * We can thus derive the following new s64 and u64 ranges. 2542 * 2543 * 0 U64_MAX 2544 * | [xxxxxx u64 range xxxxx] | 2545 * |----------------------------|----------------------------| 2546 * | [xxxxxx s64 range xxxxx] | 2547 * 0 S64_MAX S64_MIN -1 2548 * 2549 * If they overlap in two places, we can't derive anything 2550 * because reg_state can't represent two ranges per numeric 2551 * domain. 2552 * 2553 * 0 U64_MAX 2554 * | [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx] | 2555 * |----------------------------|----------------------------| 2556 * |xxxxx s64 range xxxxxxxxx] [xxxxxxxxxx| 2557 * 0 S64_MAX S64_MIN -1 2558 * 2559 * The first condition below corresponds to the first diagram 2560 * above. 2561 */ 2562 if (reg->umax_value < (u64)reg->smin_value) { 2563 reg->smin_value = (s64)reg->umin_value; 2564 reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value); 2565 } else if ((u64)reg->smax_value < reg->umin_value) { 2566 /* This second condition considers the case where the u64 range 2567 * overlaps with the negative portion of the s64 range: 2568 * 2569 * 0 U64_MAX 2570 * | [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx] | 2571 * |----------------------------|----------------------------| 2572 * |xxxxxxxxx] [xxxxxxxxxxxx s64 range | 2573 * 0 S64_MAX S64_MIN -1 2574 */ 2575 reg->smax_value = (s64)reg->umax_value; 2576 reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value); 2577 } 2578 } 2579 } 2580 2581 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2582 { 2583 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2584 * values on both sides of 64-bit range in hope to have tighter range. 2585 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2586 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2587 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2588 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2589 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2590 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2591 * We just need to make sure that derived bounds we are intersecting 2592 * with are well-formed ranges in respective s64 or u64 domain, just 2593 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2594 */ 2595 __u64 new_umin, new_umax; 2596 __s64 new_smin, new_smax; 2597 2598 /* u32 -> u64 tightening, it's always well-formed */ 2599 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2600 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2601 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2602 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2603 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2604 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2605 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2606 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2607 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2608 2609 /* Here we would like to handle a special case after sign extending load, 2610 * when upper bits for a 64-bit range are all 1s or all 0s. 2611 * 2612 * Upper bits are all 1s when register is in a range: 2613 * [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff] 2614 * Upper bits are all 0s when register is in a range: 2615 * [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff] 2616 * Together this forms are continuous range: 2617 * [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff] 2618 * 2619 * Now, suppose that register range is in fact tighter: 2620 * [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R) 2621 * Also suppose that it's 32-bit range is positive, 2622 * meaning that lower 32-bits of the full 64-bit register 2623 * are in the range: 2624 * [0x0000_0000, 0x7fff_ffff] (W) 2625 * 2626 * If this happens, then any value in a range: 2627 * [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff] 2628 * is smaller than a lowest bound of the range (R): 2629 * 0xffff_ffff_8000_0000 2630 * which means that upper bits of the full 64-bit register 2631 * can't be all 1s, when lower bits are in range (W). 2632 * 2633 * Note that: 2634 * - 0xffff_ffff_8000_0000 == (s64)S32_MIN 2635 * - 0x0000_0000_7fff_ffff == (s64)S32_MAX 2636 * These relations are used in the conditions below. 2637 */ 2638 if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) { 2639 reg->smin_value = reg->s32_min_value; 2640 reg->smax_value = reg->s32_max_value; 2641 reg->umin_value = reg->s32_min_value; 2642 reg->umax_value = reg->s32_max_value; 2643 reg->var_off = tnum_intersect(reg->var_off, 2644 tnum_range(reg->smin_value, reg->smax_value)); 2645 } 2646 } 2647 2648 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2649 { 2650 __reg32_deduce_bounds(reg); 2651 __reg64_deduce_bounds(reg); 2652 __reg_deduce_mixed_bounds(reg); 2653 } 2654 2655 /* Attempts to improve var_off based on unsigned min/max information */ 2656 static void __reg_bound_offset(struct bpf_reg_state *reg) 2657 { 2658 struct tnum var64_off = tnum_intersect(reg->var_off, 2659 tnum_range(reg->umin_value, 2660 reg->umax_value)); 2661 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2662 tnum_range(reg->u32_min_value, 2663 reg->u32_max_value)); 2664 2665 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2666 } 2667 2668 static void reg_bounds_sync(struct bpf_reg_state *reg) 2669 { 2670 /* We might have learned new bounds from the var_off. */ 2671 __update_reg_bounds(reg); 2672 /* We might have learned something about the sign bit. */ 2673 __reg_deduce_bounds(reg); 2674 __reg_deduce_bounds(reg); 2675 __reg_deduce_bounds(reg); 2676 /* We might have learned some bits from the bounds. */ 2677 __reg_bound_offset(reg); 2678 /* Intersecting with the old var_off might have improved our bounds 2679 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2680 * then new var_off is (0; 0x7f...fc) which improves our umax. 2681 */ 2682 __update_reg_bounds(reg); 2683 } 2684 2685 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2686 struct bpf_reg_state *reg, const char *ctx) 2687 { 2688 const char *msg; 2689 2690 if (reg->umin_value > reg->umax_value || 2691 reg->smin_value > reg->smax_value || 2692 reg->u32_min_value > reg->u32_max_value || 2693 reg->s32_min_value > reg->s32_max_value) { 2694 msg = "range bounds violation"; 2695 goto out; 2696 } 2697 2698 if (tnum_is_const(reg->var_off)) { 2699 u64 uval = reg->var_off.value; 2700 s64 sval = (s64)uval; 2701 2702 if (reg->umin_value != uval || reg->umax_value != uval || 2703 reg->smin_value != sval || reg->smax_value != sval) { 2704 msg = "const tnum out of sync with range bounds"; 2705 goto out; 2706 } 2707 } 2708 2709 if (tnum_subreg_is_const(reg->var_off)) { 2710 u32 uval32 = tnum_subreg(reg->var_off).value; 2711 s32 sval32 = (s32)uval32; 2712 2713 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2714 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2715 msg = "const subreg tnum out of sync with range bounds"; 2716 goto out; 2717 } 2718 } 2719 2720 return 0; 2721 out: 2722 verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2723 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)", 2724 ctx, msg, reg->umin_value, reg->umax_value, 2725 reg->smin_value, reg->smax_value, 2726 reg->u32_min_value, reg->u32_max_value, 2727 reg->s32_min_value, reg->s32_max_value, 2728 reg->var_off.value, reg->var_off.mask); 2729 if (env->test_reg_invariants) 2730 return -EFAULT; 2731 __mark_reg_unbounded(reg); 2732 return 0; 2733 } 2734 2735 static bool __reg32_bound_s64(s32 a) 2736 { 2737 return a >= 0 && a <= S32_MAX; 2738 } 2739 2740 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2741 { 2742 reg->umin_value = reg->u32_min_value; 2743 reg->umax_value = reg->u32_max_value; 2744 2745 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2746 * be positive otherwise set to worse case bounds and refine later 2747 * from tnum. 2748 */ 2749 if (__reg32_bound_s64(reg->s32_min_value) && 2750 __reg32_bound_s64(reg->s32_max_value)) { 2751 reg->smin_value = reg->s32_min_value; 2752 reg->smax_value = reg->s32_max_value; 2753 } else { 2754 reg->smin_value = 0; 2755 reg->smax_value = U32_MAX; 2756 } 2757 } 2758 2759 /* Mark a register as having a completely unknown (scalar) value. */ 2760 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2761 { 2762 /* 2763 * Clear type, off, and union(map_ptr, range) and 2764 * padding between 'type' and union 2765 */ 2766 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2767 reg->type = SCALAR_VALUE; 2768 reg->id = 0; 2769 reg->ref_obj_id = 0; 2770 reg->var_off = tnum_unknown; 2771 reg->frameno = 0; 2772 reg->precise = false; 2773 __mark_reg_unbounded(reg); 2774 } 2775 2776 /* Mark a register as having a completely unknown (scalar) value, 2777 * initialize .precise as true when not bpf capable. 2778 */ 2779 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2780 struct bpf_reg_state *reg) 2781 { 2782 __mark_reg_unknown_imprecise(reg); 2783 reg->precise = !env->bpf_capable; 2784 } 2785 2786 static void mark_reg_unknown(struct bpf_verifier_env *env, 2787 struct bpf_reg_state *regs, u32 regno) 2788 { 2789 if (WARN_ON(regno >= MAX_BPF_REG)) { 2790 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2791 /* Something bad happened, let's kill all regs except FP */ 2792 for (regno = 0; regno < BPF_REG_FP; regno++) 2793 __mark_reg_not_init(env, regs + regno); 2794 return; 2795 } 2796 __mark_reg_unknown(env, regs + regno); 2797 } 2798 2799 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2800 struct bpf_reg_state *regs, 2801 u32 regno, 2802 s32 s32_min, 2803 s32 s32_max) 2804 { 2805 struct bpf_reg_state *reg = regs + regno; 2806 2807 reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min); 2808 reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max); 2809 2810 reg->smin_value = max_t(s64, reg->smin_value, s32_min); 2811 reg->smax_value = min_t(s64, reg->smax_value, s32_max); 2812 2813 reg_bounds_sync(reg); 2814 2815 return reg_bounds_sanity_check(env, reg, "s32_range"); 2816 } 2817 2818 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2819 struct bpf_reg_state *reg) 2820 { 2821 __mark_reg_unknown(env, reg); 2822 reg->type = NOT_INIT; 2823 } 2824 2825 static void mark_reg_not_init(struct bpf_verifier_env *env, 2826 struct bpf_reg_state *regs, u32 regno) 2827 { 2828 if (WARN_ON(regno >= MAX_BPF_REG)) { 2829 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2830 /* Something bad happened, let's kill all regs except FP */ 2831 for (regno = 0; regno < BPF_REG_FP; regno++) 2832 __mark_reg_not_init(env, regs + regno); 2833 return; 2834 } 2835 __mark_reg_not_init(env, regs + regno); 2836 } 2837 2838 static int mark_btf_ld_reg(struct bpf_verifier_env *env, 2839 struct bpf_reg_state *regs, u32 regno, 2840 enum bpf_reg_type reg_type, 2841 struct btf *btf, u32 btf_id, 2842 enum bpf_type_flag flag) 2843 { 2844 switch (reg_type) { 2845 case SCALAR_VALUE: 2846 mark_reg_unknown(env, regs, regno); 2847 return 0; 2848 case PTR_TO_BTF_ID: 2849 mark_reg_known_zero(env, regs, regno); 2850 regs[regno].type = PTR_TO_BTF_ID | flag; 2851 regs[regno].btf = btf; 2852 regs[regno].btf_id = btf_id; 2853 if (type_may_be_null(flag)) 2854 regs[regno].id = ++env->id_gen; 2855 return 0; 2856 case PTR_TO_MEM: 2857 mark_reg_known_zero(env, regs, regno); 2858 regs[regno].type = PTR_TO_MEM | flag; 2859 regs[regno].mem_size = 0; 2860 return 0; 2861 default: 2862 verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__); 2863 return -EFAULT; 2864 } 2865 } 2866 2867 #define DEF_NOT_SUBREG (0) 2868 static void init_reg_state(struct bpf_verifier_env *env, 2869 struct bpf_func_state *state) 2870 { 2871 struct bpf_reg_state *regs = state->regs; 2872 int i; 2873 2874 for (i = 0; i < MAX_BPF_REG; i++) { 2875 mark_reg_not_init(env, regs, i); 2876 regs[i].live = REG_LIVE_NONE; 2877 regs[i].parent = NULL; 2878 regs[i].subreg_def = DEF_NOT_SUBREG; 2879 } 2880 2881 /* frame pointer */ 2882 regs[BPF_REG_FP].type = PTR_TO_STACK; 2883 mark_reg_known_zero(env, regs, BPF_REG_FP); 2884 regs[BPF_REG_FP].frameno = state->frameno; 2885 } 2886 2887 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2888 { 2889 return (struct bpf_retval_range){ minval, maxval }; 2890 } 2891 2892 #define BPF_MAIN_FUNC (-1) 2893 static void init_func_state(struct bpf_verifier_env *env, 2894 struct bpf_func_state *state, 2895 int callsite, int frameno, int subprogno) 2896 { 2897 state->callsite = callsite; 2898 state->frameno = frameno; 2899 state->subprogno = subprogno; 2900 state->callback_ret_range = retval_range(0, 0); 2901 init_reg_state(env, state); 2902 mark_verifier_state_scratched(env); 2903 } 2904 2905 /* Similar to push_stack(), but for async callbacks */ 2906 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2907 int insn_idx, int prev_insn_idx, 2908 int subprog, bool is_sleepable) 2909 { 2910 struct bpf_verifier_stack_elem *elem; 2911 struct bpf_func_state *frame; 2912 2913 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL_ACCOUNT); 2914 if (!elem) 2915 return NULL; 2916 2917 elem->insn_idx = insn_idx; 2918 elem->prev_insn_idx = prev_insn_idx; 2919 elem->next = env->head; 2920 elem->log_pos = env->log.end_pos; 2921 env->head = elem; 2922 env->stack_size++; 2923 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2924 verbose(env, 2925 "The sequence of %d jumps is too complex for async cb.\n", 2926 env->stack_size); 2927 return NULL; 2928 } 2929 /* Unlike push_stack() do not copy_verifier_state(). 2930 * The caller state doesn't matter. 2931 * This is async callback. It starts in a fresh stack. 2932 * Initialize it similar to do_check_common(). 2933 */ 2934 elem->st.branches = 1; 2935 elem->st.in_sleepable = is_sleepable; 2936 frame = kzalloc(sizeof(*frame), GFP_KERNEL_ACCOUNT); 2937 if (!frame) 2938 return NULL; 2939 init_func_state(env, frame, 2940 BPF_MAIN_FUNC /* callsite */, 2941 0 /* frameno within this callchain */, 2942 subprog /* subprog number within this prog */); 2943 elem->st.frame[0] = frame; 2944 return &elem->st; 2945 } 2946 2947 2948 enum reg_arg_type { 2949 SRC_OP, /* register is used as source operand */ 2950 DST_OP, /* register is used as destination operand */ 2951 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2952 }; 2953 2954 static int cmp_subprogs(const void *a, const void *b) 2955 { 2956 return ((struct bpf_subprog_info *)a)->start - 2957 ((struct bpf_subprog_info *)b)->start; 2958 } 2959 2960 /* Find subprogram that contains instruction at 'off' */ 2961 static struct bpf_subprog_info *find_containing_subprog(struct bpf_verifier_env *env, int off) 2962 { 2963 struct bpf_subprog_info *vals = env->subprog_info; 2964 int l, r, m; 2965 2966 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0) 2967 return NULL; 2968 2969 l = 0; 2970 r = env->subprog_cnt - 1; 2971 while (l < r) { 2972 m = l + (r - l + 1) / 2; 2973 if (vals[m].start <= off) 2974 l = m; 2975 else 2976 r = m - 1; 2977 } 2978 return &vals[l]; 2979 } 2980 2981 /* Find subprogram that starts exactly at 'off' */ 2982 static int find_subprog(struct bpf_verifier_env *env, int off) 2983 { 2984 struct bpf_subprog_info *p; 2985 2986 p = find_containing_subprog(env, off); 2987 if (!p || p->start != off) 2988 return -ENOENT; 2989 return p - env->subprog_info; 2990 } 2991 2992 static int add_subprog(struct bpf_verifier_env *env, int off) 2993 { 2994 int insn_cnt = env->prog->len; 2995 int ret; 2996 2997 if (off >= insn_cnt || off < 0) { 2998 verbose(env, "call to invalid destination\n"); 2999 return -EINVAL; 3000 } 3001 ret = find_subprog(env, off); 3002 if (ret >= 0) 3003 return ret; 3004 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 3005 verbose(env, "too many subprograms\n"); 3006 return -E2BIG; 3007 } 3008 /* determine subprog starts. The end is one before the next starts */ 3009 env->subprog_info[env->subprog_cnt++].start = off; 3010 sort(env->subprog_info, env->subprog_cnt, 3011 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 3012 return env->subprog_cnt - 1; 3013 } 3014 3015 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 3016 { 3017 struct bpf_prog_aux *aux = env->prog->aux; 3018 struct btf *btf = aux->btf; 3019 const struct btf_type *t; 3020 u32 main_btf_id, id; 3021 const char *name; 3022 int ret, i; 3023 3024 /* Non-zero func_info_cnt implies valid btf */ 3025 if (!aux->func_info_cnt) 3026 return 0; 3027 main_btf_id = aux->func_info[0].type_id; 3028 3029 t = btf_type_by_id(btf, main_btf_id); 3030 if (!t) { 3031 verbose(env, "invalid btf id for main subprog in func_info\n"); 3032 return -EINVAL; 3033 } 3034 3035 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 3036 if (IS_ERR(name)) { 3037 ret = PTR_ERR(name); 3038 /* If there is no tag present, there is no exception callback */ 3039 if (ret == -ENOENT) 3040 ret = 0; 3041 else if (ret == -EEXIST) 3042 verbose(env, "multiple exception callback tags for main subprog\n"); 3043 return ret; 3044 } 3045 3046 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 3047 if (ret < 0) { 3048 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 3049 return ret; 3050 } 3051 id = ret; 3052 t = btf_type_by_id(btf, id); 3053 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 3054 verbose(env, "exception callback '%s' must have global linkage\n", name); 3055 return -EINVAL; 3056 } 3057 ret = 0; 3058 for (i = 0; i < aux->func_info_cnt; i++) { 3059 if (aux->func_info[i].type_id != id) 3060 continue; 3061 ret = aux->func_info[i].insn_off; 3062 /* Further func_info and subprog checks will also happen 3063 * later, so assume this is the right insn_off for now. 3064 */ 3065 if (!ret) { 3066 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 3067 ret = -EINVAL; 3068 } 3069 } 3070 if (!ret) { 3071 verbose(env, "exception callback type id not found in func_info\n"); 3072 ret = -EINVAL; 3073 } 3074 return ret; 3075 } 3076 3077 #define MAX_KFUNC_DESCS 256 3078 #define MAX_KFUNC_BTFS 256 3079 3080 struct bpf_kfunc_desc { 3081 struct btf_func_model func_model; 3082 u32 func_id; 3083 s32 imm; 3084 u16 offset; 3085 unsigned long addr; 3086 }; 3087 3088 struct bpf_kfunc_btf { 3089 struct btf *btf; 3090 struct module *module; 3091 u16 offset; 3092 }; 3093 3094 struct bpf_kfunc_desc_tab { 3095 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 3096 * verification. JITs do lookups by bpf_insn, where func_id may not be 3097 * available, therefore at the end of verification do_misc_fixups() 3098 * sorts this by imm and offset. 3099 */ 3100 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 3101 u32 nr_descs; 3102 }; 3103 3104 struct bpf_kfunc_btf_tab { 3105 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 3106 u32 nr_descs; 3107 }; 3108 3109 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 3110 { 3111 const struct bpf_kfunc_desc *d0 = a; 3112 const struct bpf_kfunc_desc *d1 = b; 3113 3114 /* func_id is not greater than BTF_MAX_TYPE */ 3115 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 3116 } 3117 3118 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 3119 { 3120 const struct bpf_kfunc_btf *d0 = a; 3121 const struct bpf_kfunc_btf *d1 = b; 3122 3123 return d0->offset - d1->offset; 3124 } 3125 3126 static const struct bpf_kfunc_desc * 3127 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 3128 { 3129 struct bpf_kfunc_desc desc = { 3130 .func_id = func_id, 3131 .offset = offset, 3132 }; 3133 struct bpf_kfunc_desc_tab *tab; 3134 3135 tab = prog->aux->kfunc_tab; 3136 return bsearch(&desc, tab->descs, tab->nr_descs, 3137 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 3138 } 3139 3140 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 3141 u16 btf_fd_idx, u8 **func_addr) 3142 { 3143 const struct bpf_kfunc_desc *desc; 3144 3145 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 3146 if (!desc) 3147 return -EFAULT; 3148 3149 *func_addr = (u8 *)desc->addr; 3150 return 0; 3151 } 3152 3153 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 3154 s16 offset) 3155 { 3156 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 3157 struct bpf_kfunc_btf_tab *tab; 3158 struct bpf_kfunc_btf *b; 3159 struct module *mod; 3160 struct btf *btf; 3161 int btf_fd; 3162 3163 tab = env->prog->aux->kfunc_btf_tab; 3164 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 3165 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 3166 if (!b) { 3167 if (tab->nr_descs == MAX_KFUNC_BTFS) { 3168 verbose(env, "too many different module BTFs\n"); 3169 return ERR_PTR(-E2BIG); 3170 } 3171 3172 if (bpfptr_is_null(env->fd_array)) { 3173 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 3174 return ERR_PTR(-EPROTO); 3175 } 3176 3177 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 3178 offset * sizeof(btf_fd), 3179 sizeof(btf_fd))) 3180 return ERR_PTR(-EFAULT); 3181 3182 btf = btf_get_by_fd(btf_fd); 3183 if (IS_ERR(btf)) { 3184 verbose(env, "invalid module BTF fd specified\n"); 3185 return btf; 3186 } 3187 3188 if (!btf_is_module(btf)) { 3189 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 3190 btf_put(btf); 3191 return ERR_PTR(-EINVAL); 3192 } 3193 3194 mod = btf_try_get_module(btf); 3195 if (!mod) { 3196 btf_put(btf); 3197 return ERR_PTR(-ENXIO); 3198 } 3199 3200 b = &tab->descs[tab->nr_descs++]; 3201 b->btf = btf; 3202 b->module = mod; 3203 b->offset = offset; 3204 3205 /* sort() reorders entries by value, so b may no longer point 3206 * to the right entry after this 3207 */ 3208 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3209 kfunc_btf_cmp_by_off, NULL); 3210 } else { 3211 btf = b->btf; 3212 } 3213 3214 return btf; 3215 } 3216 3217 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 3218 { 3219 if (!tab) 3220 return; 3221 3222 while (tab->nr_descs--) { 3223 module_put(tab->descs[tab->nr_descs].module); 3224 btf_put(tab->descs[tab->nr_descs].btf); 3225 } 3226 kfree(tab); 3227 } 3228 3229 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 3230 { 3231 if (offset) { 3232 if (offset < 0) { 3233 /* In the future, this can be allowed to increase limit 3234 * of fd index into fd_array, interpreted as u16. 3235 */ 3236 verbose(env, "negative offset disallowed for kernel module function call\n"); 3237 return ERR_PTR(-EINVAL); 3238 } 3239 3240 return __find_kfunc_desc_btf(env, offset); 3241 } 3242 return btf_vmlinux ?: ERR_PTR(-ENOENT); 3243 } 3244 3245 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 3246 { 3247 const struct btf_type *func, *func_proto; 3248 struct bpf_kfunc_btf_tab *btf_tab; 3249 struct bpf_kfunc_desc_tab *tab; 3250 struct bpf_prog_aux *prog_aux; 3251 struct bpf_kfunc_desc *desc; 3252 const char *func_name; 3253 struct btf *desc_btf; 3254 unsigned long call_imm; 3255 unsigned long addr; 3256 int err; 3257 3258 prog_aux = env->prog->aux; 3259 tab = prog_aux->kfunc_tab; 3260 btf_tab = prog_aux->kfunc_btf_tab; 3261 if (!tab) { 3262 if (!btf_vmlinux) { 3263 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 3264 return -ENOTSUPP; 3265 } 3266 3267 if (!env->prog->jit_requested) { 3268 verbose(env, "JIT is required for calling kernel function\n"); 3269 return -ENOTSUPP; 3270 } 3271 3272 if (!bpf_jit_supports_kfunc_call()) { 3273 verbose(env, "JIT does not support calling kernel function\n"); 3274 return -ENOTSUPP; 3275 } 3276 3277 if (!env->prog->gpl_compatible) { 3278 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 3279 return -EINVAL; 3280 } 3281 3282 tab = kzalloc(sizeof(*tab), GFP_KERNEL_ACCOUNT); 3283 if (!tab) 3284 return -ENOMEM; 3285 prog_aux->kfunc_tab = tab; 3286 } 3287 3288 /* func_id == 0 is always invalid, but instead of returning an error, be 3289 * conservative and wait until the code elimination pass before returning 3290 * error, so that invalid calls that get pruned out can be in BPF programs 3291 * loaded from userspace. It is also required that offset be untouched 3292 * for such calls. 3293 */ 3294 if (!func_id && !offset) 3295 return 0; 3296 3297 if (!btf_tab && offset) { 3298 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL_ACCOUNT); 3299 if (!btf_tab) 3300 return -ENOMEM; 3301 prog_aux->kfunc_btf_tab = btf_tab; 3302 } 3303 3304 desc_btf = find_kfunc_desc_btf(env, offset); 3305 if (IS_ERR(desc_btf)) { 3306 verbose(env, "failed to find BTF for kernel function\n"); 3307 return PTR_ERR(desc_btf); 3308 } 3309 3310 if (find_kfunc_desc(env->prog, func_id, offset)) 3311 return 0; 3312 3313 if (tab->nr_descs == MAX_KFUNC_DESCS) { 3314 verbose(env, "too many different kernel function calls\n"); 3315 return -E2BIG; 3316 } 3317 3318 func = btf_type_by_id(desc_btf, func_id); 3319 if (!func || !btf_type_is_func(func)) { 3320 verbose(env, "kernel btf_id %u is not a function\n", 3321 func_id); 3322 return -EINVAL; 3323 } 3324 func_proto = btf_type_by_id(desc_btf, func->type); 3325 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 3326 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 3327 func_id); 3328 return -EINVAL; 3329 } 3330 3331 func_name = btf_name_by_offset(desc_btf, func->name_off); 3332 addr = kallsyms_lookup_name(func_name); 3333 if (!addr) { 3334 verbose(env, "cannot find address for kernel function %s\n", 3335 func_name); 3336 return -EINVAL; 3337 } 3338 specialize_kfunc(env, func_id, offset, &addr); 3339 3340 if (bpf_jit_supports_far_kfunc_call()) { 3341 call_imm = func_id; 3342 } else { 3343 call_imm = BPF_CALL_IMM(addr); 3344 /* Check whether the relative offset overflows desc->imm */ 3345 if ((unsigned long)(s32)call_imm != call_imm) { 3346 verbose(env, "address of kernel function %s is out of range\n", 3347 func_name); 3348 return -EINVAL; 3349 } 3350 } 3351 3352 if (bpf_dev_bound_kfunc_id(func_id)) { 3353 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 3354 if (err) 3355 return err; 3356 } 3357 3358 desc = &tab->descs[tab->nr_descs++]; 3359 desc->func_id = func_id; 3360 desc->imm = call_imm; 3361 desc->offset = offset; 3362 desc->addr = addr; 3363 err = btf_distill_func_proto(&env->log, desc_btf, 3364 func_proto, func_name, 3365 &desc->func_model); 3366 if (!err) 3367 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3368 kfunc_desc_cmp_by_id_off, NULL); 3369 return err; 3370 } 3371 3372 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 3373 { 3374 const struct bpf_kfunc_desc *d0 = a; 3375 const struct bpf_kfunc_desc *d1 = b; 3376 3377 if (d0->imm != d1->imm) 3378 return d0->imm < d1->imm ? -1 : 1; 3379 if (d0->offset != d1->offset) 3380 return d0->offset < d1->offset ? -1 : 1; 3381 return 0; 3382 } 3383 3384 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 3385 { 3386 struct bpf_kfunc_desc_tab *tab; 3387 3388 tab = prog->aux->kfunc_tab; 3389 if (!tab) 3390 return; 3391 3392 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3393 kfunc_desc_cmp_by_imm_off, NULL); 3394 } 3395 3396 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 3397 { 3398 return !!prog->aux->kfunc_tab; 3399 } 3400 3401 const struct btf_func_model * 3402 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 3403 const struct bpf_insn *insn) 3404 { 3405 const struct bpf_kfunc_desc desc = { 3406 .imm = insn->imm, 3407 .offset = insn->off, 3408 }; 3409 const struct bpf_kfunc_desc *res; 3410 struct bpf_kfunc_desc_tab *tab; 3411 3412 tab = prog->aux->kfunc_tab; 3413 res = bsearch(&desc, tab->descs, tab->nr_descs, 3414 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 3415 3416 return res ? &res->func_model : NULL; 3417 } 3418 3419 static int add_kfunc_in_insns(struct bpf_verifier_env *env, 3420 struct bpf_insn *insn, int cnt) 3421 { 3422 int i, ret; 3423 3424 for (i = 0; i < cnt; i++, insn++) { 3425 if (bpf_pseudo_kfunc_call(insn)) { 3426 ret = add_kfunc_call(env, insn->imm, insn->off); 3427 if (ret < 0) 3428 return ret; 3429 } 3430 } 3431 return 0; 3432 } 3433 3434 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 3435 { 3436 struct bpf_subprog_info *subprog = env->subprog_info; 3437 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 3438 struct bpf_insn *insn = env->prog->insnsi; 3439 3440 /* Add entry function. */ 3441 ret = add_subprog(env, 0); 3442 if (ret) 3443 return ret; 3444 3445 for (i = 0; i < insn_cnt; i++, insn++) { 3446 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 3447 !bpf_pseudo_kfunc_call(insn)) 3448 continue; 3449 3450 if (!env->bpf_capable) { 3451 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 3452 return -EPERM; 3453 } 3454 3455 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 3456 ret = add_subprog(env, i + insn->imm + 1); 3457 else 3458 ret = add_kfunc_call(env, insn->imm, insn->off); 3459 3460 if (ret < 0) 3461 return ret; 3462 } 3463 3464 ret = bpf_find_exception_callback_insn_off(env); 3465 if (ret < 0) 3466 return ret; 3467 ex_cb_insn = ret; 3468 3469 /* If ex_cb_insn > 0, this means that the main program has a subprog 3470 * marked using BTF decl tag to serve as the exception callback. 3471 */ 3472 if (ex_cb_insn) { 3473 ret = add_subprog(env, ex_cb_insn); 3474 if (ret < 0) 3475 return ret; 3476 for (i = 1; i < env->subprog_cnt; i++) { 3477 if (env->subprog_info[i].start != ex_cb_insn) 3478 continue; 3479 env->exception_callback_subprog = i; 3480 mark_subprog_exc_cb(env, i); 3481 break; 3482 } 3483 } 3484 3485 /* Add a fake 'exit' subprog which could simplify subprog iteration 3486 * logic. 'subprog_cnt' should not be increased. 3487 */ 3488 subprog[env->subprog_cnt].start = insn_cnt; 3489 3490 if (env->log.level & BPF_LOG_LEVEL2) 3491 for (i = 0; i < env->subprog_cnt; i++) 3492 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3493 3494 return 0; 3495 } 3496 3497 static int jmp_offset(struct bpf_insn *insn) 3498 { 3499 u8 code = insn->code; 3500 3501 if (code == (BPF_JMP32 | BPF_JA)) 3502 return insn->imm; 3503 return insn->off; 3504 } 3505 3506 static int check_subprogs(struct bpf_verifier_env *env) 3507 { 3508 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3509 struct bpf_subprog_info *subprog = env->subprog_info; 3510 struct bpf_insn *insn = env->prog->insnsi; 3511 int insn_cnt = env->prog->len; 3512 3513 /* now check that all jumps are within the same subprog */ 3514 subprog_start = subprog[cur_subprog].start; 3515 subprog_end = subprog[cur_subprog + 1].start; 3516 for (i = 0; i < insn_cnt; i++) { 3517 u8 code = insn[i].code; 3518 3519 if (code == (BPF_JMP | BPF_CALL) && 3520 insn[i].src_reg == 0 && 3521 insn[i].imm == BPF_FUNC_tail_call) { 3522 subprog[cur_subprog].has_tail_call = true; 3523 subprog[cur_subprog].tail_call_reachable = true; 3524 } 3525 if (BPF_CLASS(code) == BPF_LD && 3526 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3527 subprog[cur_subprog].has_ld_abs = true; 3528 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3529 goto next; 3530 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 3531 goto next; 3532 off = i + jmp_offset(&insn[i]) + 1; 3533 if (off < subprog_start || off >= subprog_end) { 3534 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3535 return -EINVAL; 3536 } 3537 next: 3538 if (i == subprog_end - 1) { 3539 /* to avoid fall-through from one subprog into another 3540 * the last insn of the subprog should be either exit 3541 * or unconditional jump back or bpf_throw call 3542 */ 3543 if (code != (BPF_JMP | BPF_EXIT) && 3544 code != (BPF_JMP32 | BPF_JA) && 3545 code != (BPF_JMP | BPF_JA)) { 3546 verbose(env, "last insn is not an exit or jmp\n"); 3547 return -EINVAL; 3548 } 3549 subprog_start = subprog_end; 3550 cur_subprog++; 3551 if (cur_subprog < env->subprog_cnt) 3552 subprog_end = subprog[cur_subprog + 1].start; 3553 } 3554 } 3555 return 0; 3556 } 3557 3558 /* Parentage chain of this register (or stack slot) should take care of all 3559 * issues like callee-saved registers, stack slot allocation time, etc. 3560 */ 3561 static int mark_reg_read(struct bpf_verifier_env *env, 3562 const struct bpf_reg_state *state, 3563 struct bpf_reg_state *parent, u8 flag) 3564 { 3565 bool writes = parent == state->parent; /* Observe write marks */ 3566 int cnt = 0; 3567 3568 while (parent) { 3569 /* if read wasn't screened by an earlier write ... */ 3570 if (writes && state->live & REG_LIVE_WRITTEN) 3571 break; 3572 if (verifier_bug_if(parent->live & REG_LIVE_DONE, env, 3573 "type %s var_off %lld off %d", 3574 reg_type_str(env, parent->type), 3575 parent->var_off.value, parent->off)) 3576 return -EFAULT; 3577 /* The first condition is more likely to be true than the 3578 * second, checked it first. 3579 */ 3580 if ((parent->live & REG_LIVE_READ) == flag || 3581 parent->live & REG_LIVE_READ64) 3582 /* The parentage chain never changes and 3583 * this parent was already marked as LIVE_READ. 3584 * There is no need to keep walking the chain again and 3585 * keep re-marking all parents as LIVE_READ. 3586 * This case happens when the same register is read 3587 * multiple times without writes into it in-between. 3588 * Also, if parent has the stronger REG_LIVE_READ64 set, 3589 * then no need to set the weak REG_LIVE_READ32. 3590 */ 3591 break; 3592 /* ... then we depend on parent's value */ 3593 parent->live |= flag; 3594 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3595 if (flag == REG_LIVE_READ64) 3596 parent->live &= ~REG_LIVE_READ32; 3597 state = parent; 3598 parent = state->parent; 3599 writes = true; 3600 cnt++; 3601 } 3602 3603 if (env->longest_mark_read_walk < cnt) 3604 env->longest_mark_read_walk = cnt; 3605 return 0; 3606 } 3607 3608 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3609 int spi, int nr_slots) 3610 { 3611 struct bpf_func_state *state = func(env, reg); 3612 int err, i; 3613 3614 for (i = 0; i < nr_slots; i++) { 3615 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3616 3617 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3618 if (err) 3619 return err; 3620 3621 mark_stack_slot_scratched(env, spi - i); 3622 } 3623 return 0; 3624 } 3625 3626 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3627 { 3628 int spi; 3629 3630 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3631 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3632 * check_kfunc_call. 3633 */ 3634 if (reg->type == CONST_PTR_TO_DYNPTR) 3635 return 0; 3636 spi = dynptr_get_spi(env, reg); 3637 if (spi < 0) 3638 return spi; 3639 /* Caller ensures dynptr is valid and initialized, which means spi is in 3640 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3641 * read. 3642 */ 3643 return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS); 3644 } 3645 3646 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3647 int spi, int nr_slots) 3648 { 3649 return mark_stack_slot_obj_read(env, reg, spi, nr_slots); 3650 } 3651 3652 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3653 { 3654 int spi; 3655 3656 spi = irq_flag_get_spi(env, reg); 3657 if (spi < 0) 3658 return spi; 3659 return mark_stack_slot_obj_read(env, reg, spi, 1); 3660 } 3661 3662 /* This function is supposed to be used by the following 32-bit optimization 3663 * code only. It returns TRUE if the source or destination register operates 3664 * on 64-bit, otherwise return FALSE. 3665 */ 3666 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3667 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3668 { 3669 u8 code, class, op; 3670 3671 code = insn->code; 3672 class = BPF_CLASS(code); 3673 op = BPF_OP(code); 3674 if (class == BPF_JMP) { 3675 /* BPF_EXIT for "main" will reach here. Return TRUE 3676 * conservatively. 3677 */ 3678 if (op == BPF_EXIT) 3679 return true; 3680 if (op == BPF_CALL) { 3681 /* BPF to BPF call will reach here because of marking 3682 * caller saved clobber with DST_OP_NO_MARK for which we 3683 * don't care the register def because they are anyway 3684 * marked as NOT_INIT already. 3685 */ 3686 if (insn->src_reg == BPF_PSEUDO_CALL) 3687 return false; 3688 /* Helper call will reach here because of arg type 3689 * check, conservatively return TRUE. 3690 */ 3691 if (t == SRC_OP) 3692 return true; 3693 3694 return false; 3695 } 3696 } 3697 3698 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3699 return false; 3700 3701 if (class == BPF_ALU64 || class == BPF_JMP || 3702 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3703 return true; 3704 3705 if (class == BPF_ALU || class == BPF_JMP32) 3706 return false; 3707 3708 if (class == BPF_LDX) { 3709 if (t != SRC_OP) 3710 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3711 /* LDX source must be ptr. */ 3712 return true; 3713 } 3714 3715 if (class == BPF_STX) { 3716 /* BPF_STX (including atomic variants) has one or more source 3717 * operands, one of which is a ptr. Check whether the caller is 3718 * asking about it. 3719 */ 3720 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3721 return true; 3722 return BPF_SIZE(code) == BPF_DW; 3723 } 3724 3725 if (class == BPF_LD) { 3726 u8 mode = BPF_MODE(code); 3727 3728 /* LD_IMM64 */ 3729 if (mode == BPF_IMM) 3730 return true; 3731 3732 /* Both LD_IND and LD_ABS return 32-bit data. */ 3733 if (t != SRC_OP) 3734 return false; 3735 3736 /* Implicit ctx ptr. */ 3737 if (regno == BPF_REG_6) 3738 return true; 3739 3740 /* Explicit source could be any width. */ 3741 return true; 3742 } 3743 3744 if (class == BPF_ST) 3745 /* The only source register for BPF_ST is a ptr. */ 3746 return true; 3747 3748 /* Conservatively return true at default. */ 3749 return true; 3750 } 3751 3752 /* Return the regno defined by the insn, or -1. */ 3753 static int insn_def_regno(const struct bpf_insn *insn) 3754 { 3755 switch (BPF_CLASS(insn->code)) { 3756 case BPF_JMP: 3757 case BPF_JMP32: 3758 case BPF_ST: 3759 return -1; 3760 case BPF_STX: 3761 if (BPF_MODE(insn->code) == BPF_ATOMIC || 3762 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) { 3763 if (insn->imm == BPF_CMPXCHG) 3764 return BPF_REG_0; 3765 else if (insn->imm == BPF_LOAD_ACQ) 3766 return insn->dst_reg; 3767 else if (insn->imm & BPF_FETCH) 3768 return insn->src_reg; 3769 } 3770 return -1; 3771 default: 3772 return insn->dst_reg; 3773 } 3774 } 3775 3776 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3777 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3778 { 3779 int dst_reg = insn_def_regno(insn); 3780 3781 if (dst_reg == -1) 3782 return false; 3783 3784 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3785 } 3786 3787 static void mark_insn_zext(struct bpf_verifier_env *env, 3788 struct bpf_reg_state *reg) 3789 { 3790 s32 def_idx = reg->subreg_def; 3791 3792 if (def_idx == DEF_NOT_SUBREG) 3793 return; 3794 3795 env->insn_aux_data[def_idx - 1].zext_dst = true; 3796 /* The dst will be zero extended, so won't be sub-register anymore. */ 3797 reg->subreg_def = DEF_NOT_SUBREG; 3798 } 3799 3800 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3801 enum reg_arg_type t) 3802 { 3803 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3804 struct bpf_reg_state *reg; 3805 bool rw64; 3806 3807 if (regno >= MAX_BPF_REG) { 3808 verbose(env, "R%d is invalid\n", regno); 3809 return -EINVAL; 3810 } 3811 3812 mark_reg_scratched(env, regno); 3813 3814 reg = ®s[regno]; 3815 rw64 = is_reg64(env, insn, regno, reg, t); 3816 if (t == SRC_OP) { 3817 /* check whether register used as source operand can be read */ 3818 if (reg->type == NOT_INIT) { 3819 verbose(env, "R%d !read_ok\n", regno); 3820 return -EACCES; 3821 } 3822 /* We don't need to worry about FP liveness because it's read-only */ 3823 if (regno == BPF_REG_FP) 3824 return 0; 3825 3826 if (rw64) 3827 mark_insn_zext(env, reg); 3828 3829 return mark_reg_read(env, reg, reg->parent, 3830 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3831 } else { 3832 /* check whether register used as dest operand can be written to */ 3833 if (regno == BPF_REG_FP) { 3834 verbose(env, "frame pointer is read only\n"); 3835 return -EACCES; 3836 } 3837 reg->live |= REG_LIVE_WRITTEN; 3838 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3839 if (t == DST_OP) 3840 mark_reg_unknown(env, regs, regno); 3841 } 3842 return 0; 3843 } 3844 3845 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3846 enum reg_arg_type t) 3847 { 3848 struct bpf_verifier_state *vstate = env->cur_state; 3849 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3850 3851 return __check_reg_arg(env, state->regs, regno, t); 3852 } 3853 3854 static int insn_stack_access_flags(int frameno, int spi) 3855 { 3856 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3857 } 3858 3859 static int insn_stack_access_spi(int insn_flags) 3860 { 3861 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3862 } 3863 3864 static int insn_stack_access_frameno(int insn_flags) 3865 { 3866 return insn_flags & INSN_F_FRAMENO_MASK; 3867 } 3868 3869 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3870 { 3871 env->insn_aux_data[idx].jmp_point = true; 3872 } 3873 3874 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3875 { 3876 return env->insn_aux_data[insn_idx].jmp_point; 3877 } 3878 3879 #define LR_FRAMENO_BITS 3 3880 #define LR_SPI_BITS 6 3881 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3882 #define LR_SIZE_BITS 4 3883 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3884 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3885 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3886 #define LR_SPI_OFF LR_FRAMENO_BITS 3887 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3888 #define LINKED_REGS_MAX 6 3889 3890 struct linked_reg { 3891 u8 frameno; 3892 union { 3893 u8 spi; 3894 u8 regno; 3895 }; 3896 bool is_reg; 3897 }; 3898 3899 struct linked_regs { 3900 int cnt; 3901 struct linked_reg entries[LINKED_REGS_MAX]; 3902 }; 3903 3904 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3905 { 3906 if (s->cnt < LINKED_REGS_MAX) 3907 return &s->entries[s->cnt++]; 3908 3909 return NULL; 3910 } 3911 3912 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track 3913 * number of elements currently in stack. 3914 * Pack one history entry for linked registers as 10 bits in the following format: 3915 * - 3-bits frameno 3916 * - 6-bits spi_or_reg 3917 * - 1-bit is_reg 3918 */ 3919 static u64 linked_regs_pack(struct linked_regs *s) 3920 { 3921 u64 val = 0; 3922 int i; 3923 3924 for (i = 0; i < s->cnt; ++i) { 3925 struct linked_reg *e = &s->entries[i]; 3926 u64 tmp = 0; 3927 3928 tmp |= e->frameno; 3929 tmp |= e->spi << LR_SPI_OFF; 3930 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3931 3932 val <<= LR_ENTRY_BITS; 3933 val |= tmp; 3934 } 3935 val <<= LR_SIZE_BITS; 3936 val |= s->cnt; 3937 return val; 3938 } 3939 3940 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3941 { 3942 int i; 3943 3944 s->cnt = val & LR_SIZE_MASK; 3945 val >>= LR_SIZE_BITS; 3946 3947 for (i = 0; i < s->cnt; ++i) { 3948 struct linked_reg *e = &s->entries[i]; 3949 3950 e->frameno = val & LR_FRAMENO_MASK; 3951 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3952 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3953 val >>= LR_ENTRY_BITS; 3954 } 3955 } 3956 3957 /* for any branch, call, exit record the history of jmps in the given state */ 3958 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3959 int insn_flags, u64 linked_regs) 3960 { 3961 u32 cnt = cur->jmp_history_cnt; 3962 struct bpf_jmp_history_entry *p; 3963 size_t alloc_size; 3964 3965 /* combine instruction flags if we already recorded this instruction */ 3966 if (env->cur_hist_ent) { 3967 /* atomic instructions push insn_flags twice, for READ and 3968 * WRITE sides, but they should agree on stack slot 3969 */ 3970 verifier_bug_if((env->cur_hist_ent->flags & insn_flags) && 3971 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3972 env, "insn history: insn_idx %d cur flags %x new flags %x", 3973 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3974 env->cur_hist_ent->flags |= insn_flags; 3975 verifier_bug_if(env->cur_hist_ent->linked_regs != 0, env, 3976 "insn history: insn_idx %d linked_regs: %#llx", 3977 env->insn_idx, env->cur_hist_ent->linked_regs); 3978 env->cur_hist_ent->linked_regs = linked_regs; 3979 return 0; 3980 } 3981 3982 cnt++; 3983 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3984 p = krealloc(cur->jmp_history, alloc_size, GFP_KERNEL_ACCOUNT); 3985 if (!p) 3986 return -ENOMEM; 3987 cur->jmp_history = p; 3988 3989 p = &cur->jmp_history[cnt - 1]; 3990 p->idx = env->insn_idx; 3991 p->prev_idx = env->prev_insn_idx; 3992 p->flags = insn_flags; 3993 p->linked_regs = linked_regs; 3994 cur->jmp_history_cnt = cnt; 3995 env->cur_hist_ent = p; 3996 3997 return 0; 3998 } 3999 4000 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 4001 u32 hist_end, int insn_idx) 4002 { 4003 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 4004 return &st->jmp_history[hist_end - 1]; 4005 return NULL; 4006 } 4007 4008 /* Backtrack one insn at a time. If idx is not at the top of recorded 4009 * history then previous instruction came from straight line execution. 4010 * Return -ENOENT if we exhausted all instructions within given state. 4011 * 4012 * It's legal to have a bit of a looping with the same starting and ending 4013 * insn index within the same state, e.g.: 3->4->5->3, so just because current 4014 * instruction index is the same as state's first_idx doesn't mean we are 4015 * done. If there is still some jump history left, we should keep going. We 4016 * need to take into account that we might have a jump history between given 4017 * state's parent and itself, due to checkpointing. In this case, we'll have 4018 * history entry recording a jump from last instruction of parent state and 4019 * first instruction of given state. 4020 */ 4021 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 4022 u32 *history) 4023 { 4024 u32 cnt = *history; 4025 4026 if (i == st->first_insn_idx) { 4027 if (cnt == 0) 4028 return -ENOENT; 4029 if (cnt == 1 && st->jmp_history[0].idx == i) 4030 return -ENOENT; 4031 } 4032 4033 if (cnt && st->jmp_history[cnt - 1].idx == i) { 4034 i = st->jmp_history[cnt - 1].prev_idx; 4035 (*history)--; 4036 } else { 4037 i--; 4038 } 4039 return i; 4040 } 4041 4042 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 4043 { 4044 const struct btf_type *func; 4045 struct btf *desc_btf; 4046 4047 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 4048 return NULL; 4049 4050 desc_btf = find_kfunc_desc_btf(data, insn->off); 4051 if (IS_ERR(desc_btf)) 4052 return "<error>"; 4053 4054 func = btf_type_by_id(desc_btf, insn->imm); 4055 return btf_name_by_offset(desc_btf, func->name_off); 4056 } 4057 4058 static void verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn) 4059 { 4060 const struct bpf_insn_cbs cbs = { 4061 .cb_call = disasm_kfunc_name, 4062 .cb_print = verbose, 4063 .private_data = env, 4064 }; 4065 4066 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 4067 } 4068 4069 static inline void bt_init(struct backtrack_state *bt, u32 frame) 4070 { 4071 bt->frame = frame; 4072 } 4073 4074 static inline void bt_reset(struct backtrack_state *bt) 4075 { 4076 struct bpf_verifier_env *env = bt->env; 4077 4078 memset(bt, 0, sizeof(*bt)); 4079 bt->env = env; 4080 } 4081 4082 static inline u32 bt_empty(struct backtrack_state *bt) 4083 { 4084 u64 mask = 0; 4085 int i; 4086 4087 for (i = 0; i <= bt->frame; i++) 4088 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 4089 4090 return mask == 0; 4091 } 4092 4093 static inline int bt_subprog_enter(struct backtrack_state *bt) 4094 { 4095 if (bt->frame == MAX_CALL_FRAMES - 1) { 4096 verifier_bug(bt->env, "subprog enter from frame %d", bt->frame); 4097 return -EFAULT; 4098 } 4099 bt->frame++; 4100 return 0; 4101 } 4102 4103 static inline int bt_subprog_exit(struct backtrack_state *bt) 4104 { 4105 if (bt->frame == 0) { 4106 verifier_bug(bt->env, "subprog exit from frame 0"); 4107 return -EFAULT; 4108 } 4109 bt->frame--; 4110 return 0; 4111 } 4112 4113 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 4114 { 4115 bt->reg_masks[frame] |= 1 << reg; 4116 } 4117 4118 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 4119 { 4120 bt->reg_masks[frame] &= ~(1 << reg); 4121 } 4122 4123 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 4124 { 4125 bt_set_frame_reg(bt, bt->frame, reg); 4126 } 4127 4128 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 4129 { 4130 bt_clear_frame_reg(bt, bt->frame, reg); 4131 } 4132 4133 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 4134 { 4135 bt->stack_masks[frame] |= 1ull << slot; 4136 } 4137 4138 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 4139 { 4140 bt->stack_masks[frame] &= ~(1ull << slot); 4141 } 4142 4143 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 4144 { 4145 return bt->reg_masks[frame]; 4146 } 4147 4148 static inline u32 bt_reg_mask(struct backtrack_state *bt) 4149 { 4150 return bt->reg_masks[bt->frame]; 4151 } 4152 4153 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 4154 { 4155 return bt->stack_masks[frame]; 4156 } 4157 4158 static inline u64 bt_stack_mask(struct backtrack_state *bt) 4159 { 4160 return bt->stack_masks[bt->frame]; 4161 } 4162 4163 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 4164 { 4165 return bt->reg_masks[bt->frame] & (1 << reg); 4166 } 4167 4168 static inline bool bt_is_frame_reg_set(struct backtrack_state *bt, u32 frame, u32 reg) 4169 { 4170 return bt->reg_masks[frame] & (1 << reg); 4171 } 4172 4173 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 4174 { 4175 return bt->stack_masks[frame] & (1ull << slot); 4176 } 4177 4178 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 4179 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 4180 { 4181 DECLARE_BITMAP(mask, 64); 4182 bool first = true; 4183 int i, n; 4184 4185 buf[0] = '\0'; 4186 4187 bitmap_from_u64(mask, reg_mask); 4188 for_each_set_bit(i, mask, 32) { 4189 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 4190 first = false; 4191 buf += n; 4192 buf_sz -= n; 4193 if (buf_sz < 0) 4194 break; 4195 } 4196 } 4197 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 4198 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 4199 { 4200 DECLARE_BITMAP(mask, 64); 4201 bool first = true; 4202 int i, n; 4203 4204 buf[0] = '\0'; 4205 4206 bitmap_from_u64(mask, stack_mask); 4207 for_each_set_bit(i, mask, 64) { 4208 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 4209 first = false; 4210 buf += n; 4211 buf_sz -= n; 4212 if (buf_sz < 0) 4213 break; 4214 } 4215 } 4216 4217 /* If any register R in hist->linked_regs is marked as precise in bt, 4218 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 4219 */ 4220 static void bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 4221 { 4222 struct linked_regs linked_regs; 4223 bool some_precise = false; 4224 int i; 4225 4226 if (!hist || hist->linked_regs == 0) 4227 return; 4228 4229 linked_regs_unpack(hist->linked_regs, &linked_regs); 4230 for (i = 0; i < linked_regs.cnt; ++i) { 4231 struct linked_reg *e = &linked_regs.entries[i]; 4232 4233 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 4234 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 4235 some_precise = true; 4236 break; 4237 } 4238 } 4239 4240 if (!some_precise) 4241 return; 4242 4243 for (i = 0; i < linked_regs.cnt; ++i) { 4244 struct linked_reg *e = &linked_regs.entries[i]; 4245 4246 if (e->is_reg) 4247 bt_set_frame_reg(bt, e->frameno, e->regno); 4248 else 4249 bt_set_frame_slot(bt, e->frameno, e->spi); 4250 } 4251 } 4252 4253 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 4254 4255 /* For given verifier state backtrack_insn() is called from the last insn to 4256 * the first insn. Its purpose is to compute a bitmask of registers and 4257 * stack slots that needs precision in the parent verifier state. 4258 * 4259 * @idx is an index of the instruction we are currently processing; 4260 * @subseq_idx is an index of the subsequent instruction that: 4261 * - *would be* executed next, if jump history is viewed in forward order; 4262 * - *was* processed previously during backtracking. 4263 */ 4264 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 4265 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 4266 { 4267 struct bpf_insn *insn = env->prog->insnsi + idx; 4268 u8 class = BPF_CLASS(insn->code); 4269 u8 opcode = BPF_OP(insn->code); 4270 u8 mode = BPF_MODE(insn->code); 4271 u32 dreg = insn->dst_reg; 4272 u32 sreg = insn->src_reg; 4273 u32 spi, i, fr; 4274 4275 if (insn->code == 0) 4276 return 0; 4277 if (env->log.level & BPF_LOG_LEVEL2) { 4278 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 4279 verbose(env, "mark_precise: frame%d: regs=%s ", 4280 bt->frame, env->tmp_str_buf); 4281 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 4282 verbose(env, "stack=%s before ", env->tmp_str_buf); 4283 verbose(env, "%d: ", idx); 4284 verbose_insn(env, insn); 4285 } 4286 4287 /* If there is a history record that some registers gained range at this insn, 4288 * propagate precision marks to those registers, so that bt_is_reg_set() 4289 * accounts for these registers. 4290 */ 4291 bt_sync_linked_regs(bt, hist); 4292 4293 if (class == BPF_ALU || class == BPF_ALU64) { 4294 if (!bt_is_reg_set(bt, dreg)) 4295 return 0; 4296 if (opcode == BPF_END || opcode == BPF_NEG) { 4297 /* sreg is reserved and unused 4298 * dreg still need precision before this insn 4299 */ 4300 return 0; 4301 } else if (opcode == BPF_MOV) { 4302 if (BPF_SRC(insn->code) == BPF_X) { 4303 /* dreg = sreg or dreg = (s8, s16, s32)sreg 4304 * dreg needs precision after this insn 4305 * sreg needs precision before this insn 4306 */ 4307 bt_clear_reg(bt, dreg); 4308 if (sreg != BPF_REG_FP) 4309 bt_set_reg(bt, sreg); 4310 } else { 4311 /* dreg = K 4312 * dreg needs precision after this insn. 4313 * Corresponding register is already marked 4314 * as precise=true in this verifier state. 4315 * No further markings in parent are necessary 4316 */ 4317 bt_clear_reg(bt, dreg); 4318 } 4319 } else { 4320 if (BPF_SRC(insn->code) == BPF_X) { 4321 /* dreg += sreg 4322 * both dreg and sreg need precision 4323 * before this insn 4324 */ 4325 if (sreg != BPF_REG_FP) 4326 bt_set_reg(bt, sreg); 4327 } /* else dreg += K 4328 * dreg still needs precision before this insn 4329 */ 4330 } 4331 } else if (class == BPF_LDX || is_atomic_load_insn(insn)) { 4332 if (!bt_is_reg_set(bt, dreg)) 4333 return 0; 4334 bt_clear_reg(bt, dreg); 4335 4336 /* scalars can only be spilled into stack w/o losing precision. 4337 * Load from any other memory can be zero extended. 4338 * The desire to keep that precision is already indicated 4339 * by 'precise' mark in corresponding register of this state. 4340 * No further tracking necessary. 4341 */ 4342 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 4343 return 0; 4344 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 4345 * that [fp - off] slot contains scalar that needs to be 4346 * tracked with precision 4347 */ 4348 spi = insn_stack_access_spi(hist->flags); 4349 fr = insn_stack_access_frameno(hist->flags); 4350 bt_set_frame_slot(bt, fr, spi); 4351 } else if (class == BPF_STX || class == BPF_ST) { 4352 if (bt_is_reg_set(bt, dreg)) 4353 /* stx & st shouldn't be using _scalar_ dst_reg 4354 * to access memory. It means backtracking 4355 * encountered a case of pointer subtraction. 4356 */ 4357 return -ENOTSUPP; 4358 /* scalars can only be spilled into stack */ 4359 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 4360 return 0; 4361 spi = insn_stack_access_spi(hist->flags); 4362 fr = insn_stack_access_frameno(hist->flags); 4363 if (!bt_is_frame_slot_set(bt, fr, spi)) 4364 return 0; 4365 bt_clear_frame_slot(bt, fr, spi); 4366 if (class == BPF_STX) 4367 bt_set_reg(bt, sreg); 4368 } else if (class == BPF_JMP || class == BPF_JMP32) { 4369 if (bpf_pseudo_call(insn)) { 4370 int subprog_insn_idx, subprog; 4371 4372 subprog_insn_idx = idx + insn->imm + 1; 4373 subprog = find_subprog(env, subprog_insn_idx); 4374 if (subprog < 0) 4375 return -EFAULT; 4376 4377 if (subprog_is_global(env, subprog)) { 4378 /* check that jump history doesn't have any 4379 * extra instructions from subprog; the next 4380 * instruction after call to global subprog 4381 * should be literally next instruction in 4382 * caller program 4383 */ 4384 verifier_bug_if(idx + 1 != subseq_idx, env, 4385 "extra insn from subprog"); 4386 /* r1-r5 are invalidated after subprog call, 4387 * so for global func call it shouldn't be set 4388 * anymore 4389 */ 4390 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 4391 verifier_bug(env, "global subprog unexpected regs %x", 4392 bt_reg_mask(bt)); 4393 return -EFAULT; 4394 } 4395 /* global subprog always sets R0 */ 4396 bt_clear_reg(bt, BPF_REG_0); 4397 return 0; 4398 } else { 4399 /* static subprog call instruction, which 4400 * means that we are exiting current subprog, 4401 * so only r1-r5 could be still requested as 4402 * precise, r0 and r6-r10 or any stack slot in 4403 * the current frame should be zero by now 4404 */ 4405 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 4406 verifier_bug(env, "static subprog unexpected regs %x", 4407 bt_reg_mask(bt)); 4408 return -EFAULT; 4409 } 4410 /* we are now tracking register spills correctly, 4411 * so any instance of leftover slots is a bug 4412 */ 4413 if (bt_stack_mask(bt) != 0) { 4414 verifier_bug(env, 4415 "static subprog leftover stack slots %llx", 4416 bt_stack_mask(bt)); 4417 return -EFAULT; 4418 } 4419 /* propagate r1-r5 to the caller */ 4420 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 4421 if (bt_is_reg_set(bt, i)) { 4422 bt_clear_reg(bt, i); 4423 bt_set_frame_reg(bt, bt->frame - 1, i); 4424 } 4425 } 4426 if (bt_subprog_exit(bt)) 4427 return -EFAULT; 4428 return 0; 4429 } 4430 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 4431 /* exit from callback subprog to callback-calling helper or 4432 * kfunc call. Use idx/subseq_idx check to discern it from 4433 * straight line code backtracking. 4434 * Unlike the subprog call handling above, we shouldn't 4435 * propagate precision of r1-r5 (if any requested), as they are 4436 * not actually arguments passed directly to callback subprogs 4437 */ 4438 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 4439 verifier_bug(env, "callback unexpected regs %x", 4440 bt_reg_mask(bt)); 4441 return -EFAULT; 4442 } 4443 if (bt_stack_mask(bt) != 0) { 4444 verifier_bug(env, "callback leftover stack slots %llx", 4445 bt_stack_mask(bt)); 4446 return -EFAULT; 4447 } 4448 /* clear r1-r5 in callback subprog's mask */ 4449 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 4450 bt_clear_reg(bt, i); 4451 if (bt_subprog_exit(bt)) 4452 return -EFAULT; 4453 return 0; 4454 } else if (opcode == BPF_CALL) { 4455 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 4456 * catch this error later. Make backtracking conservative 4457 * with ENOTSUPP. 4458 */ 4459 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 4460 return -ENOTSUPP; 4461 /* regular helper call sets R0 */ 4462 bt_clear_reg(bt, BPF_REG_0); 4463 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 4464 /* if backtracking was looking for registers R1-R5 4465 * they should have been found already. 4466 */ 4467 verifier_bug(env, "backtracking call unexpected regs %x", 4468 bt_reg_mask(bt)); 4469 return -EFAULT; 4470 } 4471 } else if (opcode == BPF_EXIT) { 4472 bool r0_precise; 4473 4474 /* Backtracking to a nested function call, 'idx' is a part of 4475 * the inner frame 'subseq_idx' is a part of the outer frame. 4476 * In case of a regular function call, instructions giving 4477 * precision to registers R1-R5 should have been found already. 4478 * In case of a callback, it is ok to have R1-R5 marked for 4479 * backtracking, as these registers are set by the function 4480 * invoking callback. 4481 */ 4482 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 4483 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 4484 bt_clear_reg(bt, i); 4485 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 4486 verifier_bug(env, "backtracking exit unexpected regs %x", 4487 bt_reg_mask(bt)); 4488 return -EFAULT; 4489 } 4490 4491 /* BPF_EXIT in subprog or callback always returns 4492 * right after the call instruction, so by checking 4493 * whether the instruction at subseq_idx-1 is subprog 4494 * call or not we can distinguish actual exit from 4495 * *subprog* from exit from *callback*. In the former 4496 * case, we need to propagate r0 precision, if 4497 * necessary. In the former we never do that. 4498 */ 4499 r0_precise = subseq_idx - 1 >= 0 && 4500 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 4501 bt_is_reg_set(bt, BPF_REG_0); 4502 4503 bt_clear_reg(bt, BPF_REG_0); 4504 if (bt_subprog_enter(bt)) 4505 return -EFAULT; 4506 4507 if (r0_precise) 4508 bt_set_reg(bt, BPF_REG_0); 4509 /* r6-r9 and stack slots will stay set in caller frame 4510 * bitmasks until we return back from callee(s) 4511 */ 4512 return 0; 4513 } else if (BPF_SRC(insn->code) == BPF_X) { 4514 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 4515 return 0; 4516 /* dreg <cond> sreg 4517 * Both dreg and sreg need precision before 4518 * this insn. If only sreg was marked precise 4519 * before it would be equally necessary to 4520 * propagate it to dreg. 4521 */ 4522 if (!hist || !(hist->flags & INSN_F_SRC_REG_STACK)) 4523 bt_set_reg(bt, sreg); 4524 if (!hist || !(hist->flags & INSN_F_DST_REG_STACK)) 4525 bt_set_reg(bt, dreg); 4526 } else if (BPF_SRC(insn->code) == BPF_K) { 4527 /* dreg <cond> K 4528 * Only dreg still needs precision before 4529 * this insn, so for the K-based conditional 4530 * there is nothing new to be marked. 4531 */ 4532 } 4533 } else if (class == BPF_LD) { 4534 if (!bt_is_reg_set(bt, dreg)) 4535 return 0; 4536 bt_clear_reg(bt, dreg); 4537 /* It's ld_imm64 or ld_abs or ld_ind. 4538 * For ld_imm64 no further tracking of precision 4539 * into parent is necessary 4540 */ 4541 if (mode == BPF_IND || mode == BPF_ABS) 4542 /* to be analyzed */ 4543 return -ENOTSUPP; 4544 } 4545 /* Propagate precision marks to linked registers, to account for 4546 * registers marked as precise in this function. 4547 */ 4548 bt_sync_linked_regs(bt, hist); 4549 return 0; 4550 } 4551 4552 /* the scalar precision tracking algorithm: 4553 * . at the start all registers have precise=false. 4554 * . scalar ranges are tracked as normal through alu and jmp insns. 4555 * . once precise value of the scalar register is used in: 4556 * . ptr + scalar alu 4557 * . if (scalar cond K|scalar) 4558 * . helper_call(.., scalar, ...) where ARG_CONST is expected 4559 * backtrack through the verifier states and mark all registers and 4560 * stack slots with spilled constants that these scalar registers 4561 * should be precise. 4562 * . during state pruning two registers (or spilled stack slots) 4563 * are equivalent if both are not precise. 4564 * 4565 * Note the verifier cannot simply walk register parentage chain, 4566 * since many different registers and stack slots could have been 4567 * used to compute single precise scalar. 4568 * 4569 * The approach of starting with precise=true for all registers and then 4570 * backtrack to mark a register as not precise when the verifier detects 4571 * that program doesn't care about specific value (e.g., when helper 4572 * takes register as ARG_ANYTHING parameter) is not safe. 4573 * 4574 * It's ok to walk single parentage chain of the verifier states. 4575 * It's possible that this backtracking will go all the way till 1st insn. 4576 * All other branches will be explored for needing precision later. 4577 * 4578 * The backtracking needs to deal with cases like: 4579 * 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) 4580 * r9 -= r8 4581 * r5 = r9 4582 * if r5 > 0x79f goto pc+7 4583 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 4584 * r5 += 1 4585 * ... 4586 * call bpf_perf_event_output#25 4587 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 4588 * 4589 * and this case: 4590 * r6 = 1 4591 * call foo // uses callee's r6 inside to compute r0 4592 * r0 += r6 4593 * if r0 == 0 goto 4594 * 4595 * to track above reg_mask/stack_mask needs to be independent for each frame. 4596 * 4597 * Also if parent's curframe > frame where backtracking started, 4598 * the verifier need to mark registers in both frames, otherwise callees 4599 * may incorrectly prune callers. This is similar to 4600 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 4601 * 4602 * For now backtracking falls back into conservative marking. 4603 */ 4604 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 4605 struct bpf_verifier_state *st) 4606 { 4607 struct bpf_func_state *func; 4608 struct bpf_reg_state *reg; 4609 int i, j; 4610 4611 if (env->log.level & BPF_LOG_LEVEL2) { 4612 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 4613 st->curframe); 4614 } 4615 4616 /* big hammer: mark all scalars precise in this path. 4617 * pop_stack may still get !precise scalars. 4618 * We also skip current state and go straight to first parent state, 4619 * because precision markings in current non-checkpointed state are 4620 * not needed. See why in the comment in __mark_chain_precision below. 4621 */ 4622 for (st = st->parent; st; st = st->parent) { 4623 for (i = 0; i <= st->curframe; i++) { 4624 func = st->frame[i]; 4625 for (j = 0; j < BPF_REG_FP; j++) { 4626 reg = &func->regs[j]; 4627 if (reg->type != SCALAR_VALUE || reg->precise) 4628 continue; 4629 reg->precise = true; 4630 if (env->log.level & BPF_LOG_LEVEL2) { 4631 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 4632 i, j); 4633 } 4634 } 4635 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4636 if (!is_spilled_reg(&func->stack[j])) 4637 continue; 4638 reg = &func->stack[j].spilled_ptr; 4639 if (reg->type != SCALAR_VALUE || reg->precise) 4640 continue; 4641 reg->precise = true; 4642 if (env->log.level & BPF_LOG_LEVEL2) { 4643 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 4644 i, -(j + 1) * 8); 4645 } 4646 } 4647 } 4648 } 4649 } 4650 4651 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4652 { 4653 struct bpf_func_state *func; 4654 struct bpf_reg_state *reg; 4655 int i, j; 4656 4657 for (i = 0; i <= st->curframe; i++) { 4658 func = st->frame[i]; 4659 for (j = 0; j < BPF_REG_FP; j++) { 4660 reg = &func->regs[j]; 4661 if (reg->type != SCALAR_VALUE) 4662 continue; 4663 reg->precise = false; 4664 } 4665 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 4666 if (!is_spilled_reg(&func->stack[j])) 4667 continue; 4668 reg = &func->stack[j].spilled_ptr; 4669 if (reg->type != SCALAR_VALUE) 4670 continue; 4671 reg->precise = false; 4672 } 4673 } 4674 } 4675 4676 /* 4677 * __mark_chain_precision() backtracks BPF program instruction sequence and 4678 * chain of verifier states making sure that register *regno* (if regno >= 0) 4679 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4680 * SCALARS, as well as any other registers and slots that contribute to 4681 * a tracked state of given registers/stack slots, depending on specific BPF 4682 * assembly instructions (see backtrack_insns() for exact instruction handling 4683 * logic). This backtracking relies on recorded jmp_history and is able to 4684 * traverse entire chain of parent states. This process ends only when all the 4685 * necessary registers/slots and their transitive dependencies are marked as 4686 * precise. 4687 * 4688 * One important and subtle aspect is that precise marks *do not matter* in 4689 * the currently verified state (current state). It is important to understand 4690 * why this is the case. 4691 * 4692 * First, note that current state is the state that is not yet "checkpointed", 4693 * i.e., it is not yet put into env->explored_states, and it has no children 4694 * states as well. It's ephemeral, and can end up either a) being discarded if 4695 * compatible explored state is found at some point or BPF_EXIT instruction is 4696 * reached or b) checkpointed and put into env->explored_states, branching out 4697 * into one or more children states. 4698 * 4699 * In the former case, precise markings in current state are completely 4700 * ignored by state comparison code (see regsafe() for details). Only 4701 * checkpointed ("old") state precise markings are important, and if old 4702 * state's register/slot is precise, regsafe() assumes current state's 4703 * register/slot as precise and checks value ranges exactly and precisely. If 4704 * states turn out to be compatible, current state's necessary precise 4705 * markings and any required parent states' precise markings are enforced 4706 * after the fact with propagate_precision() logic, after the fact. But it's 4707 * important to realize that in this case, even after marking current state 4708 * registers/slots as precise, we immediately discard current state. So what 4709 * actually matters is any of the precise markings propagated into current 4710 * state's parent states, which are always checkpointed (due to b) case above). 4711 * As such, for scenario a) it doesn't matter if current state has precise 4712 * markings set or not. 4713 * 4714 * Now, for the scenario b), checkpointing and forking into child(ren) 4715 * state(s). Note that before current state gets to checkpointing step, any 4716 * processed instruction always assumes precise SCALAR register/slot 4717 * knowledge: if precise value or range is useful to prune jump branch, BPF 4718 * verifier takes this opportunity enthusiastically. Similarly, when 4719 * register's value is used to calculate offset or memory address, exact 4720 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4721 * what we mentioned above about state comparison ignoring precise markings 4722 * during state comparison, BPF verifier ignores and also assumes precise 4723 * markings *at will* during instruction verification process. But as verifier 4724 * assumes precision, it also propagates any precision dependencies across 4725 * parent states, which are not yet finalized, so can be further restricted 4726 * based on new knowledge gained from restrictions enforced by their children 4727 * states. This is so that once those parent states are finalized, i.e., when 4728 * they have no more active children state, state comparison logic in 4729 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4730 * required for correctness. 4731 * 4732 * To build a bit more intuition, note also that once a state is checkpointed, 4733 * the path we took to get to that state is not important. This is crucial 4734 * property for state pruning. When state is checkpointed and finalized at 4735 * some instruction index, it can be correctly and safely used to "short 4736 * circuit" any *compatible* state that reaches exactly the same instruction 4737 * index. I.e., if we jumped to that instruction from a completely different 4738 * code path than original finalized state was derived from, it doesn't 4739 * matter, current state can be discarded because from that instruction 4740 * forward having a compatible state will ensure we will safely reach the 4741 * exit. States describe preconditions for further exploration, but completely 4742 * forget the history of how we got here. 4743 * 4744 * This also means that even if we needed precise SCALAR range to get to 4745 * finalized state, but from that point forward *that same* SCALAR register is 4746 * never used in a precise context (i.e., it's precise value is not needed for 4747 * correctness), it's correct and safe to mark such register as "imprecise" 4748 * (i.e., precise marking set to false). This is what we rely on when we do 4749 * not set precise marking in current state. If no child state requires 4750 * precision for any given SCALAR register, it's safe to dictate that it can 4751 * be imprecise. If any child state does require this register to be precise, 4752 * we'll mark it precise later retroactively during precise markings 4753 * propagation from child state to parent states. 4754 * 4755 * Skipping precise marking setting in current state is a mild version of 4756 * relying on the above observation. But we can utilize this property even 4757 * more aggressively by proactively forgetting any precise marking in the 4758 * current state (which we inherited from the parent state), right before we 4759 * checkpoint it and branch off into new child state. This is done by 4760 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4761 * finalized states which help in short circuiting more future states. 4762 */ 4763 static int __mark_chain_precision(struct bpf_verifier_env *env, 4764 struct bpf_verifier_state *starting_state, 4765 int regno, 4766 bool *changed) 4767 { 4768 struct bpf_verifier_state *st = starting_state; 4769 struct backtrack_state *bt = &env->bt; 4770 int first_idx = st->first_insn_idx; 4771 int last_idx = starting_state->insn_idx; 4772 int subseq_idx = -1; 4773 struct bpf_func_state *func; 4774 bool tmp, skip_first = true; 4775 struct bpf_reg_state *reg; 4776 int i, fr, err; 4777 4778 if (!env->bpf_capable) 4779 return 0; 4780 4781 changed = changed ?: &tmp; 4782 /* set frame number from which we are starting to backtrack */ 4783 bt_init(bt, starting_state->curframe); 4784 4785 /* Do sanity checks against current state of register and/or stack 4786 * slot, but don't set precise flag in current state, as precision 4787 * tracking in the current state is unnecessary. 4788 */ 4789 func = st->frame[bt->frame]; 4790 if (regno >= 0) { 4791 reg = &func->regs[regno]; 4792 if (reg->type != SCALAR_VALUE) { 4793 verifier_bug(env, "backtracking misuse"); 4794 return -EFAULT; 4795 } 4796 bt_set_reg(bt, regno); 4797 } 4798 4799 if (bt_empty(bt)) 4800 return 0; 4801 4802 for (;;) { 4803 DECLARE_BITMAP(mask, 64); 4804 u32 history = st->jmp_history_cnt; 4805 struct bpf_jmp_history_entry *hist; 4806 4807 if (env->log.level & BPF_LOG_LEVEL2) { 4808 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4809 bt->frame, last_idx, first_idx, subseq_idx); 4810 } 4811 4812 if (last_idx < 0) { 4813 /* we are at the entry into subprog, which 4814 * is expected for global funcs, but only if 4815 * requested precise registers are R1-R5 4816 * (which are global func's input arguments) 4817 */ 4818 if (st->curframe == 0 && 4819 st->frame[0]->subprogno > 0 && 4820 st->frame[0]->callsite == BPF_MAIN_FUNC && 4821 bt_stack_mask(bt) == 0 && 4822 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4823 bitmap_from_u64(mask, bt_reg_mask(bt)); 4824 for_each_set_bit(i, mask, 32) { 4825 reg = &st->frame[0]->regs[i]; 4826 bt_clear_reg(bt, i); 4827 if (reg->type == SCALAR_VALUE) { 4828 reg->precise = true; 4829 *changed = true; 4830 } 4831 } 4832 return 0; 4833 } 4834 4835 verifier_bug(env, "backtracking func entry subprog %d reg_mask %x stack_mask %llx", 4836 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4837 return -EFAULT; 4838 } 4839 4840 for (i = last_idx;;) { 4841 if (skip_first) { 4842 err = 0; 4843 skip_first = false; 4844 } else { 4845 hist = get_jmp_hist_entry(st, history, i); 4846 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4847 } 4848 if (err == -ENOTSUPP) { 4849 mark_all_scalars_precise(env, starting_state); 4850 bt_reset(bt); 4851 return 0; 4852 } else if (err) { 4853 return err; 4854 } 4855 if (bt_empty(bt)) 4856 /* Found assignment(s) into tracked register in this state. 4857 * Since this state is already marked, just return. 4858 * Nothing to be tracked further in the parent state. 4859 */ 4860 return 0; 4861 subseq_idx = i; 4862 i = get_prev_insn_idx(st, i, &history); 4863 if (i == -ENOENT) 4864 break; 4865 if (i >= env->prog->len) { 4866 /* This can happen if backtracking reached insn 0 4867 * and there are still reg_mask or stack_mask 4868 * to backtrack. 4869 * It means the backtracking missed the spot where 4870 * particular register was initialized with a constant. 4871 */ 4872 verifier_bug(env, "backtracking idx %d", i); 4873 return -EFAULT; 4874 } 4875 } 4876 st = st->parent; 4877 if (!st) 4878 break; 4879 4880 for (fr = bt->frame; fr >= 0; fr--) { 4881 func = st->frame[fr]; 4882 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4883 for_each_set_bit(i, mask, 32) { 4884 reg = &func->regs[i]; 4885 if (reg->type != SCALAR_VALUE) { 4886 bt_clear_frame_reg(bt, fr, i); 4887 continue; 4888 } 4889 if (reg->precise) { 4890 bt_clear_frame_reg(bt, fr, i); 4891 } else { 4892 reg->precise = true; 4893 *changed = true; 4894 } 4895 } 4896 4897 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4898 for_each_set_bit(i, mask, 64) { 4899 if (verifier_bug_if(i >= func->allocated_stack / BPF_REG_SIZE, 4900 env, "stack slot %d, total slots %d", 4901 i, func->allocated_stack / BPF_REG_SIZE)) 4902 return -EFAULT; 4903 4904 if (!is_spilled_scalar_reg(&func->stack[i])) { 4905 bt_clear_frame_slot(bt, fr, i); 4906 continue; 4907 } 4908 reg = &func->stack[i].spilled_ptr; 4909 if (reg->precise) { 4910 bt_clear_frame_slot(bt, fr, i); 4911 } else { 4912 reg->precise = true; 4913 *changed = true; 4914 } 4915 } 4916 if (env->log.level & BPF_LOG_LEVEL2) { 4917 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4918 bt_frame_reg_mask(bt, fr)); 4919 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4920 fr, env->tmp_str_buf); 4921 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4922 bt_frame_stack_mask(bt, fr)); 4923 verbose(env, "stack=%s: ", env->tmp_str_buf); 4924 print_verifier_state(env, st, fr, true); 4925 } 4926 } 4927 4928 if (bt_empty(bt)) 4929 return 0; 4930 4931 subseq_idx = first_idx; 4932 last_idx = st->last_insn_idx; 4933 first_idx = st->first_insn_idx; 4934 } 4935 4936 /* if we still have requested precise regs or slots, we missed 4937 * something (e.g., stack access through non-r10 register), so 4938 * fallback to marking all precise 4939 */ 4940 if (!bt_empty(bt)) { 4941 mark_all_scalars_precise(env, starting_state); 4942 bt_reset(bt); 4943 } 4944 4945 return 0; 4946 } 4947 4948 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4949 { 4950 return __mark_chain_precision(env, env->cur_state, regno, NULL); 4951 } 4952 4953 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4954 * desired reg and stack masks across all relevant frames 4955 */ 4956 static int mark_chain_precision_batch(struct bpf_verifier_env *env, 4957 struct bpf_verifier_state *starting_state) 4958 { 4959 return __mark_chain_precision(env, starting_state, -1, NULL); 4960 } 4961 4962 static bool is_spillable_regtype(enum bpf_reg_type type) 4963 { 4964 switch (base_type(type)) { 4965 case PTR_TO_MAP_VALUE: 4966 case PTR_TO_STACK: 4967 case PTR_TO_CTX: 4968 case PTR_TO_PACKET: 4969 case PTR_TO_PACKET_META: 4970 case PTR_TO_PACKET_END: 4971 case PTR_TO_FLOW_KEYS: 4972 case CONST_PTR_TO_MAP: 4973 case PTR_TO_SOCKET: 4974 case PTR_TO_SOCK_COMMON: 4975 case PTR_TO_TCP_SOCK: 4976 case PTR_TO_XDP_SOCK: 4977 case PTR_TO_BTF_ID: 4978 case PTR_TO_BUF: 4979 case PTR_TO_MEM: 4980 case PTR_TO_FUNC: 4981 case PTR_TO_MAP_KEY: 4982 case PTR_TO_ARENA: 4983 return true; 4984 default: 4985 return false; 4986 } 4987 } 4988 4989 /* Does this register contain a constant zero? */ 4990 static bool register_is_null(struct bpf_reg_state *reg) 4991 { 4992 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4993 } 4994 4995 /* check if register is a constant scalar value */ 4996 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 4997 { 4998 return reg->type == SCALAR_VALUE && 4999 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 5000 } 5001 5002 /* assuming is_reg_const() is true, return constant value of a register */ 5003 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 5004 { 5005 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 5006 } 5007 5008 static bool __is_pointer_value(bool allow_ptr_leaks, 5009 const struct bpf_reg_state *reg) 5010 { 5011 if (allow_ptr_leaks) 5012 return false; 5013 5014 return reg->type != SCALAR_VALUE; 5015 } 5016 5017 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 5018 struct bpf_reg_state *src_reg) 5019 { 5020 if (src_reg->type != SCALAR_VALUE) 5021 return; 5022 5023 if (src_reg->id & BPF_ADD_CONST) { 5024 /* 5025 * The verifier is processing rX = rY insn and 5026 * rY->id has special linked register already. 5027 * Cleared it, since multiple rX += const are not supported. 5028 */ 5029 src_reg->id = 0; 5030 src_reg->off = 0; 5031 } 5032 5033 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 5034 /* Ensure that src_reg has a valid ID that will be copied to 5035 * dst_reg and then will be used by sync_linked_regs() to 5036 * propagate min/max range. 5037 */ 5038 src_reg->id = ++env->id_gen; 5039 } 5040 5041 /* Copy src state preserving dst->parent and dst->live fields */ 5042 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 5043 { 5044 struct bpf_reg_state *parent = dst->parent; 5045 enum bpf_reg_liveness live = dst->live; 5046 5047 *dst = *src; 5048 dst->parent = parent; 5049 dst->live = live; 5050 } 5051 5052 static void save_register_state(struct bpf_verifier_env *env, 5053 struct bpf_func_state *state, 5054 int spi, struct bpf_reg_state *reg, 5055 int size) 5056 { 5057 int i; 5058 5059 copy_register_state(&state->stack[spi].spilled_ptr, reg); 5060 if (size == BPF_REG_SIZE) 5061 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 5062 5063 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 5064 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 5065 5066 /* size < 8 bytes spill */ 5067 for (; i; i--) 5068 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 5069 } 5070 5071 static bool is_bpf_st_mem(struct bpf_insn *insn) 5072 { 5073 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 5074 } 5075 5076 static int get_reg_width(struct bpf_reg_state *reg) 5077 { 5078 return fls64(reg->umax_value); 5079 } 5080 5081 /* See comment for mark_fastcall_pattern_for_call() */ 5082 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 5083 struct bpf_func_state *state, int insn_idx, int off) 5084 { 5085 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 5086 struct bpf_insn_aux_data *aux = env->insn_aux_data; 5087 int i; 5088 5089 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 5090 return; 5091 /* access to the region [max_stack_depth .. fastcall_stack_off) 5092 * from something that is not a part of the fastcall pattern, 5093 * disable fastcall rewrites for current subprogram by setting 5094 * fastcall_stack_off to a value smaller than any possible offset. 5095 */ 5096 subprog->fastcall_stack_off = S16_MIN; 5097 /* reset fastcall aux flags within subprogram, 5098 * happens at most once per subprogram 5099 */ 5100 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 5101 aux[i].fastcall_spills_num = 0; 5102 aux[i].fastcall_pattern = 0; 5103 } 5104 } 5105 5106 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 5107 * stack boundary and alignment are checked in check_mem_access() 5108 */ 5109 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 5110 /* stack frame we're writing to */ 5111 struct bpf_func_state *state, 5112 int off, int size, int value_regno, 5113 int insn_idx) 5114 { 5115 struct bpf_func_state *cur; /* state of the current function */ 5116 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 5117 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5118 struct bpf_reg_state *reg = NULL; 5119 int insn_flags = insn_stack_access_flags(state->frameno, spi); 5120 5121 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 5122 * so it's aligned access and [off, off + size) are within stack limits 5123 */ 5124 if (!env->allow_ptr_leaks && 5125 is_spilled_reg(&state->stack[spi]) && 5126 !is_spilled_scalar_reg(&state->stack[spi]) && 5127 size != BPF_REG_SIZE) { 5128 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 5129 return -EACCES; 5130 } 5131 5132 cur = env->cur_state->frame[env->cur_state->curframe]; 5133 if (value_regno >= 0) 5134 reg = &cur->regs[value_regno]; 5135 if (!env->bypass_spec_v4) { 5136 bool sanitize = reg && is_spillable_regtype(reg->type); 5137 5138 for (i = 0; i < size; i++) { 5139 u8 type = state->stack[spi].slot_type[i]; 5140 5141 if (type != STACK_MISC && type != STACK_ZERO) { 5142 sanitize = true; 5143 break; 5144 } 5145 } 5146 5147 if (sanitize) 5148 env->insn_aux_data[insn_idx].nospec_result = true; 5149 } 5150 5151 err = destroy_if_dynptr_stack_slot(env, state, spi); 5152 if (err) 5153 return err; 5154 5155 check_fastcall_stack_contract(env, state, insn_idx, off); 5156 mark_stack_slot_scratched(env, spi); 5157 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 5158 bool reg_value_fits; 5159 5160 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 5161 /* Make sure that reg had an ID to build a relation on spill. */ 5162 if (reg_value_fits) 5163 assign_scalar_id_before_mov(env, reg); 5164 save_register_state(env, state, spi, reg, size); 5165 /* Break the relation on a narrowing spill. */ 5166 if (!reg_value_fits) 5167 state->stack[spi].spilled_ptr.id = 0; 5168 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 5169 env->bpf_capable) { 5170 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 5171 5172 memset(tmp_reg, 0, sizeof(*tmp_reg)); 5173 __mark_reg_known(tmp_reg, insn->imm); 5174 tmp_reg->type = SCALAR_VALUE; 5175 save_register_state(env, state, spi, tmp_reg, size); 5176 } else if (reg && is_spillable_regtype(reg->type)) { 5177 /* register containing pointer is being spilled into stack */ 5178 if (size != BPF_REG_SIZE) { 5179 verbose_linfo(env, insn_idx, "; "); 5180 verbose(env, "invalid size of register spill\n"); 5181 return -EACCES; 5182 } 5183 if (state != cur && reg->type == PTR_TO_STACK) { 5184 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 5185 return -EINVAL; 5186 } 5187 save_register_state(env, state, spi, reg, size); 5188 } else { 5189 u8 type = STACK_MISC; 5190 5191 /* regular write of data into stack destroys any spilled ptr */ 5192 state->stack[spi].spilled_ptr.type = NOT_INIT; 5193 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 5194 if (is_stack_slot_special(&state->stack[spi])) 5195 for (i = 0; i < BPF_REG_SIZE; i++) 5196 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 5197 5198 /* only mark the slot as written if all 8 bytes were written 5199 * otherwise read propagation may incorrectly stop too soon 5200 * when stack slots are partially written. 5201 * This heuristic means that read propagation will be 5202 * conservative, since it will add reg_live_read marks 5203 * to stack slots all the way to first state when programs 5204 * writes+reads less than 8 bytes 5205 */ 5206 if (size == BPF_REG_SIZE) 5207 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 5208 5209 /* when we zero initialize stack slots mark them as such */ 5210 if ((reg && register_is_null(reg)) || 5211 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 5212 /* STACK_ZERO case happened because register spill 5213 * wasn't properly aligned at the stack slot boundary, 5214 * so it's not a register spill anymore; force 5215 * originating register to be precise to make 5216 * STACK_ZERO correct for subsequent states 5217 */ 5218 err = mark_chain_precision(env, value_regno); 5219 if (err) 5220 return err; 5221 type = STACK_ZERO; 5222 } 5223 5224 /* Mark slots affected by this stack write. */ 5225 for (i = 0; i < size; i++) 5226 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 5227 insn_flags = 0; /* not a register spill */ 5228 } 5229 5230 if (insn_flags) 5231 return push_jmp_history(env, env->cur_state, insn_flags, 0); 5232 return 0; 5233 } 5234 5235 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 5236 * known to contain a variable offset. 5237 * This function checks whether the write is permitted and conservatively 5238 * tracks the effects of the write, considering that each stack slot in the 5239 * dynamic range is potentially written to. 5240 * 5241 * 'off' includes 'regno->off'. 5242 * 'value_regno' can be -1, meaning that an unknown value is being written to 5243 * the stack. 5244 * 5245 * Spilled pointers in range are not marked as written because we don't know 5246 * what's going to be actually written. This means that read propagation for 5247 * future reads cannot be terminated by this write. 5248 * 5249 * For privileged programs, uninitialized stack slots are considered 5250 * initialized by this write (even though we don't know exactly what offsets 5251 * are going to be written to). The idea is that we don't want the verifier to 5252 * reject future reads that access slots written to through variable offsets. 5253 */ 5254 static int check_stack_write_var_off(struct bpf_verifier_env *env, 5255 /* func where register points to */ 5256 struct bpf_func_state *state, 5257 int ptr_regno, int off, int size, 5258 int value_regno, int insn_idx) 5259 { 5260 struct bpf_func_state *cur; /* state of the current function */ 5261 int min_off, max_off; 5262 int i, err; 5263 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 5264 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5265 bool writing_zero = false; 5266 /* set if the fact that we're writing a zero is used to let any 5267 * stack slots remain STACK_ZERO 5268 */ 5269 bool zero_used = false; 5270 5271 cur = env->cur_state->frame[env->cur_state->curframe]; 5272 ptr_reg = &cur->regs[ptr_regno]; 5273 min_off = ptr_reg->smin_value + off; 5274 max_off = ptr_reg->smax_value + off + size; 5275 if (value_regno >= 0) 5276 value_reg = &cur->regs[value_regno]; 5277 if ((value_reg && register_is_null(value_reg)) || 5278 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 5279 writing_zero = true; 5280 5281 for (i = min_off; i < max_off; i++) { 5282 int spi; 5283 5284 spi = __get_spi(i); 5285 err = destroy_if_dynptr_stack_slot(env, state, spi); 5286 if (err) 5287 return err; 5288 } 5289 5290 check_fastcall_stack_contract(env, state, insn_idx, min_off); 5291 /* Variable offset writes destroy any spilled pointers in range. */ 5292 for (i = min_off; i < max_off; i++) { 5293 u8 new_type, *stype; 5294 int slot, spi; 5295 5296 slot = -i - 1; 5297 spi = slot / BPF_REG_SIZE; 5298 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 5299 mark_stack_slot_scratched(env, spi); 5300 5301 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 5302 /* Reject the write if range we may write to has not 5303 * been initialized beforehand. If we didn't reject 5304 * here, the ptr status would be erased below (even 5305 * though not all slots are actually overwritten), 5306 * possibly opening the door to leaks. 5307 * 5308 * We do however catch STACK_INVALID case below, and 5309 * only allow reading possibly uninitialized memory 5310 * later for CAP_PERFMON, as the write may not happen to 5311 * that slot. 5312 */ 5313 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 5314 insn_idx, i); 5315 return -EINVAL; 5316 } 5317 5318 /* If writing_zero and the spi slot contains a spill of value 0, 5319 * maintain the spill type. 5320 */ 5321 if (writing_zero && *stype == STACK_SPILL && 5322 is_spilled_scalar_reg(&state->stack[spi])) { 5323 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 5324 5325 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 5326 zero_used = true; 5327 continue; 5328 } 5329 } 5330 5331 /* Erase all other spilled pointers. */ 5332 state->stack[spi].spilled_ptr.type = NOT_INIT; 5333 5334 /* Update the slot type. */ 5335 new_type = STACK_MISC; 5336 if (writing_zero && *stype == STACK_ZERO) { 5337 new_type = STACK_ZERO; 5338 zero_used = true; 5339 } 5340 /* If the slot is STACK_INVALID, we check whether it's OK to 5341 * pretend that it will be initialized by this write. The slot 5342 * might not actually be written to, and so if we mark it as 5343 * initialized future reads might leak uninitialized memory. 5344 * For privileged programs, we will accept such reads to slots 5345 * that may or may not be written because, if we're reject 5346 * them, the error would be too confusing. 5347 */ 5348 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 5349 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 5350 insn_idx, i); 5351 return -EINVAL; 5352 } 5353 *stype = new_type; 5354 } 5355 if (zero_used) { 5356 /* backtracking doesn't work for STACK_ZERO yet. */ 5357 err = mark_chain_precision(env, value_regno); 5358 if (err) 5359 return err; 5360 } 5361 return 0; 5362 } 5363 5364 /* When register 'dst_regno' is assigned some values from stack[min_off, 5365 * max_off), we set the register's type according to the types of the 5366 * respective stack slots. If all the stack values are known to be zeros, then 5367 * so is the destination reg. Otherwise, the register is considered to be 5368 * SCALAR. This function does not deal with register filling; the caller must 5369 * ensure that all spilled registers in the stack range have been marked as 5370 * read. 5371 */ 5372 static void mark_reg_stack_read(struct bpf_verifier_env *env, 5373 /* func where src register points to */ 5374 struct bpf_func_state *ptr_state, 5375 int min_off, int max_off, int dst_regno) 5376 { 5377 struct bpf_verifier_state *vstate = env->cur_state; 5378 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5379 int i, slot, spi; 5380 u8 *stype; 5381 int zeros = 0; 5382 5383 for (i = min_off; i < max_off; i++) { 5384 slot = -i - 1; 5385 spi = slot / BPF_REG_SIZE; 5386 mark_stack_slot_scratched(env, spi); 5387 stype = ptr_state->stack[spi].slot_type; 5388 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 5389 break; 5390 zeros++; 5391 } 5392 if (zeros == max_off - min_off) { 5393 /* Any access_size read into register is zero extended, 5394 * so the whole register == const_zero. 5395 */ 5396 __mark_reg_const_zero(env, &state->regs[dst_regno]); 5397 } else { 5398 /* have read misc data from the stack */ 5399 mark_reg_unknown(env, state->regs, dst_regno); 5400 } 5401 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5402 } 5403 5404 /* Read the stack at 'off' and put the results into the register indicated by 5405 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 5406 * spilled reg. 5407 * 5408 * 'dst_regno' can be -1, meaning that the read value is not going to a 5409 * register. 5410 * 5411 * The access is assumed to be within the current stack bounds. 5412 */ 5413 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 5414 /* func where src register points to */ 5415 struct bpf_func_state *reg_state, 5416 int off, int size, int dst_regno) 5417 { 5418 struct bpf_verifier_state *vstate = env->cur_state; 5419 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5420 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 5421 struct bpf_reg_state *reg; 5422 u8 *stype, type; 5423 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 5424 5425 stype = reg_state->stack[spi].slot_type; 5426 reg = ®_state->stack[spi].spilled_ptr; 5427 5428 mark_stack_slot_scratched(env, spi); 5429 check_fastcall_stack_contract(env, state, env->insn_idx, off); 5430 5431 if (is_spilled_reg(®_state->stack[spi])) { 5432 u8 spill_size = 1; 5433 5434 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 5435 spill_size++; 5436 5437 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 5438 if (reg->type != SCALAR_VALUE) { 5439 verbose_linfo(env, env->insn_idx, "; "); 5440 verbose(env, "invalid size of register fill\n"); 5441 return -EACCES; 5442 } 5443 5444 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5445 if (dst_regno < 0) 5446 return 0; 5447 5448 if (size <= spill_size && 5449 bpf_stack_narrow_access_ok(off, size, spill_size)) { 5450 /* The earlier check_reg_arg() has decided the 5451 * subreg_def for this insn. Save it first. 5452 */ 5453 s32 subreg_def = state->regs[dst_regno].subreg_def; 5454 5455 copy_register_state(&state->regs[dst_regno], reg); 5456 state->regs[dst_regno].subreg_def = subreg_def; 5457 5458 /* Break the relation on a narrowing fill. 5459 * coerce_reg_to_size will adjust the boundaries. 5460 */ 5461 if (get_reg_width(reg) > size * BITS_PER_BYTE) 5462 state->regs[dst_regno].id = 0; 5463 } else { 5464 int spill_cnt = 0, zero_cnt = 0; 5465 5466 for (i = 0; i < size; i++) { 5467 type = stype[(slot - i) % BPF_REG_SIZE]; 5468 if (type == STACK_SPILL) { 5469 spill_cnt++; 5470 continue; 5471 } 5472 if (type == STACK_MISC) 5473 continue; 5474 if (type == STACK_ZERO) { 5475 zero_cnt++; 5476 continue; 5477 } 5478 if (type == STACK_INVALID && env->allow_uninit_stack) 5479 continue; 5480 verbose(env, "invalid read from stack off %d+%d size %d\n", 5481 off, i, size); 5482 return -EACCES; 5483 } 5484 5485 if (spill_cnt == size && 5486 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 5487 __mark_reg_const_zero(env, &state->regs[dst_regno]); 5488 /* this IS register fill, so keep insn_flags */ 5489 } else if (zero_cnt == size) { 5490 /* similarly to mark_reg_stack_read(), preserve zeroes */ 5491 __mark_reg_const_zero(env, &state->regs[dst_regno]); 5492 insn_flags = 0; /* not restoring original register state */ 5493 } else { 5494 mark_reg_unknown(env, state->regs, dst_regno); 5495 insn_flags = 0; /* not restoring original register state */ 5496 } 5497 } 5498 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5499 } else if (dst_regno >= 0) { 5500 /* restore register state from stack */ 5501 copy_register_state(&state->regs[dst_regno], reg); 5502 /* mark reg as written since spilled pointer state likely 5503 * has its liveness marks cleared by is_state_visited() 5504 * which resets stack/reg liveness for state transitions 5505 */ 5506 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 5507 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 5508 /* If dst_regno==-1, the caller is asking us whether 5509 * it is acceptable to use this value as a SCALAR_VALUE 5510 * (e.g. for XADD). 5511 * We must not allow unprivileged callers to do that 5512 * with spilled pointers. 5513 */ 5514 verbose(env, "leaking pointer from stack off %d\n", 5515 off); 5516 return -EACCES; 5517 } 5518 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5519 } else { 5520 for (i = 0; i < size; i++) { 5521 type = stype[(slot - i) % BPF_REG_SIZE]; 5522 if (type == STACK_MISC) 5523 continue; 5524 if (type == STACK_ZERO) 5525 continue; 5526 if (type == STACK_INVALID && env->allow_uninit_stack) 5527 continue; 5528 verbose(env, "invalid read from stack off %d+%d size %d\n", 5529 off, i, size); 5530 return -EACCES; 5531 } 5532 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 5533 if (dst_regno >= 0) 5534 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 5535 insn_flags = 0; /* we are not restoring spilled register */ 5536 } 5537 if (insn_flags) 5538 return push_jmp_history(env, env->cur_state, insn_flags, 0); 5539 return 0; 5540 } 5541 5542 enum bpf_access_src { 5543 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 5544 ACCESS_HELPER = 2, /* the access is performed by a helper */ 5545 }; 5546 5547 static int check_stack_range_initialized(struct bpf_verifier_env *env, 5548 int regno, int off, int access_size, 5549 bool zero_size_allowed, 5550 enum bpf_access_type type, 5551 struct bpf_call_arg_meta *meta); 5552 5553 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 5554 { 5555 return cur_regs(env) + regno; 5556 } 5557 5558 /* Read the stack at 'ptr_regno + off' and put the result into the register 5559 * 'dst_regno'. 5560 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 5561 * but not its variable offset. 5562 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 5563 * 5564 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 5565 * filling registers (i.e. reads of spilled register cannot be detected when 5566 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 5567 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 5568 * offset; for a fixed offset check_stack_read_fixed_off should be used 5569 * instead. 5570 */ 5571 static int check_stack_read_var_off(struct bpf_verifier_env *env, 5572 int ptr_regno, int off, int size, int dst_regno) 5573 { 5574 /* The state of the source register. */ 5575 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5576 struct bpf_func_state *ptr_state = func(env, reg); 5577 int err; 5578 int min_off, max_off; 5579 5580 /* Note that we pass a NULL meta, so raw access will not be permitted. 5581 */ 5582 err = check_stack_range_initialized(env, ptr_regno, off, size, 5583 false, BPF_READ, NULL); 5584 if (err) 5585 return err; 5586 5587 min_off = reg->smin_value + off; 5588 max_off = reg->smax_value + off; 5589 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 5590 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 5591 return 0; 5592 } 5593 5594 /* check_stack_read dispatches to check_stack_read_fixed_off or 5595 * check_stack_read_var_off. 5596 * 5597 * The caller must ensure that the offset falls within the allocated stack 5598 * bounds. 5599 * 5600 * 'dst_regno' is a register which will receive the value from the stack. It 5601 * can be -1, meaning that the read value is not going to a register. 5602 */ 5603 static int check_stack_read(struct bpf_verifier_env *env, 5604 int ptr_regno, int off, int size, 5605 int dst_regno) 5606 { 5607 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5608 struct bpf_func_state *state = func(env, reg); 5609 int err; 5610 /* Some accesses are only permitted with a static offset. */ 5611 bool var_off = !tnum_is_const(reg->var_off); 5612 5613 /* The offset is required to be static when reads don't go to a 5614 * register, in order to not leak pointers (see 5615 * check_stack_read_fixed_off). 5616 */ 5617 if (dst_regno < 0 && var_off) { 5618 char tn_buf[48]; 5619 5620 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5621 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 5622 tn_buf, off, size); 5623 return -EACCES; 5624 } 5625 /* Variable offset is prohibited for unprivileged mode for simplicity 5626 * since it requires corresponding support in Spectre masking for stack 5627 * ALU. See also retrieve_ptr_limit(). The check in 5628 * check_stack_access_for_ptr_arithmetic() called by 5629 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 5630 * with variable offsets, therefore no check is required here. Further, 5631 * just checking it here would be insufficient as speculative stack 5632 * writes could still lead to unsafe speculative behaviour. 5633 */ 5634 if (!var_off) { 5635 off += reg->var_off.value; 5636 err = check_stack_read_fixed_off(env, state, off, size, 5637 dst_regno); 5638 } else { 5639 /* Variable offset stack reads need more conservative handling 5640 * than fixed offset ones. Note that dst_regno >= 0 on this 5641 * branch. 5642 */ 5643 err = check_stack_read_var_off(env, ptr_regno, off, size, 5644 dst_regno); 5645 } 5646 return err; 5647 } 5648 5649 5650 /* check_stack_write dispatches to check_stack_write_fixed_off or 5651 * check_stack_write_var_off. 5652 * 5653 * 'ptr_regno' is the register used as a pointer into the stack. 5654 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5655 * 'value_regno' is the register whose value we're writing to the stack. It can 5656 * be -1, meaning that we're not writing from a register. 5657 * 5658 * The caller must ensure that the offset falls within the maximum stack size. 5659 */ 5660 static int check_stack_write(struct bpf_verifier_env *env, 5661 int ptr_regno, int off, int size, 5662 int value_regno, int insn_idx) 5663 { 5664 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5665 struct bpf_func_state *state = func(env, reg); 5666 int err; 5667 5668 if (tnum_is_const(reg->var_off)) { 5669 off += reg->var_off.value; 5670 err = check_stack_write_fixed_off(env, state, off, size, 5671 value_regno, insn_idx); 5672 } else { 5673 /* Variable offset stack reads need more conservative handling 5674 * than fixed offset ones. 5675 */ 5676 err = check_stack_write_var_off(env, state, 5677 ptr_regno, off, size, 5678 value_regno, insn_idx); 5679 } 5680 return err; 5681 } 5682 5683 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5684 int off, int size, enum bpf_access_type type) 5685 { 5686 struct bpf_reg_state *regs = cur_regs(env); 5687 struct bpf_map *map = regs[regno].map_ptr; 5688 u32 cap = bpf_map_flags_to_cap(map); 5689 5690 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5691 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5692 map->value_size, off, size); 5693 return -EACCES; 5694 } 5695 5696 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5697 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5698 map->value_size, off, size); 5699 return -EACCES; 5700 } 5701 5702 return 0; 5703 } 5704 5705 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5706 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5707 int off, int size, u32 mem_size, 5708 bool zero_size_allowed) 5709 { 5710 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5711 struct bpf_reg_state *reg; 5712 5713 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5714 return 0; 5715 5716 reg = &cur_regs(env)[regno]; 5717 switch (reg->type) { 5718 case PTR_TO_MAP_KEY: 5719 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5720 mem_size, off, size); 5721 break; 5722 case PTR_TO_MAP_VALUE: 5723 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5724 mem_size, off, size); 5725 break; 5726 case PTR_TO_PACKET: 5727 case PTR_TO_PACKET_META: 5728 case PTR_TO_PACKET_END: 5729 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5730 off, size, regno, reg->id, off, mem_size); 5731 break; 5732 case PTR_TO_MEM: 5733 default: 5734 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5735 mem_size, off, size); 5736 } 5737 5738 return -EACCES; 5739 } 5740 5741 /* check read/write into a memory region with possible variable offset */ 5742 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5743 int off, int size, u32 mem_size, 5744 bool zero_size_allowed) 5745 { 5746 struct bpf_verifier_state *vstate = env->cur_state; 5747 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5748 struct bpf_reg_state *reg = &state->regs[regno]; 5749 int err; 5750 5751 /* We may have adjusted the register pointing to memory region, so we 5752 * need to try adding each of min_value and max_value to off 5753 * to make sure our theoretical access will be safe. 5754 * 5755 * The minimum value is only important with signed 5756 * comparisons where we can't assume the floor of a 5757 * value is 0. If we are using signed variables for our 5758 * index'es we need to make sure that whatever we use 5759 * will have a set floor within our range. 5760 */ 5761 if (reg->smin_value < 0 && 5762 (reg->smin_value == S64_MIN || 5763 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5764 reg->smin_value + off < 0)) { 5765 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5766 regno); 5767 return -EACCES; 5768 } 5769 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5770 mem_size, zero_size_allowed); 5771 if (err) { 5772 verbose(env, "R%d min value is outside of the allowed memory range\n", 5773 regno); 5774 return err; 5775 } 5776 5777 /* If we haven't set a max value then we need to bail since we can't be 5778 * sure we won't do bad things. 5779 * If reg->umax_value + off could overflow, treat that as unbounded too. 5780 */ 5781 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5782 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5783 regno); 5784 return -EACCES; 5785 } 5786 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5787 mem_size, zero_size_allowed); 5788 if (err) { 5789 verbose(env, "R%d max value is outside of the allowed memory range\n", 5790 regno); 5791 return err; 5792 } 5793 5794 return 0; 5795 } 5796 5797 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5798 const struct bpf_reg_state *reg, int regno, 5799 bool fixed_off_ok) 5800 { 5801 /* Access to this pointer-typed register or passing it to a helper 5802 * is only allowed in its original, unmodified form. 5803 */ 5804 5805 if (reg->off < 0) { 5806 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5807 reg_type_str(env, reg->type), regno, reg->off); 5808 return -EACCES; 5809 } 5810 5811 if (!fixed_off_ok && reg->off) { 5812 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5813 reg_type_str(env, reg->type), regno, reg->off); 5814 return -EACCES; 5815 } 5816 5817 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5818 char tn_buf[48]; 5819 5820 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5821 verbose(env, "variable %s access var_off=%s disallowed\n", 5822 reg_type_str(env, reg->type), tn_buf); 5823 return -EACCES; 5824 } 5825 5826 return 0; 5827 } 5828 5829 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5830 const struct bpf_reg_state *reg, int regno) 5831 { 5832 return __check_ptr_off_reg(env, reg, regno, false); 5833 } 5834 5835 static int map_kptr_match_type(struct bpf_verifier_env *env, 5836 struct btf_field *kptr_field, 5837 struct bpf_reg_state *reg, u32 regno) 5838 { 5839 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5840 int perm_flags; 5841 const char *reg_name = ""; 5842 5843 if (btf_is_kernel(reg->btf)) { 5844 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5845 5846 /* Only unreferenced case accepts untrusted pointers */ 5847 if (kptr_field->type == BPF_KPTR_UNREF) 5848 perm_flags |= PTR_UNTRUSTED; 5849 } else { 5850 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5851 if (kptr_field->type == BPF_KPTR_PERCPU) 5852 perm_flags |= MEM_PERCPU; 5853 } 5854 5855 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5856 goto bad_type; 5857 5858 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5859 reg_name = btf_type_name(reg->btf, reg->btf_id); 5860 5861 /* For ref_ptr case, release function check should ensure we get one 5862 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5863 * normal store of unreferenced kptr, we must ensure var_off is zero. 5864 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5865 * reg->off and reg->ref_obj_id are not needed here. 5866 */ 5867 if (__check_ptr_off_reg(env, reg, regno, true)) 5868 return -EACCES; 5869 5870 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5871 * we also need to take into account the reg->off. 5872 * 5873 * We want to support cases like: 5874 * 5875 * struct foo { 5876 * struct bar br; 5877 * struct baz bz; 5878 * }; 5879 * 5880 * struct foo *v; 5881 * v = func(); // PTR_TO_BTF_ID 5882 * val->foo = v; // reg->off is zero, btf and btf_id match type 5883 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5884 * // first member type of struct after comparison fails 5885 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5886 * // to match type 5887 * 5888 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5889 * is zero. We must also ensure that btf_struct_ids_match does not walk 5890 * the struct to match type against first member of struct, i.e. reject 5891 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5892 * strict mode to true for type match. 5893 */ 5894 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5895 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5896 kptr_field->type != BPF_KPTR_UNREF)) 5897 goto bad_type; 5898 return 0; 5899 bad_type: 5900 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5901 reg_type_str(env, reg->type), reg_name); 5902 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5903 if (kptr_field->type == BPF_KPTR_UNREF) 5904 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5905 targ_name); 5906 else 5907 verbose(env, "\n"); 5908 return -EINVAL; 5909 } 5910 5911 static bool in_sleepable(struct bpf_verifier_env *env) 5912 { 5913 return env->prog->sleepable || 5914 (env->cur_state && env->cur_state->in_sleepable); 5915 } 5916 5917 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5918 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5919 */ 5920 static bool in_rcu_cs(struct bpf_verifier_env *env) 5921 { 5922 return env->cur_state->active_rcu_lock || 5923 env->cur_state->active_locks || 5924 !in_sleepable(env); 5925 } 5926 5927 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5928 BTF_SET_START(rcu_protected_types) 5929 #ifdef CONFIG_NET 5930 BTF_ID(struct, prog_test_ref_kfunc) 5931 #endif 5932 #ifdef CONFIG_CGROUPS 5933 BTF_ID(struct, cgroup) 5934 #endif 5935 #ifdef CONFIG_BPF_JIT 5936 BTF_ID(struct, bpf_cpumask) 5937 #endif 5938 BTF_ID(struct, task_struct) 5939 #ifdef CONFIG_CRYPTO 5940 BTF_ID(struct, bpf_crypto_ctx) 5941 #endif 5942 BTF_SET_END(rcu_protected_types) 5943 5944 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5945 { 5946 if (!btf_is_kernel(btf)) 5947 return true; 5948 return btf_id_set_contains(&rcu_protected_types, btf_id); 5949 } 5950 5951 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5952 { 5953 struct btf_struct_meta *meta; 5954 5955 if (btf_is_kernel(kptr_field->kptr.btf)) 5956 return NULL; 5957 5958 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5959 kptr_field->kptr.btf_id); 5960 5961 return meta ? meta->record : NULL; 5962 } 5963 5964 static bool rcu_safe_kptr(const struct btf_field *field) 5965 { 5966 const struct btf_field_kptr *kptr = &field->kptr; 5967 5968 return field->type == BPF_KPTR_PERCPU || 5969 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5970 } 5971 5972 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5973 { 5974 struct btf_record *rec; 5975 u32 ret; 5976 5977 ret = PTR_MAYBE_NULL; 5978 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5979 ret |= MEM_RCU; 5980 if (kptr_field->type == BPF_KPTR_PERCPU) 5981 ret |= MEM_PERCPU; 5982 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5983 ret |= MEM_ALLOC; 5984 5985 rec = kptr_pointee_btf_record(kptr_field); 5986 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5987 ret |= NON_OWN_REF; 5988 } else { 5989 ret |= PTR_UNTRUSTED; 5990 } 5991 5992 return ret; 5993 } 5994 5995 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 5996 struct btf_field *field) 5997 { 5998 struct bpf_reg_state *reg; 5999 const struct btf_type *t; 6000 6001 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 6002 mark_reg_known_zero(env, cur_regs(env), regno); 6003 reg = reg_state(env, regno); 6004 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 6005 reg->mem_size = t->size; 6006 reg->id = ++env->id_gen; 6007 6008 return 0; 6009 } 6010 6011 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 6012 int value_regno, int insn_idx, 6013 struct btf_field *kptr_field) 6014 { 6015 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 6016 int class = BPF_CLASS(insn->code); 6017 struct bpf_reg_state *val_reg; 6018 int ret; 6019 6020 /* Things we already checked for in check_map_access and caller: 6021 * - Reject cases where variable offset may touch kptr 6022 * - size of access (must be BPF_DW) 6023 * - tnum_is_const(reg->var_off) 6024 * - kptr_field->offset == off + reg->var_off.value 6025 */ 6026 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 6027 if (BPF_MODE(insn->code) != BPF_MEM) { 6028 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 6029 return -EACCES; 6030 } 6031 6032 /* We only allow loading referenced kptr, since it will be marked as 6033 * untrusted, similar to unreferenced kptr. 6034 */ 6035 if (class != BPF_LDX && 6036 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 6037 verbose(env, "store to referenced kptr disallowed\n"); 6038 return -EACCES; 6039 } 6040 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 6041 verbose(env, "store to uptr disallowed\n"); 6042 return -EACCES; 6043 } 6044 6045 if (class == BPF_LDX) { 6046 if (kptr_field->type == BPF_UPTR) 6047 return mark_uptr_ld_reg(env, value_regno, kptr_field); 6048 6049 /* We can simply mark the value_regno receiving the pointer 6050 * value from map as PTR_TO_BTF_ID, with the correct type. 6051 */ 6052 ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, 6053 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 6054 btf_ld_kptr_type(env, kptr_field)); 6055 if (ret < 0) 6056 return ret; 6057 } else if (class == BPF_STX) { 6058 val_reg = reg_state(env, value_regno); 6059 if (!register_is_null(val_reg) && 6060 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 6061 return -EACCES; 6062 } else if (class == BPF_ST) { 6063 if (insn->imm) { 6064 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 6065 kptr_field->offset); 6066 return -EACCES; 6067 } 6068 } else { 6069 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 6070 return -EACCES; 6071 } 6072 return 0; 6073 } 6074 6075 /* check read/write into a map element with possible variable offset */ 6076 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 6077 int off, int size, bool zero_size_allowed, 6078 enum bpf_access_src src) 6079 { 6080 struct bpf_verifier_state *vstate = env->cur_state; 6081 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6082 struct bpf_reg_state *reg = &state->regs[regno]; 6083 struct bpf_map *map = reg->map_ptr; 6084 struct btf_record *rec; 6085 int err, i; 6086 6087 err = check_mem_region_access(env, regno, off, size, map->value_size, 6088 zero_size_allowed); 6089 if (err) 6090 return err; 6091 6092 if (IS_ERR_OR_NULL(map->record)) 6093 return 0; 6094 rec = map->record; 6095 for (i = 0; i < rec->cnt; i++) { 6096 struct btf_field *field = &rec->fields[i]; 6097 u32 p = field->offset; 6098 6099 /* If any part of a field can be touched by load/store, reject 6100 * this program. To check that [x1, x2) overlaps with [y1, y2), 6101 * it is sufficient to check x1 < y2 && y1 < x2. 6102 */ 6103 if (reg->smin_value + off < p + field->size && 6104 p < reg->umax_value + off + size) { 6105 switch (field->type) { 6106 case BPF_KPTR_UNREF: 6107 case BPF_KPTR_REF: 6108 case BPF_KPTR_PERCPU: 6109 case BPF_UPTR: 6110 if (src != ACCESS_DIRECT) { 6111 verbose(env, "%s cannot be accessed indirectly by helper\n", 6112 btf_field_type_name(field->type)); 6113 return -EACCES; 6114 } 6115 if (!tnum_is_const(reg->var_off)) { 6116 verbose(env, "%s access cannot have variable offset\n", 6117 btf_field_type_name(field->type)); 6118 return -EACCES; 6119 } 6120 if (p != off + reg->var_off.value) { 6121 verbose(env, "%s access misaligned expected=%u off=%llu\n", 6122 btf_field_type_name(field->type), 6123 p, off + reg->var_off.value); 6124 return -EACCES; 6125 } 6126 if (size != bpf_size_to_bytes(BPF_DW)) { 6127 verbose(env, "%s access size must be BPF_DW\n", 6128 btf_field_type_name(field->type)); 6129 return -EACCES; 6130 } 6131 break; 6132 default: 6133 verbose(env, "%s cannot be accessed directly by load/store\n", 6134 btf_field_type_name(field->type)); 6135 return -EACCES; 6136 } 6137 } 6138 } 6139 return 0; 6140 } 6141 6142 #define MAX_PACKET_OFF 0xffff 6143 6144 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 6145 const struct bpf_call_arg_meta *meta, 6146 enum bpf_access_type t) 6147 { 6148 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 6149 6150 switch (prog_type) { 6151 /* Program types only with direct read access go here! */ 6152 case BPF_PROG_TYPE_LWT_IN: 6153 case BPF_PROG_TYPE_LWT_OUT: 6154 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 6155 case BPF_PROG_TYPE_SK_REUSEPORT: 6156 case BPF_PROG_TYPE_FLOW_DISSECTOR: 6157 case BPF_PROG_TYPE_CGROUP_SKB: 6158 if (t == BPF_WRITE) 6159 return false; 6160 fallthrough; 6161 6162 /* Program types with direct read + write access go here! */ 6163 case BPF_PROG_TYPE_SCHED_CLS: 6164 case BPF_PROG_TYPE_SCHED_ACT: 6165 case BPF_PROG_TYPE_XDP: 6166 case BPF_PROG_TYPE_LWT_XMIT: 6167 case BPF_PROG_TYPE_SK_SKB: 6168 case BPF_PROG_TYPE_SK_MSG: 6169 if (meta) 6170 return meta->pkt_access; 6171 6172 env->seen_direct_write = true; 6173 return true; 6174 6175 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 6176 if (t == BPF_WRITE) 6177 env->seen_direct_write = true; 6178 6179 return true; 6180 6181 default: 6182 return false; 6183 } 6184 } 6185 6186 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 6187 int size, bool zero_size_allowed) 6188 { 6189 struct bpf_reg_state *regs = cur_regs(env); 6190 struct bpf_reg_state *reg = ®s[regno]; 6191 int err; 6192 6193 /* We may have added a variable offset to the packet pointer; but any 6194 * reg->range we have comes after that. We are only checking the fixed 6195 * offset. 6196 */ 6197 6198 /* We don't allow negative numbers, because we aren't tracking enough 6199 * detail to prove they're safe. 6200 */ 6201 if (reg->smin_value < 0) { 6202 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 6203 regno); 6204 return -EACCES; 6205 } 6206 6207 err = reg->range < 0 ? -EINVAL : 6208 __check_mem_access(env, regno, off, size, reg->range, 6209 zero_size_allowed); 6210 if (err) { 6211 verbose(env, "R%d offset is outside of the packet\n", regno); 6212 return err; 6213 } 6214 6215 /* __check_mem_access has made sure "off + size - 1" is within u16. 6216 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 6217 * otherwise find_good_pkt_pointers would have refused to set range info 6218 * that __check_mem_access would have rejected this pkt access. 6219 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 6220 */ 6221 env->prog->aux->max_pkt_offset = 6222 max_t(u32, env->prog->aux->max_pkt_offset, 6223 off + reg->umax_value + size - 1); 6224 6225 return err; 6226 } 6227 6228 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 6229 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 6230 enum bpf_access_type t, struct bpf_insn_access_aux *info) 6231 { 6232 if (env->ops->is_valid_access && 6233 env->ops->is_valid_access(off, size, t, env->prog, info)) { 6234 /* A non zero info.ctx_field_size indicates that this field is a 6235 * candidate for later verifier transformation to load the whole 6236 * field and then apply a mask when accessed with a narrower 6237 * access than actual ctx access size. A zero info.ctx_field_size 6238 * will only allow for whole field access and rejects any other 6239 * type of narrower access. 6240 */ 6241 if (base_type(info->reg_type) == PTR_TO_BTF_ID) { 6242 if (info->ref_obj_id && 6243 !find_reference_state(env->cur_state, info->ref_obj_id)) { 6244 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n", 6245 off); 6246 return -EACCES; 6247 } 6248 } else { 6249 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size; 6250 } 6251 /* remember the offset of last byte accessed in ctx */ 6252 if (env->prog->aux->max_ctx_offset < off + size) 6253 env->prog->aux->max_ctx_offset = off + size; 6254 return 0; 6255 } 6256 6257 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 6258 return -EACCES; 6259 } 6260 6261 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 6262 int size) 6263 { 6264 if (size < 0 || off < 0 || 6265 (u64)off + size > sizeof(struct bpf_flow_keys)) { 6266 verbose(env, "invalid access to flow keys off=%d size=%d\n", 6267 off, size); 6268 return -EACCES; 6269 } 6270 return 0; 6271 } 6272 6273 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 6274 u32 regno, int off, int size, 6275 enum bpf_access_type t) 6276 { 6277 struct bpf_reg_state *regs = cur_regs(env); 6278 struct bpf_reg_state *reg = ®s[regno]; 6279 struct bpf_insn_access_aux info = {}; 6280 bool valid; 6281 6282 if (reg->smin_value < 0) { 6283 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 6284 regno); 6285 return -EACCES; 6286 } 6287 6288 switch (reg->type) { 6289 case PTR_TO_SOCK_COMMON: 6290 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 6291 break; 6292 case PTR_TO_SOCKET: 6293 valid = bpf_sock_is_valid_access(off, size, t, &info); 6294 break; 6295 case PTR_TO_TCP_SOCK: 6296 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 6297 break; 6298 case PTR_TO_XDP_SOCK: 6299 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 6300 break; 6301 default: 6302 valid = false; 6303 } 6304 6305 6306 if (valid) { 6307 env->insn_aux_data[insn_idx].ctx_field_size = 6308 info.ctx_field_size; 6309 return 0; 6310 } 6311 6312 verbose(env, "R%d invalid %s access off=%d size=%d\n", 6313 regno, reg_type_str(env, reg->type), off, size); 6314 6315 return -EACCES; 6316 } 6317 6318 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 6319 { 6320 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 6321 } 6322 6323 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 6324 { 6325 const struct bpf_reg_state *reg = reg_state(env, regno); 6326 6327 return reg->type == PTR_TO_CTX; 6328 } 6329 6330 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 6331 { 6332 const struct bpf_reg_state *reg = reg_state(env, regno); 6333 6334 return type_is_sk_pointer(reg->type); 6335 } 6336 6337 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 6338 { 6339 const struct bpf_reg_state *reg = reg_state(env, regno); 6340 6341 return type_is_pkt_pointer(reg->type); 6342 } 6343 6344 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 6345 { 6346 const struct bpf_reg_state *reg = reg_state(env, regno); 6347 6348 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 6349 return reg->type == PTR_TO_FLOW_KEYS; 6350 } 6351 6352 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 6353 { 6354 const struct bpf_reg_state *reg = reg_state(env, regno); 6355 6356 return reg->type == PTR_TO_ARENA; 6357 } 6358 6359 /* Return false if @regno contains a pointer whose type isn't supported for 6360 * atomic instruction @insn. 6361 */ 6362 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno, 6363 struct bpf_insn *insn) 6364 { 6365 if (is_ctx_reg(env, regno)) 6366 return false; 6367 if (is_pkt_reg(env, regno)) 6368 return false; 6369 if (is_flow_key_reg(env, regno)) 6370 return false; 6371 if (is_sk_reg(env, regno)) 6372 return false; 6373 if (is_arena_reg(env, regno)) 6374 return bpf_jit_supports_insn(insn, true); 6375 6376 return true; 6377 } 6378 6379 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 6380 #ifdef CONFIG_NET 6381 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 6382 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 6383 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 6384 #endif 6385 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 6386 }; 6387 6388 static bool is_trusted_reg(const struct bpf_reg_state *reg) 6389 { 6390 /* A referenced register is always trusted. */ 6391 if (reg->ref_obj_id) 6392 return true; 6393 6394 /* Types listed in the reg2btf_ids are always trusted */ 6395 if (reg2btf_ids[base_type(reg->type)] && 6396 !bpf_type_has_unsafe_modifiers(reg->type)) 6397 return true; 6398 6399 /* If a register is not referenced, it is trusted if it has the 6400 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 6401 * other type modifiers may be safe, but we elect to take an opt-in 6402 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 6403 * not. 6404 * 6405 * Eventually, we should make PTR_TRUSTED the single source of truth 6406 * for whether a register is trusted. 6407 */ 6408 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 6409 !bpf_type_has_unsafe_modifiers(reg->type); 6410 } 6411 6412 static bool is_rcu_reg(const struct bpf_reg_state *reg) 6413 { 6414 return reg->type & MEM_RCU; 6415 } 6416 6417 static void clear_trusted_flags(enum bpf_type_flag *flag) 6418 { 6419 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 6420 } 6421 6422 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 6423 const struct bpf_reg_state *reg, 6424 int off, int size, bool strict) 6425 { 6426 struct tnum reg_off; 6427 int ip_align; 6428 6429 /* Byte size accesses are always allowed. */ 6430 if (!strict || size == 1) 6431 return 0; 6432 6433 /* For platforms that do not have a Kconfig enabling 6434 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 6435 * NET_IP_ALIGN is universally set to '2'. And on platforms 6436 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 6437 * to this code only in strict mode where we want to emulate 6438 * the NET_IP_ALIGN==2 checking. Therefore use an 6439 * unconditional IP align value of '2'. 6440 */ 6441 ip_align = 2; 6442 6443 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 6444 if (!tnum_is_aligned(reg_off, size)) { 6445 char tn_buf[48]; 6446 6447 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6448 verbose(env, 6449 "misaligned packet access off %d+%s+%d+%d size %d\n", 6450 ip_align, tn_buf, reg->off, off, size); 6451 return -EACCES; 6452 } 6453 6454 return 0; 6455 } 6456 6457 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 6458 const struct bpf_reg_state *reg, 6459 const char *pointer_desc, 6460 int off, int size, bool strict) 6461 { 6462 struct tnum reg_off; 6463 6464 /* Byte size accesses are always allowed. */ 6465 if (!strict || size == 1) 6466 return 0; 6467 6468 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 6469 if (!tnum_is_aligned(reg_off, size)) { 6470 char tn_buf[48]; 6471 6472 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6473 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 6474 pointer_desc, tn_buf, reg->off, off, size); 6475 return -EACCES; 6476 } 6477 6478 return 0; 6479 } 6480 6481 static int check_ptr_alignment(struct bpf_verifier_env *env, 6482 const struct bpf_reg_state *reg, int off, 6483 int size, bool strict_alignment_once) 6484 { 6485 bool strict = env->strict_alignment || strict_alignment_once; 6486 const char *pointer_desc = ""; 6487 6488 switch (reg->type) { 6489 case PTR_TO_PACKET: 6490 case PTR_TO_PACKET_META: 6491 /* Special case, because of NET_IP_ALIGN. Given metadata sits 6492 * right in front, treat it the very same way. 6493 */ 6494 return check_pkt_ptr_alignment(env, reg, off, size, strict); 6495 case PTR_TO_FLOW_KEYS: 6496 pointer_desc = "flow keys "; 6497 break; 6498 case PTR_TO_MAP_KEY: 6499 pointer_desc = "key "; 6500 break; 6501 case PTR_TO_MAP_VALUE: 6502 pointer_desc = "value "; 6503 break; 6504 case PTR_TO_CTX: 6505 pointer_desc = "context "; 6506 break; 6507 case PTR_TO_STACK: 6508 pointer_desc = "stack "; 6509 /* The stack spill tracking logic in check_stack_write_fixed_off() 6510 * and check_stack_read_fixed_off() relies on stack accesses being 6511 * aligned. 6512 */ 6513 strict = true; 6514 break; 6515 case PTR_TO_SOCKET: 6516 pointer_desc = "sock "; 6517 break; 6518 case PTR_TO_SOCK_COMMON: 6519 pointer_desc = "sock_common "; 6520 break; 6521 case PTR_TO_TCP_SOCK: 6522 pointer_desc = "tcp_sock "; 6523 break; 6524 case PTR_TO_XDP_SOCK: 6525 pointer_desc = "xdp_sock "; 6526 break; 6527 case PTR_TO_ARENA: 6528 return 0; 6529 default: 6530 break; 6531 } 6532 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 6533 strict); 6534 } 6535 6536 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 6537 { 6538 if (!bpf_jit_supports_private_stack()) 6539 return NO_PRIV_STACK; 6540 6541 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 6542 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 6543 * explicitly. 6544 */ 6545 switch (prog->type) { 6546 case BPF_PROG_TYPE_KPROBE: 6547 case BPF_PROG_TYPE_TRACEPOINT: 6548 case BPF_PROG_TYPE_PERF_EVENT: 6549 case BPF_PROG_TYPE_RAW_TRACEPOINT: 6550 return PRIV_STACK_ADAPTIVE; 6551 case BPF_PROG_TYPE_TRACING: 6552 case BPF_PROG_TYPE_LSM: 6553 case BPF_PROG_TYPE_STRUCT_OPS: 6554 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 6555 return PRIV_STACK_ADAPTIVE; 6556 fallthrough; 6557 default: 6558 break; 6559 } 6560 6561 return NO_PRIV_STACK; 6562 } 6563 6564 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 6565 { 6566 if (env->prog->jit_requested) 6567 return round_up(stack_depth, 16); 6568 6569 /* round up to 32-bytes, since this is granularity 6570 * of interpreter stack size 6571 */ 6572 return round_up(max_t(u32, stack_depth, 1), 32); 6573 } 6574 6575 /* starting from main bpf function walk all instructions of the function 6576 * and recursively walk all callees that given function can call. 6577 * Ignore jump and exit insns. 6578 * Since recursion is prevented by check_cfg() this algorithm 6579 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 6580 */ 6581 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 6582 bool priv_stack_supported) 6583 { 6584 struct bpf_subprog_info *subprog = env->subprog_info; 6585 struct bpf_insn *insn = env->prog->insnsi; 6586 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 6587 bool tail_call_reachable = false; 6588 int ret_insn[MAX_CALL_FRAMES]; 6589 int ret_prog[MAX_CALL_FRAMES]; 6590 int j; 6591 6592 i = subprog[idx].start; 6593 if (!priv_stack_supported) 6594 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 6595 process_func: 6596 /* protect against potential stack overflow that might happen when 6597 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 6598 * depth for such case down to 256 so that the worst case scenario 6599 * would result in 8k stack size (32 which is tailcall limit * 256 = 6600 * 8k). 6601 * 6602 * To get the idea what might happen, see an example: 6603 * func1 -> sub rsp, 128 6604 * subfunc1 -> sub rsp, 256 6605 * tailcall1 -> add rsp, 256 6606 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 6607 * subfunc2 -> sub rsp, 64 6608 * subfunc22 -> sub rsp, 128 6609 * tailcall2 -> add rsp, 128 6610 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 6611 * 6612 * tailcall will unwind the current stack frame but it will not get rid 6613 * of caller's stack as shown on the example above. 6614 */ 6615 if (idx && subprog[idx].has_tail_call && depth >= 256) { 6616 verbose(env, 6617 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 6618 depth); 6619 return -EACCES; 6620 } 6621 6622 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 6623 if (priv_stack_supported) { 6624 /* Request private stack support only if the subprog stack 6625 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 6626 * avoid jit penalty if the stack usage is small. 6627 */ 6628 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 6629 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 6630 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 6631 } 6632 6633 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 6634 if (subprog_depth > MAX_BPF_STACK) { 6635 verbose(env, "stack size of subprog %d is %d. Too large\n", 6636 idx, subprog_depth); 6637 return -EACCES; 6638 } 6639 } else { 6640 depth += subprog_depth; 6641 if (depth > MAX_BPF_STACK) { 6642 verbose(env, "combined stack size of %d calls is %d. Too large\n", 6643 frame + 1, depth); 6644 return -EACCES; 6645 } 6646 } 6647 continue_func: 6648 subprog_end = subprog[idx + 1].start; 6649 for (; i < subprog_end; i++) { 6650 int next_insn, sidx; 6651 6652 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 6653 bool err = false; 6654 6655 if (!is_bpf_throw_kfunc(insn + i)) 6656 continue; 6657 if (subprog[idx].is_cb) 6658 err = true; 6659 for (int c = 0; c < frame && !err; c++) { 6660 if (subprog[ret_prog[c]].is_cb) { 6661 err = true; 6662 break; 6663 } 6664 } 6665 if (!err) 6666 continue; 6667 verbose(env, 6668 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 6669 i, idx); 6670 return -EINVAL; 6671 } 6672 6673 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 6674 continue; 6675 /* remember insn and function to return to */ 6676 ret_insn[frame] = i + 1; 6677 ret_prog[frame] = idx; 6678 6679 /* find the callee */ 6680 next_insn = i + insn[i].imm + 1; 6681 sidx = find_subprog(env, next_insn); 6682 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn)) 6683 return -EFAULT; 6684 if (subprog[sidx].is_async_cb) { 6685 if (subprog[sidx].has_tail_call) { 6686 verifier_bug(env, "subprog has tail_call and async cb"); 6687 return -EFAULT; 6688 } 6689 /* async callbacks don't increase bpf prog stack size unless called directly */ 6690 if (!bpf_pseudo_call(insn + i)) 6691 continue; 6692 if (subprog[sidx].is_exception_cb) { 6693 verbose(env, "insn %d cannot call exception cb directly", i); 6694 return -EINVAL; 6695 } 6696 } 6697 i = next_insn; 6698 idx = sidx; 6699 if (!priv_stack_supported) 6700 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 6701 6702 if (subprog[idx].has_tail_call) 6703 tail_call_reachable = true; 6704 6705 frame++; 6706 if (frame >= MAX_CALL_FRAMES) { 6707 verbose(env, "the call stack of %d frames is too deep !\n", 6708 frame); 6709 return -E2BIG; 6710 } 6711 goto process_func; 6712 } 6713 /* if tail call got detected across bpf2bpf calls then mark each of the 6714 * currently present subprog frames as tail call reachable subprogs; 6715 * this info will be utilized by JIT so that we will be preserving the 6716 * tail call counter throughout bpf2bpf calls combined with tailcalls 6717 */ 6718 if (tail_call_reachable) 6719 for (j = 0; j < frame; j++) { 6720 if (subprog[ret_prog[j]].is_exception_cb) { 6721 verbose(env, "cannot tail call within exception cb\n"); 6722 return -EINVAL; 6723 } 6724 subprog[ret_prog[j]].tail_call_reachable = true; 6725 } 6726 if (subprog[0].tail_call_reachable) 6727 env->prog->aux->tail_call_reachable = true; 6728 6729 /* end of for() loop means the last insn of the 'subprog' 6730 * was reached. Doesn't matter whether it was JA or EXIT 6731 */ 6732 if (frame == 0) 6733 return 0; 6734 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 6735 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 6736 frame--; 6737 i = ret_insn[frame]; 6738 idx = ret_prog[frame]; 6739 goto continue_func; 6740 } 6741 6742 static int check_max_stack_depth(struct bpf_verifier_env *env) 6743 { 6744 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 6745 struct bpf_subprog_info *si = env->subprog_info; 6746 bool priv_stack_supported; 6747 int ret; 6748 6749 for (int i = 0; i < env->subprog_cnt; i++) { 6750 if (si[i].has_tail_call) { 6751 priv_stack_mode = NO_PRIV_STACK; 6752 break; 6753 } 6754 } 6755 6756 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 6757 priv_stack_mode = bpf_enable_priv_stack(env->prog); 6758 6759 /* All async_cb subprogs use normal kernel stack. If a particular 6760 * subprog appears in both main prog and async_cb subtree, that 6761 * subprog will use normal kernel stack to avoid potential nesting. 6762 * The reverse subprog traversal ensures when main prog subtree is 6763 * checked, the subprogs appearing in async_cb subtrees are already 6764 * marked as using normal kernel stack, so stack size checking can 6765 * be done properly. 6766 */ 6767 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 6768 if (!i || si[i].is_async_cb) { 6769 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 6770 ret = check_max_stack_depth_subprog(env, i, priv_stack_supported); 6771 if (ret < 0) 6772 return ret; 6773 } 6774 } 6775 6776 for (int i = 0; i < env->subprog_cnt; i++) { 6777 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 6778 env->prog->aux->jits_use_priv_stack = true; 6779 break; 6780 } 6781 } 6782 6783 return 0; 6784 } 6785 6786 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6787 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6788 const struct bpf_insn *insn, int idx) 6789 { 6790 int start = idx + insn->imm + 1, subprog; 6791 6792 subprog = find_subprog(env, start); 6793 if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start)) 6794 return -EFAULT; 6795 return env->subprog_info[subprog].stack_depth; 6796 } 6797 #endif 6798 6799 static int __check_buffer_access(struct bpf_verifier_env *env, 6800 const char *buf_info, 6801 const struct bpf_reg_state *reg, 6802 int regno, int off, int size) 6803 { 6804 if (off < 0) { 6805 verbose(env, 6806 "R%d invalid %s buffer access: off=%d, size=%d\n", 6807 regno, buf_info, off, size); 6808 return -EACCES; 6809 } 6810 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6811 char tn_buf[48]; 6812 6813 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6814 verbose(env, 6815 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6816 regno, off, tn_buf); 6817 return -EACCES; 6818 } 6819 6820 return 0; 6821 } 6822 6823 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6824 const struct bpf_reg_state *reg, 6825 int regno, int off, int size) 6826 { 6827 int err; 6828 6829 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6830 if (err) 6831 return err; 6832 6833 if (off + size > env->prog->aux->max_tp_access) 6834 env->prog->aux->max_tp_access = off + size; 6835 6836 return 0; 6837 } 6838 6839 static int check_buffer_access(struct bpf_verifier_env *env, 6840 const struct bpf_reg_state *reg, 6841 int regno, int off, int size, 6842 bool zero_size_allowed, 6843 u32 *max_access) 6844 { 6845 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6846 int err; 6847 6848 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6849 if (err) 6850 return err; 6851 6852 if (off + size > *max_access) 6853 *max_access = off + size; 6854 6855 return 0; 6856 } 6857 6858 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6859 static void zext_32_to_64(struct bpf_reg_state *reg) 6860 { 6861 reg->var_off = tnum_subreg(reg->var_off); 6862 __reg_assign_32_into_64(reg); 6863 } 6864 6865 /* truncate register to smaller size (in bytes) 6866 * must be called with size < BPF_REG_SIZE 6867 */ 6868 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6869 { 6870 u64 mask; 6871 6872 /* clear high bits in bit representation */ 6873 reg->var_off = tnum_cast(reg->var_off, size); 6874 6875 /* fix arithmetic bounds */ 6876 mask = ((u64)1 << (size * 8)) - 1; 6877 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6878 reg->umin_value &= mask; 6879 reg->umax_value &= mask; 6880 } else { 6881 reg->umin_value = 0; 6882 reg->umax_value = mask; 6883 } 6884 reg->smin_value = reg->umin_value; 6885 reg->smax_value = reg->umax_value; 6886 6887 /* If size is smaller than 32bit register the 32bit register 6888 * values are also truncated so we push 64-bit bounds into 6889 * 32-bit bounds. Above were truncated < 32-bits already. 6890 */ 6891 if (size < 4) 6892 __mark_reg32_unbounded(reg); 6893 6894 reg_bounds_sync(reg); 6895 } 6896 6897 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6898 { 6899 if (size == 1) { 6900 reg->smin_value = reg->s32_min_value = S8_MIN; 6901 reg->smax_value = reg->s32_max_value = S8_MAX; 6902 } else if (size == 2) { 6903 reg->smin_value = reg->s32_min_value = S16_MIN; 6904 reg->smax_value = reg->s32_max_value = S16_MAX; 6905 } else { 6906 /* size == 4 */ 6907 reg->smin_value = reg->s32_min_value = S32_MIN; 6908 reg->smax_value = reg->s32_max_value = S32_MAX; 6909 } 6910 reg->umin_value = reg->u32_min_value = 0; 6911 reg->umax_value = U64_MAX; 6912 reg->u32_max_value = U32_MAX; 6913 reg->var_off = tnum_unknown; 6914 } 6915 6916 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6917 { 6918 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6919 u64 top_smax_value, top_smin_value; 6920 u64 num_bits = size * 8; 6921 6922 if (tnum_is_const(reg->var_off)) { 6923 u64_cval = reg->var_off.value; 6924 if (size == 1) 6925 reg->var_off = tnum_const((s8)u64_cval); 6926 else if (size == 2) 6927 reg->var_off = tnum_const((s16)u64_cval); 6928 else 6929 /* size == 4 */ 6930 reg->var_off = tnum_const((s32)u64_cval); 6931 6932 u64_cval = reg->var_off.value; 6933 reg->smax_value = reg->smin_value = u64_cval; 6934 reg->umax_value = reg->umin_value = u64_cval; 6935 reg->s32_max_value = reg->s32_min_value = u64_cval; 6936 reg->u32_max_value = reg->u32_min_value = u64_cval; 6937 return; 6938 } 6939 6940 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6941 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6942 6943 if (top_smax_value != top_smin_value) 6944 goto out; 6945 6946 /* find the s64_min and s64_min after sign extension */ 6947 if (size == 1) { 6948 init_s64_max = (s8)reg->smax_value; 6949 init_s64_min = (s8)reg->smin_value; 6950 } else if (size == 2) { 6951 init_s64_max = (s16)reg->smax_value; 6952 init_s64_min = (s16)reg->smin_value; 6953 } else { 6954 init_s64_max = (s32)reg->smax_value; 6955 init_s64_min = (s32)reg->smin_value; 6956 } 6957 6958 s64_max = max(init_s64_max, init_s64_min); 6959 s64_min = min(init_s64_max, init_s64_min); 6960 6961 /* both of s64_max/s64_min positive or negative */ 6962 if ((s64_max >= 0) == (s64_min >= 0)) { 6963 reg->s32_min_value = reg->smin_value = s64_min; 6964 reg->s32_max_value = reg->smax_value = s64_max; 6965 reg->u32_min_value = reg->umin_value = s64_min; 6966 reg->u32_max_value = reg->umax_value = s64_max; 6967 reg->var_off = tnum_range(s64_min, s64_max); 6968 return; 6969 } 6970 6971 out: 6972 set_sext64_default_val(reg, size); 6973 } 6974 6975 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6976 { 6977 if (size == 1) { 6978 reg->s32_min_value = S8_MIN; 6979 reg->s32_max_value = S8_MAX; 6980 } else { 6981 /* size == 2 */ 6982 reg->s32_min_value = S16_MIN; 6983 reg->s32_max_value = S16_MAX; 6984 } 6985 reg->u32_min_value = 0; 6986 reg->u32_max_value = U32_MAX; 6987 reg->var_off = tnum_subreg(tnum_unknown); 6988 } 6989 6990 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6991 { 6992 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6993 u32 top_smax_value, top_smin_value; 6994 u32 num_bits = size * 8; 6995 6996 if (tnum_is_const(reg->var_off)) { 6997 u32_val = reg->var_off.value; 6998 if (size == 1) 6999 reg->var_off = tnum_const((s8)u32_val); 7000 else 7001 reg->var_off = tnum_const((s16)u32_val); 7002 7003 u32_val = reg->var_off.value; 7004 reg->s32_min_value = reg->s32_max_value = u32_val; 7005 reg->u32_min_value = reg->u32_max_value = u32_val; 7006 return; 7007 } 7008 7009 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 7010 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 7011 7012 if (top_smax_value != top_smin_value) 7013 goto out; 7014 7015 /* find the s32_min and s32_min after sign extension */ 7016 if (size == 1) { 7017 init_s32_max = (s8)reg->s32_max_value; 7018 init_s32_min = (s8)reg->s32_min_value; 7019 } else { 7020 /* size == 2 */ 7021 init_s32_max = (s16)reg->s32_max_value; 7022 init_s32_min = (s16)reg->s32_min_value; 7023 } 7024 s32_max = max(init_s32_max, init_s32_min); 7025 s32_min = min(init_s32_max, init_s32_min); 7026 7027 if ((s32_min >= 0) == (s32_max >= 0)) { 7028 reg->s32_min_value = s32_min; 7029 reg->s32_max_value = s32_max; 7030 reg->u32_min_value = (u32)s32_min; 7031 reg->u32_max_value = (u32)s32_max; 7032 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 7033 return; 7034 } 7035 7036 out: 7037 set_sext32_default_val(reg, size); 7038 } 7039 7040 static bool bpf_map_is_rdonly(const struct bpf_map *map) 7041 { 7042 /* A map is considered read-only if the following condition are true: 7043 * 7044 * 1) BPF program side cannot change any of the map content. The 7045 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 7046 * and was set at map creation time. 7047 * 2) The map value(s) have been initialized from user space by a 7048 * loader and then "frozen", such that no new map update/delete 7049 * operations from syscall side are possible for the rest of 7050 * the map's lifetime from that point onwards. 7051 * 3) Any parallel/pending map update/delete operations from syscall 7052 * side have been completed. Only after that point, it's safe to 7053 * assume that map value(s) are immutable. 7054 */ 7055 return (map->map_flags & BPF_F_RDONLY_PROG) && 7056 READ_ONCE(map->frozen) && 7057 !bpf_map_write_active(map); 7058 } 7059 7060 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 7061 bool is_ldsx) 7062 { 7063 void *ptr; 7064 u64 addr; 7065 int err; 7066 7067 err = map->ops->map_direct_value_addr(map, &addr, off); 7068 if (err) 7069 return err; 7070 ptr = (void *)(long)addr + off; 7071 7072 switch (size) { 7073 case sizeof(u8): 7074 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 7075 break; 7076 case sizeof(u16): 7077 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 7078 break; 7079 case sizeof(u32): 7080 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 7081 break; 7082 case sizeof(u64): 7083 *val = *(u64 *)ptr; 7084 break; 7085 default: 7086 return -EINVAL; 7087 } 7088 return 0; 7089 } 7090 7091 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 7092 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 7093 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 7094 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 7095 7096 /* 7097 * Allow list few fields as RCU trusted or full trusted. 7098 * This logic doesn't allow mix tagging and will be removed once GCC supports 7099 * btf_type_tag. 7100 */ 7101 7102 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 7103 BTF_TYPE_SAFE_RCU(struct task_struct) { 7104 const cpumask_t *cpus_ptr; 7105 struct css_set __rcu *cgroups; 7106 struct task_struct __rcu *real_parent; 7107 struct task_struct *group_leader; 7108 }; 7109 7110 BTF_TYPE_SAFE_RCU(struct cgroup) { 7111 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 7112 struct kernfs_node *kn; 7113 }; 7114 7115 BTF_TYPE_SAFE_RCU(struct css_set) { 7116 struct cgroup *dfl_cgrp; 7117 }; 7118 7119 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) { 7120 struct cgroup *cgroup; 7121 }; 7122 7123 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 7124 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 7125 struct file __rcu *exe_file; 7126 }; 7127 7128 /* skb->sk, req->sk are not RCU protected, but we mark them as such 7129 * because bpf prog accessible sockets are SOCK_RCU_FREE. 7130 */ 7131 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 7132 struct sock *sk; 7133 }; 7134 7135 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 7136 struct sock *sk; 7137 }; 7138 7139 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 7140 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 7141 struct seq_file *seq; 7142 }; 7143 7144 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 7145 struct bpf_iter_meta *meta; 7146 struct task_struct *task; 7147 }; 7148 7149 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 7150 struct file *file; 7151 }; 7152 7153 BTF_TYPE_SAFE_TRUSTED(struct file) { 7154 struct inode *f_inode; 7155 }; 7156 7157 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) { 7158 struct inode *d_inode; 7159 }; 7160 7161 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 7162 struct sock *sk; 7163 }; 7164 7165 static bool type_is_rcu(struct bpf_verifier_env *env, 7166 struct bpf_reg_state *reg, 7167 const char *field_name, u32 btf_id) 7168 { 7169 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 7170 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 7171 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 7172 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)); 7173 7174 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 7175 } 7176 7177 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 7178 struct bpf_reg_state *reg, 7179 const char *field_name, u32 btf_id) 7180 { 7181 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 7182 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 7183 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 7184 7185 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 7186 } 7187 7188 static bool type_is_trusted(struct bpf_verifier_env *env, 7189 struct bpf_reg_state *reg, 7190 const char *field_name, u32 btf_id) 7191 { 7192 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 7193 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 7194 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 7195 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 7196 7197 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 7198 } 7199 7200 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 7201 struct bpf_reg_state *reg, 7202 const char *field_name, u32 btf_id) 7203 { 7204 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 7205 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)); 7206 7207 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 7208 "__safe_trusted_or_null"); 7209 } 7210 7211 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 7212 struct bpf_reg_state *regs, 7213 int regno, int off, int size, 7214 enum bpf_access_type atype, 7215 int value_regno) 7216 { 7217 struct bpf_reg_state *reg = regs + regno; 7218 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 7219 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 7220 const char *field_name = NULL; 7221 enum bpf_type_flag flag = 0; 7222 u32 btf_id = 0; 7223 int ret; 7224 7225 if (!env->allow_ptr_leaks) { 7226 verbose(env, 7227 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 7228 tname); 7229 return -EPERM; 7230 } 7231 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 7232 verbose(env, 7233 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 7234 tname); 7235 return -EINVAL; 7236 } 7237 if (off < 0) { 7238 verbose(env, 7239 "R%d is ptr_%s invalid negative access: off=%d\n", 7240 regno, tname, off); 7241 return -EACCES; 7242 } 7243 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 7244 char tn_buf[48]; 7245 7246 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7247 verbose(env, 7248 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 7249 regno, tname, off, tn_buf); 7250 return -EACCES; 7251 } 7252 7253 if (reg->type & MEM_USER) { 7254 verbose(env, 7255 "R%d is ptr_%s access user memory: off=%d\n", 7256 regno, tname, off); 7257 return -EACCES; 7258 } 7259 7260 if (reg->type & MEM_PERCPU) { 7261 verbose(env, 7262 "R%d is ptr_%s access percpu memory: off=%d\n", 7263 regno, tname, off); 7264 return -EACCES; 7265 } 7266 7267 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 7268 if (!btf_is_kernel(reg->btf)) { 7269 verifier_bug(env, "reg->btf must be kernel btf"); 7270 return -EFAULT; 7271 } 7272 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 7273 } else { 7274 /* Writes are permitted with default btf_struct_access for 7275 * program allocated objects (which always have ref_obj_id > 0), 7276 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 7277 */ 7278 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 7279 verbose(env, "only read is supported\n"); 7280 return -EACCES; 7281 } 7282 7283 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 7284 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 7285 verifier_bug(env, "ref_obj_id for allocated object must be non-zero"); 7286 return -EFAULT; 7287 } 7288 7289 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 7290 } 7291 7292 if (ret < 0) 7293 return ret; 7294 7295 if (ret != PTR_TO_BTF_ID) { 7296 /* just mark; */ 7297 7298 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 7299 /* If this is an untrusted pointer, all pointers formed by walking it 7300 * also inherit the untrusted flag. 7301 */ 7302 flag = PTR_UNTRUSTED; 7303 7304 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 7305 /* By default any pointer obtained from walking a trusted pointer is no 7306 * longer trusted, unless the field being accessed has explicitly been 7307 * marked as inheriting its parent's state of trust (either full or RCU). 7308 * For example: 7309 * 'cgroups' pointer is untrusted if task->cgroups dereference 7310 * happened in a sleepable program outside of bpf_rcu_read_lock() 7311 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 7312 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 7313 * 7314 * A regular RCU-protected pointer with __rcu tag can also be deemed 7315 * trusted if we are in an RCU CS. Such pointer can be NULL. 7316 */ 7317 if (type_is_trusted(env, reg, field_name, btf_id)) { 7318 flag |= PTR_TRUSTED; 7319 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 7320 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 7321 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 7322 if (type_is_rcu(env, reg, field_name, btf_id)) { 7323 /* ignore __rcu tag and mark it MEM_RCU */ 7324 flag |= MEM_RCU; 7325 } else if (flag & MEM_RCU || 7326 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 7327 /* __rcu tagged pointers can be NULL */ 7328 flag |= MEM_RCU | PTR_MAYBE_NULL; 7329 7330 /* We always trust them */ 7331 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 7332 flag & PTR_UNTRUSTED) 7333 flag &= ~PTR_UNTRUSTED; 7334 } else if (flag & (MEM_PERCPU | MEM_USER)) { 7335 /* keep as-is */ 7336 } else { 7337 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 7338 clear_trusted_flags(&flag); 7339 } 7340 } else { 7341 /* 7342 * If not in RCU CS or MEM_RCU pointer can be NULL then 7343 * aggressively mark as untrusted otherwise such 7344 * pointers will be plain PTR_TO_BTF_ID without flags 7345 * and will be allowed to be passed into helpers for 7346 * compat reasons. 7347 */ 7348 flag = PTR_UNTRUSTED; 7349 } 7350 } else { 7351 /* Old compat. Deprecated */ 7352 clear_trusted_flags(&flag); 7353 } 7354 7355 if (atype == BPF_READ && value_regno >= 0) { 7356 ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 7357 if (ret < 0) 7358 return ret; 7359 } 7360 7361 return 0; 7362 } 7363 7364 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 7365 struct bpf_reg_state *regs, 7366 int regno, int off, int size, 7367 enum bpf_access_type atype, 7368 int value_regno) 7369 { 7370 struct bpf_reg_state *reg = regs + regno; 7371 struct bpf_map *map = reg->map_ptr; 7372 struct bpf_reg_state map_reg; 7373 enum bpf_type_flag flag = 0; 7374 const struct btf_type *t; 7375 const char *tname; 7376 u32 btf_id; 7377 int ret; 7378 7379 if (!btf_vmlinux) { 7380 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 7381 return -ENOTSUPP; 7382 } 7383 7384 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 7385 verbose(env, "map_ptr access not supported for map type %d\n", 7386 map->map_type); 7387 return -ENOTSUPP; 7388 } 7389 7390 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 7391 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 7392 7393 if (!env->allow_ptr_leaks) { 7394 verbose(env, 7395 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 7396 tname); 7397 return -EPERM; 7398 } 7399 7400 if (off < 0) { 7401 verbose(env, "R%d is %s invalid negative access: off=%d\n", 7402 regno, tname, off); 7403 return -EACCES; 7404 } 7405 7406 if (atype != BPF_READ) { 7407 verbose(env, "only read from %s is supported\n", tname); 7408 return -EACCES; 7409 } 7410 7411 /* Simulate access to a PTR_TO_BTF_ID */ 7412 memset(&map_reg, 0, sizeof(map_reg)); 7413 ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, 7414 btf_vmlinux, *map->ops->map_btf_id, 0); 7415 if (ret < 0) 7416 return ret; 7417 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 7418 if (ret < 0) 7419 return ret; 7420 7421 if (value_regno >= 0) { 7422 ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 7423 if (ret < 0) 7424 return ret; 7425 } 7426 7427 return 0; 7428 } 7429 7430 /* Check that the stack access at the given offset is within bounds. The 7431 * maximum valid offset is -1. 7432 * 7433 * The minimum valid offset is -MAX_BPF_STACK for writes, and 7434 * -state->allocated_stack for reads. 7435 */ 7436 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 7437 s64 off, 7438 struct bpf_func_state *state, 7439 enum bpf_access_type t) 7440 { 7441 int min_valid_off; 7442 7443 if (t == BPF_WRITE || env->allow_uninit_stack) 7444 min_valid_off = -MAX_BPF_STACK; 7445 else 7446 min_valid_off = -state->allocated_stack; 7447 7448 if (off < min_valid_off || off > -1) 7449 return -EACCES; 7450 return 0; 7451 } 7452 7453 /* Check that the stack access at 'regno + off' falls within the maximum stack 7454 * bounds. 7455 * 7456 * 'off' includes `regno->offset`, but not its dynamic part (if any). 7457 */ 7458 static int check_stack_access_within_bounds( 7459 struct bpf_verifier_env *env, 7460 int regno, int off, int access_size, 7461 enum bpf_access_type type) 7462 { 7463 struct bpf_reg_state *regs = cur_regs(env); 7464 struct bpf_reg_state *reg = regs + regno; 7465 struct bpf_func_state *state = func(env, reg); 7466 s64 min_off, max_off; 7467 int err; 7468 char *err_extra; 7469 7470 if (type == BPF_READ) 7471 err_extra = " read from"; 7472 else 7473 err_extra = " write to"; 7474 7475 if (tnum_is_const(reg->var_off)) { 7476 min_off = (s64)reg->var_off.value + off; 7477 max_off = min_off + access_size; 7478 } else { 7479 if (reg->smax_value >= BPF_MAX_VAR_OFF || 7480 reg->smin_value <= -BPF_MAX_VAR_OFF) { 7481 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 7482 err_extra, regno); 7483 return -EACCES; 7484 } 7485 min_off = reg->smin_value + off; 7486 max_off = reg->smax_value + off + access_size; 7487 } 7488 7489 err = check_stack_slot_within_bounds(env, min_off, state, type); 7490 if (!err && max_off > 0) 7491 err = -EINVAL; /* out of stack access into non-negative offsets */ 7492 if (!err && access_size < 0) 7493 /* access_size should not be negative (or overflow an int); others checks 7494 * along the way should have prevented such an access. 7495 */ 7496 err = -EFAULT; /* invalid negative access size; integer overflow? */ 7497 7498 if (err) { 7499 if (tnum_is_const(reg->var_off)) { 7500 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 7501 err_extra, regno, off, access_size); 7502 } else { 7503 char tn_buf[48]; 7504 7505 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7506 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 7507 err_extra, regno, tn_buf, off, access_size); 7508 } 7509 return err; 7510 } 7511 7512 /* Note that there is no stack access with offset zero, so the needed stack 7513 * size is -min_off, not -min_off+1. 7514 */ 7515 return grow_stack_state(env, state, -min_off /* size */); 7516 } 7517 7518 static bool get_func_retval_range(struct bpf_prog *prog, 7519 struct bpf_retval_range *range) 7520 { 7521 if (prog->type == BPF_PROG_TYPE_LSM && 7522 prog->expected_attach_type == BPF_LSM_MAC && 7523 !bpf_lsm_get_retval_range(prog, range)) { 7524 return true; 7525 } 7526 return false; 7527 } 7528 7529 /* check whether memory at (regno + off) is accessible for t = (read | write) 7530 * if t==write, value_regno is a register which value is stored into memory 7531 * if t==read, value_regno is a register which will receive the value from memory 7532 * if t==write && value_regno==-1, some unknown value is stored into memory 7533 * if t==read && value_regno==-1, don't care what we read from memory 7534 */ 7535 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 7536 int off, int bpf_size, enum bpf_access_type t, 7537 int value_regno, bool strict_alignment_once, bool is_ldsx) 7538 { 7539 struct bpf_reg_state *regs = cur_regs(env); 7540 struct bpf_reg_state *reg = regs + regno; 7541 int size, err = 0; 7542 7543 size = bpf_size_to_bytes(bpf_size); 7544 if (size < 0) 7545 return size; 7546 7547 /* alignment checks will add in reg->off themselves */ 7548 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 7549 if (err) 7550 return err; 7551 7552 /* for access checks, reg->off is just part of off */ 7553 off += reg->off; 7554 7555 if (reg->type == PTR_TO_MAP_KEY) { 7556 if (t == BPF_WRITE) { 7557 verbose(env, "write to change key R%d not allowed\n", regno); 7558 return -EACCES; 7559 } 7560 7561 err = check_mem_region_access(env, regno, off, size, 7562 reg->map_ptr->key_size, false); 7563 if (err) 7564 return err; 7565 if (value_regno >= 0) 7566 mark_reg_unknown(env, regs, value_regno); 7567 } else if (reg->type == PTR_TO_MAP_VALUE) { 7568 struct btf_field *kptr_field = NULL; 7569 7570 if (t == BPF_WRITE && value_regno >= 0 && 7571 is_pointer_value(env, value_regno)) { 7572 verbose(env, "R%d leaks addr into map\n", value_regno); 7573 return -EACCES; 7574 } 7575 err = check_map_access_type(env, regno, off, size, t); 7576 if (err) 7577 return err; 7578 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 7579 if (err) 7580 return err; 7581 if (tnum_is_const(reg->var_off)) 7582 kptr_field = btf_record_find(reg->map_ptr->record, 7583 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 7584 if (kptr_field) { 7585 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 7586 } else if (t == BPF_READ && value_regno >= 0) { 7587 struct bpf_map *map = reg->map_ptr; 7588 7589 /* if map is read-only, track its contents as scalars */ 7590 if (tnum_is_const(reg->var_off) && 7591 bpf_map_is_rdonly(map) && 7592 map->ops->map_direct_value_addr) { 7593 int map_off = off + reg->var_off.value; 7594 u64 val = 0; 7595 7596 err = bpf_map_direct_read(map, map_off, size, 7597 &val, is_ldsx); 7598 if (err) 7599 return err; 7600 7601 regs[value_regno].type = SCALAR_VALUE; 7602 __mark_reg_known(®s[value_regno], val); 7603 } else { 7604 mark_reg_unknown(env, regs, value_regno); 7605 } 7606 } 7607 } else if (base_type(reg->type) == PTR_TO_MEM) { 7608 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7609 bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED); 7610 7611 if (type_may_be_null(reg->type)) { 7612 verbose(env, "R%d invalid mem access '%s'\n", regno, 7613 reg_type_str(env, reg->type)); 7614 return -EACCES; 7615 } 7616 7617 if (t == BPF_WRITE && rdonly_mem) { 7618 verbose(env, "R%d cannot write into %s\n", 7619 regno, reg_type_str(env, reg->type)); 7620 return -EACCES; 7621 } 7622 7623 if (t == BPF_WRITE && value_regno >= 0 && 7624 is_pointer_value(env, value_regno)) { 7625 verbose(env, "R%d leaks addr into mem\n", value_regno); 7626 return -EACCES; 7627 } 7628 7629 /* 7630 * Accesses to untrusted PTR_TO_MEM are done through probe 7631 * instructions, hence no need to check bounds in that case. 7632 */ 7633 if (!rdonly_untrusted) 7634 err = check_mem_region_access(env, regno, off, size, 7635 reg->mem_size, false); 7636 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 7637 mark_reg_unknown(env, regs, value_regno); 7638 } else if (reg->type == PTR_TO_CTX) { 7639 struct bpf_retval_range range; 7640 struct bpf_insn_access_aux info = { 7641 .reg_type = SCALAR_VALUE, 7642 .is_ldsx = is_ldsx, 7643 .log = &env->log, 7644 }; 7645 7646 if (t == BPF_WRITE && value_regno >= 0 && 7647 is_pointer_value(env, value_regno)) { 7648 verbose(env, "R%d leaks addr into ctx\n", value_regno); 7649 return -EACCES; 7650 } 7651 7652 err = check_ptr_off_reg(env, reg, regno); 7653 if (err < 0) 7654 return err; 7655 7656 err = check_ctx_access(env, insn_idx, off, size, t, &info); 7657 if (err) 7658 verbose_linfo(env, insn_idx, "; "); 7659 if (!err && t == BPF_READ && value_regno >= 0) { 7660 /* ctx access returns either a scalar, or a 7661 * PTR_TO_PACKET[_META,_END]. In the latter 7662 * case, we know the offset is zero. 7663 */ 7664 if (info.reg_type == SCALAR_VALUE) { 7665 if (info.is_retval && get_func_retval_range(env->prog, &range)) { 7666 err = __mark_reg_s32_range(env, regs, value_regno, 7667 range.minval, range.maxval); 7668 if (err) 7669 return err; 7670 } else { 7671 mark_reg_unknown(env, regs, value_regno); 7672 } 7673 } else { 7674 mark_reg_known_zero(env, regs, 7675 value_regno); 7676 if (type_may_be_null(info.reg_type)) 7677 regs[value_regno].id = ++env->id_gen; 7678 /* A load of ctx field could have different 7679 * actual load size with the one encoded in the 7680 * insn. When the dst is PTR, it is for sure not 7681 * a sub-register. 7682 */ 7683 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 7684 if (base_type(info.reg_type) == PTR_TO_BTF_ID) { 7685 regs[value_regno].btf = info.btf; 7686 regs[value_regno].btf_id = info.btf_id; 7687 regs[value_regno].ref_obj_id = info.ref_obj_id; 7688 } 7689 } 7690 regs[value_regno].type = info.reg_type; 7691 } 7692 7693 } else if (reg->type == PTR_TO_STACK) { 7694 /* Basic bounds checks. */ 7695 err = check_stack_access_within_bounds(env, regno, off, size, t); 7696 if (err) 7697 return err; 7698 7699 if (t == BPF_READ) 7700 err = check_stack_read(env, regno, off, size, 7701 value_regno); 7702 else 7703 err = check_stack_write(env, regno, off, size, 7704 value_regno, insn_idx); 7705 } else if (reg_is_pkt_pointer(reg)) { 7706 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 7707 verbose(env, "cannot write into packet\n"); 7708 return -EACCES; 7709 } 7710 if (t == BPF_WRITE && value_regno >= 0 && 7711 is_pointer_value(env, value_regno)) { 7712 verbose(env, "R%d leaks addr into packet\n", 7713 value_regno); 7714 return -EACCES; 7715 } 7716 err = check_packet_access(env, regno, off, size, false); 7717 if (!err && t == BPF_READ && value_regno >= 0) 7718 mark_reg_unknown(env, regs, value_regno); 7719 } else if (reg->type == PTR_TO_FLOW_KEYS) { 7720 if (t == BPF_WRITE && value_regno >= 0 && 7721 is_pointer_value(env, value_regno)) { 7722 verbose(env, "R%d leaks addr into flow keys\n", 7723 value_regno); 7724 return -EACCES; 7725 } 7726 7727 err = check_flow_keys_access(env, off, size); 7728 if (!err && t == BPF_READ && value_regno >= 0) 7729 mark_reg_unknown(env, regs, value_regno); 7730 } else if (type_is_sk_pointer(reg->type)) { 7731 if (t == BPF_WRITE) { 7732 verbose(env, "R%d cannot write into %s\n", 7733 regno, reg_type_str(env, reg->type)); 7734 return -EACCES; 7735 } 7736 err = check_sock_access(env, insn_idx, regno, off, size, t); 7737 if (!err && value_regno >= 0) 7738 mark_reg_unknown(env, regs, value_regno); 7739 } else if (reg->type == PTR_TO_TP_BUFFER) { 7740 err = check_tp_buffer_access(env, reg, regno, off, size); 7741 if (!err && t == BPF_READ && value_regno >= 0) 7742 mark_reg_unknown(env, regs, value_regno); 7743 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 7744 !type_may_be_null(reg->type)) { 7745 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 7746 value_regno); 7747 } else if (reg->type == CONST_PTR_TO_MAP) { 7748 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 7749 value_regno); 7750 } else if (base_type(reg->type) == PTR_TO_BUF) { 7751 bool rdonly_mem = type_is_rdonly_mem(reg->type); 7752 u32 *max_access; 7753 7754 if (rdonly_mem) { 7755 if (t == BPF_WRITE) { 7756 verbose(env, "R%d cannot write into %s\n", 7757 regno, reg_type_str(env, reg->type)); 7758 return -EACCES; 7759 } 7760 max_access = &env->prog->aux->max_rdonly_access; 7761 } else { 7762 max_access = &env->prog->aux->max_rdwr_access; 7763 } 7764 7765 err = check_buffer_access(env, reg, regno, off, size, false, 7766 max_access); 7767 7768 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 7769 mark_reg_unknown(env, regs, value_regno); 7770 } else if (reg->type == PTR_TO_ARENA) { 7771 if (t == BPF_READ && value_regno >= 0) 7772 mark_reg_unknown(env, regs, value_regno); 7773 } else { 7774 verbose(env, "R%d invalid mem access '%s'\n", regno, 7775 reg_type_str(env, reg->type)); 7776 return -EACCES; 7777 } 7778 7779 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 7780 regs[value_regno].type == SCALAR_VALUE) { 7781 if (!is_ldsx) 7782 /* b/h/w load zero-extends, mark upper bits as known 0 */ 7783 coerce_reg_to_size(®s[value_regno], size); 7784 else 7785 coerce_reg_to_size_sx(®s[value_regno], size); 7786 } 7787 return err; 7788 } 7789 7790 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 7791 bool allow_trust_mismatch); 7792 7793 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn, 7794 bool strict_alignment_once, bool is_ldsx, 7795 bool allow_trust_mismatch, const char *ctx) 7796 { 7797 struct bpf_reg_state *regs = cur_regs(env); 7798 enum bpf_reg_type src_reg_type; 7799 int err; 7800 7801 /* check src operand */ 7802 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7803 if (err) 7804 return err; 7805 7806 /* check dst operand */ 7807 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 7808 if (err) 7809 return err; 7810 7811 src_reg_type = regs[insn->src_reg].type; 7812 7813 /* Check if (src_reg + off) is readable. The state of dst_reg will be 7814 * updated by this call. 7815 */ 7816 err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off, 7817 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg, 7818 strict_alignment_once, is_ldsx); 7819 err = err ?: save_aux_ptr_type(env, src_reg_type, 7820 allow_trust_mismatch); 7821 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx); 7822 7823 return err; 7824 } 7825 7826 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn, 7827 bool strict_alignment_once) 7828 { 7829 struct bpf_reg_state *regs = cur_regs(env); 7830 enum bpf_reg_type dst_reg_type; 7831 int err; 7832 7833 /* check src1 operand */ 7834 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7835 if (err) 7836 return err; 7837 7838 /* check src2 operand */ 7839 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7840 if (err) 7841 return err; 7842 7843 dst_reg_type = regs[insn->dst_reg].type; 7844 7845 /* Check if (dst_reg + off) is writeable. */ 7846 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 7847 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg, 7848 strict_alignment_once, false); 7849 err = err ?: save_aux_ptr_type(env, dst_reg_type, false); 7850 7851 return err; 7852 } 7853 7854 static int check_atomic_rmw(struct bpf_verifier_env *env, 7855 struct bpf_insn *insn) 7856 { 7857 int load_reg; 7858 int err; 7859 7860 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 7861 verbose(env, "invalid atomic operand size\n"); 7862 return -EINVAL; 7863 } 7864 7865 /* check src1 operand */ 7866 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7867 if (err) 7868 return err; 7869 7870 /* check src2 operand */ 7871 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7872 if (err) 7873 return err; 7874 7875 if (insn->imm == BPF_CMPXCHG) { 7876 /* Check comparison of R0 with memory location */ 7877 const u32 aux_reg = BPF_REG_0; 7878 7879 err = check_reg_arg(env, aux_reg, SRC_OP); 7880 if (err) 7881 return err; 7882 7883 if (is_pointer_value(env, aux_reg)) { 7884 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7885 return -EACCES; 7886 } 7887 } 7888 7889 if (is_pointer_value(env, insn->src_reg)) { 7890 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7891 return -EACCES; 7892 } 7893 7894 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 7895 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7896 insn->dst_reg, 7897 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7898 return -EACCES; 7899 } 7900 7901 if (insn->imm & BPF_FETCH) { 7902 if (insn->imm == BPF_CMPXCHG) 7903 load_reg = BPF_REG_0; 7904 else 7905 load_reg = insn->src_reg; 7906 7907 /* check and record load of old value */ 7908 err = check_reg_arg(env, load_reg, DST_OP); 7909 if (err) 7910 return err; 7911 } else { 7912 /* This instruction accesses a memory location but doesn't 7913 * actually load it into a register. 7914 */ 7915 load_reg = -1; 7916 } 7917 7918 /* Check whether we can read the memory, with second call for fetch 7919 * case to simulate the register fill. 7920 */ 7921 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 7922 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7923 if (!err && load_reg >= 0) 7924 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 7925 insn->off, BPF_SIZE(insn->code), 7926 BPF_READ, load_reg, true, false); 7927 if (err) 7928 return err; 7929 7930 if (is_arena_reg(env, insn->dst_reg)) { 7931 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 7932 if (err) 7933 return err; 7934 } 7935 /* Check whether we can write into the same memory. */ 7936 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 7937 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7938 if (err) 7939 return err; 7940 return 0; 7941 } 7942 7943 static int check_atomic_load(struct bpf_verifier_env *env, 7944 struct bpf_insn *insn) 7945 { 7946 int err; 7947 7948 err = check_load_mem(env, insn, true, false, false, "atomic_load"); 7949 if (err) 7950 return err; 7951 7952 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) { 7953 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n", 7954 insn->src_reg, 7955 reg_type_str(env, reg_state(env, insn->src_reg)->type)); 7956 return -EACCES; 7957 } 7958 7959 return 0; 7960 } 7961 7962 static int check_atomic_store(struct bpf_verifier_env *env, 7963 struct bpf_insn *insn) 7964 { 7965 int err; 7966 7967 err = check_store_reg(env, insn, true); 7968 if (err) 7969 return err; 7970 7971 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 7972 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7973 insn->dst_reg, 7974 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7975 return -EACCES; 7976 } 7977 7978 return 0; 7979 } 7980 7981 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn) 7982 { 7983 switch (insn->imm) { 7984 case BPF_ADD: 7985 case BPF_ADD | BPF_FETCH: 7986 case BPF_AND: 7987 case BPF_AND | BPF_FETCH: 7988 case BPF_OR: 7989 case BPF_OR | BPF_FETCH: 7990 case BPF_XOR: 7991 case BPF_XOR | BPF_FETCH: 7992 case BPF_XCHG: 7993 case BPF_CMPXCHG: 7994 return check_atomic_rmw(env, insn); 7995 case BPF_LOAD_ACQ: 7996 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 7997 verbose(env, 7998 "64-bit load-acquires are only supported on 64-bit arches\n"); 7999 return -EOPNOTSUPP; 8000 } 8001 return check_atomic_load(env, insn); 8002 case BPF_STORE_REL: 8003 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 8004 verbose(env, 8005 "64-bit store-releases are only supported on 64-bit arches\n"); 8006 return -EOPNOTSUPP; 8007 } 8008 return check_atomic_store(env, insn); 8009 default: 8010 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", 8011 insn->imm); 8012 return -EINVAL; 8013 } 8014 } 8015 8016 /* When register 'regno' is used to read the stack (either directly or through 8017 * a helper function) make sure that it's within stack boundary and, depending 8018 * on the access type and privileges, that all elements of the stack are 8019 * initialized. 8020 * 8021 * 'off' includes 'regno->off', but not its dynamic part (if any). 8022 * 8023 * All registers that have been spilled on the stack in the slots within the 8024 * read offsets are marked as read. 8025 */ 8026 static int check_stack_range_initialized( 8027 struct bpf_verifier_env *env, int regno, int off, 8028 int access_size, bool zero_size_allowed, 8029 enum bpf_access_type type, struct bpf_call_arg_meta *meta) 8030 { 8031 struct bpf_reg_state *reg = reg_state(env, regno); 8032 struct bpf_func_state *state = func(env, reg); 8033 int err, min_off, max_off, i, j, slot, spi; 8034 /* Some accesses can write anything into the stack, others are 8035 * read-only. 8036 */ 8037 bool clobber = false; 8038 8039 if (access_size == 0 && !zero_size_allowed) { 8040 verbose(env, "invalid zero-sized read\n"); 8041 return -EACCES; 8042 } 8043 8044 if (type == BPF_WRITE) 8045 clobber = true; 8046 8047 err = check_stack_access_within_bounds(env, regno, off, access_size, type); 8048 if (err) 8049 return err; 8050 8051 8052 if (tnum_is_const(reg->var_off)) { 8053 min_off = max_off = reg->var_off.value + off; 8054 } else { 8055 /* Variable offset is prohibited for unprivileged mode for 8056 * simplicity since it requires corresponding support in 8057 * Spectre masking for stack ALU. 8058 * See also retrieve_ptr_limit(). 8059 */ 8060 if (!env->bypass_spec_v1) { 8061 char tn_buf[48]; 8062 8063 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 8064 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 8065 regno, tn_buf); 8066 return -EACCES; 8067 } 8068 /* Only initialized buffer on stack is allowed to be accessed 8069 * with variable offset. With uninitialized buffer it's hard to 8070 * guarantee that whole memory is marked as initialized on 8071 * helper return since specific bounds are unknown what may 8072 * cause uninitialized stack leaking. 8073 */ 8074 if (meta && meta->raw_mode) 8075 meta = NULL; 8076 8077 min_off = reg->smin_value + off; 8078 max_off = reg->smax_value + off; 8079 } 8080 8081 if (meta && meta->raw_mode) { 8082 /* Ensure we won't be overwriting dynptrs when simulating byte 8083 * by byte access in check_helper_call using meta.access_size. 8084 * This would be a problem if we have a helper in the future 8085 * which takes: 8086 * 8087 * helper(uninit_mem, len, dynptr) 8088 * 8089 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 8090 * may end up writing to dynptr itself when touching memory from 8091 * arg 1. This can be relaxed on a case by case basis for known 8092 * safe cases, but reject due to the possibilitiy of aliasing by 8093 * default. 8094 */ 8095 for (i = min_off; i < max_off + access_size; i++) { 8096 int stack_off = -i - 1; 8097 8098 spi = __get_spi(i); 8099 /* raw_mode may write past allocated_stack */ 8100 if (state->allocated_stack <= stack_off) 8101 continue; 8102 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 8103 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 8104 return -EACCES; 8105 } 8106 } 8107 meta->access_size = access_size; 8108 meta->regno = regno; 8109 return 0; 8110 } 8111 8112 for (i = min_off; i < max_off + access_size; i++) { 8113 u8 *stype; 8114 8115 slot = -i - 1; 8116 spi = slot / BPF_REG_SIZE; 8117 if (state->allocated_stack <= slot) { 8118 verbose(env, "allocated_stack too small\n"); 8119 return -EFAULT; 8120 } 8121 8122 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 8123 if (*stype == STACK_MISC) 8124 goto mark; 8125 if ((*stype == STACK_ZERO) || 8126 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 8127 if (clobber) { 8128 /* helper can write anything into the stack */ 8129 *stype = STACK_MISC; 8130 } 8131 goto mark; 8132 } 8133 8134 if (is_spilled_reg(&state->stack[spi]) && 8135 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 8136 env->allow_ptr_leaks)) { 8137 if (clobber) { 8138 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 8139 for (j = 0; j < BPF_REG_SIZE; j++) 8140 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 8141 } 8142 goto mark; 8143 } 8144 8145 if (tnum_is_const(reg->var_off)) { 8146 verbose(env, "invalid read from stack R%d off %d+%d size %d\n", 8147 regno, min_off, i - min_off, access_size); 8148 } else { 8149 char tn_buf[48]; 8150 8151 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 8152 verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n", 8153 regno, tn_buf, i - min_off, access_size); 8154 } 8155 return -EACCES; 8156 mark: 8157 /* reading any byte out of 8-byte 'spill_slot' will cause 8158 * the whole slot to be marked as 'read' 8159 */ 8160 mark_reg_read(env, &state->stack[spi].spilled_ptr, 8161 state->stack[spi].spilled_ptr.parent, 8162 REG_LIVE_READ64); 8163 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 8164 * be sure that whether stack slot is written to or not. Hence, 8165 * we must still conservatively propagate reads upwards even if 8166 * helper may write to the entire memory range. 8167 */ 8168 } 8169 return 0; 8170 } 8171 8172 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 8173 int access_size, enum bpf_access_type access_type, 8174 bool zero_size_allowed, 8175 struct bpf_call_arg_meta *meta) 8176 { 8177 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8178 u32 *max_access; 8179 8180 switch (base_type(reg->type)) { 8181 case PTR_TO_PACKET: 8182 case PTR_TO_PACKET_META: 8183 return check_packet_access(env, regno, reg->off, access_size, 8184 zero_size_allowed); 8185 case PTR_TO_MAP_KEY: 8186 if (access_type == BPF_WRITE) { 8187 verbose(env, "R%d cannot write into %s\n", regno, 8188 reg_type_str(env, reg->type)); 8189 return -EACCES; 8190 } 8191 return check_mem_region_access(env, regno, reg->off, access_size, 8192 reg->map_ptr->key_size, false); 8193 case PTR_TO_MAP_VALUE: 8194 if (check_map_access_type(env, regno, reg->off, access_size, access_type)) 8195 return -EACCES; 8196 return check_map_access(env, regno, reg->off, access_size, 8197 zero_size_allowed, ACCESS_HELPER); 8198 case PTR_TO_MEM: 8199 if (type_is_rdonly_mem(reg->type)) { 8200 if (access_type == BPF_WRITE) { 8201 verbose(env, "R%d cannot write into %s\n", regno, 8202 reg_type_str(env, reg->type)); 8203 return -EACCES; 8204 } 8205 } 8206 return check_mem_region_access(env, regno, reg->off, 8207 access_size, reg->mem_size, 8208 zero_size_allowed); 8209 case PTR_TO_BUF: 8210 if (type_is_rdonly_mem(reg->type)) { 8211 if (access_type == BPF_WRITE) { 8212 verbose(env, "R%d cannot write into %s\n", regno, 8213 reg_type_str(env, reg->type)); 8214 return -EACCES; 8215 } 8216 8217 max_access = &env->prog->aux->max_rdonly_access; 8218 } else { 8219 max_access = &env->prog->aux->max_rdwr_access; 8220 } 8221 return check_buffer_access(env, reg, regno, reg->off, 8222 access_size, zero_size_allowed, 8223 max_access); 8224 case PTR_TO_STACK: 8225 return check_stack_range_initialized( 8226 env, 8227 regno, reg->off, access_size, 8228 zero_size_allowed, access_type, meta); 8229 case PTR_TO_BTF_ID: 8230 return check_ptr_to_btf_access(env, regs, regno, reg->off, 8231 access_size, BPF_READ, -1); 8232 case PTR_TO_CTX: 8233 /* in case the function doesn't know how to access the context, 8234 * (because we are in a program of type SYSCALL for example), we 8235 * can not statically check its size. 8236 * Dynamically check it now. 8237 */ 8238 if (!env->ops->convert_ctx_access) { 8239 int offset = access_size - 1; 8240 8241 /* Allow zero-byte read from PTR_TO_CTX */ 8242 if (access_size == 0) 8243 return zero_size_allowed ? 0 : -EACCES; 8244 8245 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 8246 access_type, -1, false, false); 8247 } 8248 8249 fallthrough; 8250 default: /* scalar_value or invalid ptr */ 8251 /* Allow zero-byte read from NULL, regardless of pointer type */ 8252 if (zero_size_allowed && access_size == 0 && 8253 register_is_null(reg)) 8254 return 0; 8255 8256 verbose(env, "R%d type=%s ", regno, 8257 reg_type_str(env, reg->type)); 8258 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 8259 return -EACCES; 8260 } 8261 } 8262 8263 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 8264 * size. 8265 * 8266 * @regno is the register containing the access size. regno-1 is the register 8267 * containing the pointer. 8268 */ 8269 static int check_mem_size_reg(struct bpf_verifier_env *env, 8270 struct bpf_reg_state *reg, u32 regno, 8271 enum bpf_access_type access_type, 8272 bool zero_size_allowed, 8273 struct bpf_call_arg_meta *meta) 8274 { 8275 int err; 8276 8277 /* This is used to refine r0 return value bounds for helpers 8278 * that enforce this value as an upper bound on return values. 8279 * See do_refine_retval_range() for helpers that can refine 8280 * the return value. C type of helper is u32 so we pull register 8281 * bound from umax_value however, if negative verifier errors 8282 * out. Only upper bounds can be learned because retval is an 8283 * int type and negative retvals are allowed. 8284 */ 8285 meta->msize_max_value = reg->umax_value; 8286 8287 /* The register is SCALAR_VALUE; the access check happens using 8288 * its boundaries. For unprivileged variable accesses, disable 8289 * raw mode so that the program is required to initialize all 8290 * the memory that the helper could just partially fill up. 8291 */ 8292 if (!tnum_is_const(reg->var_off)) 8293 meta = NULL; 8294 8295 if (reg->smin_value < 0) { 8296 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 8297 regno); 8298 return -EACCES; 8299 } 8300 8301 if (reg->umin_value == 0 && !zero_size_allowed) { 8302 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 8303 regno, reg->umin_value, reg->umax_value); 8304 return -EACCES; 8305 } 8306 8307 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 8308 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 8309 regno); 8310 return -EACCES; 8311 } 8312 err = check_helper_mem_access(env, regno - 1, reg->umax_value, 8313 access_type, zero_size_allowed, meta); 8314 if (!err) 8315 err = mark_chain_precision(env, regno); 8316 return err; 8317 } 8318 8319 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8320 u32 regno, u32 mem_size) 8321 { 8322 bool may_be_null = type_may_be_null(reg->type); 8323 struct bpf_reg_state saved_reg; 8324 int err; 8325 8326 if (register_is_null(reg)) 8327 return 0; 8328 8329 /* Assuming that the register contains a value check if the memory 8330 * access is safe. Temporarily save and restore the register's state as 8331 * the conversion shouldn't be visible to a caller. 8332 */ 8333 if (may_be_null) { 8334 saved_reg = *reg; 8335 mark_ptr_not_null_reg(reg); 8336 } 8337 8338 err = check_helper_mem_access(env, regno, mem_size, BPF_READ, true, NULL); 8339 err = err ?: check_helper_mem_access(env, regno, mem_size, BPF_WRITE, true, NULL); 8340 8341 if (may_be_null) 8342 *reg = saved_reg; 8343 8344 return err; 8345 } 8346 8347 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8348 u32 regno) 8349 { 8350 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 8351 bool may_be_null = type_may_be_null(mem_reg->type); 8352 struct bpf_reg_state saved_reg; 8353 struct bpf_call_arg_meta meta; 8354 int err; 8355 8356 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 8357 8358 memset(&meta, 0, sizeof(meta)); 8359 8360 if (may_be_null) { 8361 saved_reg = *mem_reg; 8362 mark_ptr_not_null_reg(mem_reg); 8363 } 8364 8365 err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta); 8366 err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta); 8367 8368 if (may_be_null) 8369 *mem_reg = saved_reg; 8370 8371 return err; 8372 } 8373 8374 enum { 8375 PROCESS_SPIN_LOCK = (1 << 0), 8376 PROCESS_RES_LOCK = (1 << 1), 8377 PROCESS_LOCK_IRQ = (1 << 2), 8378 }; 8379 8380 /* Implementation details: 8381 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 8382 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 8383 * Two bpf_map_lookups (even with the same key) will have different reg->id. 8384 * Two separate bpf_obj_new will also have different reg->id. 8385 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 8386 * clears reg->id after value_or_null->value transition, since the verifier only 8387 * cares about the range of access to valid map value pointer and doesn't care 8388 * about actual address of the map element. 8389 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 8390 * reg->id > 0 after value_or_null->value transition. By doing so 8391 * two bpf_map_lookups will be considered two different pointers that 8392 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 8393 * returned from bpf_obj_new. 8394 * The verifier allows taking only one bpf_spin_lock at a time to avoid 8395 * dead-locks. 8396 * Since only one bpf_spin_lock is allowed the checks are simpler than 8397 * reg_is_refcounted() logic. The verifier needs to remember only 8398 * one spin_lock instead of array of acquired_refs. 8399 * env->cur_state->active_locks remembers which map value element or allocated 8400 * object got locked and clears it after bpf_spin_unlock. 8401 */ 8402 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags) 8403 { 8404 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK; 8405 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin"; 8406 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8407 struct bpf_verifier_state *cur = env->cur_state; 8408 bool is_const = tnum_is_const(reg->var_off); 8409 bool is_irq = flags & PROCESS_LOCK_IRQ; 8410 u64 val = reg->var_off.value; 8411 struct bpf_map *map = NULL; 8412 struct btf *btf = NULL; 8413 struct btf_record *rec; 8414 u32 spin_lock_off; 8415 int err; 8416 8417 if (!is_const) { 8418 verbose(env, 8419 "R%d doesn't have constant offset. %s_lock has to be at the constant offset\n", 8420 regno, lock_str); 8421 return -EINVAL; 8422 } 8423 if (reg->type == PTR_TO_MAP_VALUE) { 8424 map = reg->map_ptr; 8425 if (!map->btf) { 8426 verbose(env, 8427 "map '%s' has to have BTF in order to use %s_lock\n", 8428 map->name, lock_str); 8429 return -EINVAL; 8430 } 8431 } else { 8432 btf = reg->btf; 8433 } 8434 8435 rec = reg_btf_record(reg); 8436 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) { 8437 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local", 8438 map ? map->name : "kptr", lock_str); 8439 return -EINVAL; 8440 } 8441 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off; 8442 if (spin_lock_off != val + reg->off) { 8443 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n", 8444 val + reg->off, lock_str, spin_lock_off); 8445 return -EINVAL; 8446 } 8447 if (is_lock) { 8448 void *ptr; 8449 int type; 8450 8451 if (map) 8452 ptr = map; 8453 else 8454 ptr = btf; 8455 8456 if (!is_res_lock && cur->active_locks) { 8457 if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) { 8458 verbose(env, 8459 "Locking two bpf_spin_locks are not allowed\n"); 8460 return -EINVAL; 8461 } 8462 } else if (is_res_lock && cur->active_locks) { 8463 if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) { 8464 verbose(env, "Acquiring the same lock again, AA deadlock detected\n"); 8465 return -EINVAL; 8466 } 8467 } 8468 8469 if (is_res_lock && is_irq) 8470 type = REF_TYPE_RES_LOCK_IRQ; 8471 else if (is_res_lock) 8472 type = REF_TYPE_RES_LOCK; 8473 else 8474 type = REF_TYPE_LOCK; 8475 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr); 8476 if (err < 0) { 8477 verbose(env, "Failed to acquire lock state\n"); 8478 return err; 8479 } 8480 } else { 8481 void *ptr; 8482 int type; 8483 8484 if (map) 8485 ptr = map; 8486 else 8487 ptr = btf; 8488 8489 if (!cur->active_locks) { 8490 verbose(env, "%s_unlock without taking a lock\n", lock_str); 8491 return -EINVAL; 8492 } 8493 8494 if (is_res_lock && is_irq) 8495 type = REF_TYPE_RES_LOCK_IRQ; 8496 else if (is_res_lock) 8497 type = REF_TYPE_RES_LOCK; 8498 else 8499 type = REF_TYPE_LOCK; 8500 if (!find_lock_state(cur, type, reg->id, ptr)) { 8501 verbose(env, "%s_unlock of different lock\n", lock_str); 8502 return -EINVAL; 8503 } 8504 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) { 8505 verbose(env, "%s_unlock cannot be out of order\n", lock_str); 8506 return -EINVAL; 8507 } 8508 if (release_lock_state(cur, type, reg->id, ptr)) { 8509 verbose(env, "%s_unlock of different lock\n", lock_str); 8510 return -EINVAL; 8511 } 8512 8513 invalidate_non_owning_refs(env); 8514 } 8515 return 0; 8516 } 8517 8518 static int process_timer_func(struct bpf_verifier_env *env, int regno, 8519 struct bpf_call_arg_meta *meta) 8520 { 8521 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8522 bool is_const = tnum_is_const(reg->var_off); 8523 struct bpf_map *map = reg->map_ptr; 8524 u64 val = reg->var_off.value; 8525 8526 if (!is_const) { 8527 verbose(env, 8528 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 8529 regno); 8530 return -EINVAL; 8531 } 8532 if (!map->btf) { 8533 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 8534 map->name); 8535 return -EINVAL; 8536 } 8537 if (!btf_record_has_field(map->record, BPF_TIMER)) { 8538 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 8539 return -EINVAL; 8540 } 8541 if (map->record->timer_off != val + reg->off) { 8542 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 8543 val + reg->off, map->record->timer_off); 8544 return -EINVAL; 8545 } 8546 if (meta->map_ptr) { 8547 verifier_bug(env, "Two map pointers in a timer helper"); 8548 return -EFAULT; 8549 } 8550 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 8551 verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n"); 8552 return -EOPNOTSUPP; 8553 } 8554 meta->map_uid = reg->map_uid; 8555 meta->map_ptr = map; 8556 return 0; 8557 } 8558 8559 static int process_wq_func(struct bpf_verifier_env *env, int regno, 8560 struct bpf_kfunc_call_arg_meta *meta) 8561 { 8562 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8563 struct bpf_map *map = reg->map_ptr; 8564 u64 val = reg->var_off.value; 8565 8566 if (map->record->wq_off != val + reg->off) { 8567 verbose(env, "off %lld doesn't point to 'struct bpf_wq' that is at %d\n", 8568 val + reg->off, map->record->wq_off); 8569 return -EINVAL; 8570 } 8571 meta->map.uid = reg->map_uid; 8572 meta->map.ptr = map; 8573 return 0; 8574 } 8575 8576 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 8577 struct bpf_call_arg_meta *meta) 8578 { 8579 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8580 struct btf_field *kptr_field; 8581 struct bpf_map *map_ptr; 8582 struct btf_record *rec; 8583 u32 kptr_off; 8584 8585 if (type_is_ptr_alloc_obj(reg->type)) { 8586 rec = reg_btf_record(reg); 8587 } else { /* PTR_TO_MAP_VALUE */ 8588 map_ptr = reg->map_ptr; 8589 if (!map_ptr->btf) { 8590 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 8591 map_ptr->name); 8592 return -EINVAL; 8593 } 8594 rec = map_ptr->record; 8595 meta->map_ptr = map_ptr; 8596 } 8597 8598 if (!tnum_is_const(reg->var_off)) { 8599 verbose(env, 8600 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 8601 regno); 8602 return -EINVAL; 8603 } 8604 8605 if (!btf_record_has_field(rec, BPF_KPTR)) { 8606 verbose(env, "R%d has no valid kptr\n", regno); 8607 return -EINVAL; 8608 } 8609 8610 kptr_off = reg->off + reg->var_off.value; 8611 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 8612 if (!kptr_field) { 8613 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 8614 return -EACCES; 8615 } 8616 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 8617 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 8618 return -EACCES; 8619 } 8620 meta->kptr_field = kptr_field; 8621 return 0; 8622 } 8623 8624 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 8625 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 8626 * 8627 * In both cases we deal with the first 8 bytes, but need to mark the next 8 8628 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 8629 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 8630 * 8631 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 8632 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 8633 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 8634 * mutate the view of the dynptr and also possibly destroy it. In the latter 8635 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 8636 * memory that dynptr points to. 8637 * 8638 * The verifier will keep track both levels of mutation (bpf_dynptr's in 8639 * reg->type and the memory's in reg->dynptr.type), but there is no support for 8640 * readonly dynptr view yet, hence only the first case is tracked and checked. 8641 * 8642 * This is consistent with how C applies the const modifier to a struct object, 8643 * where the pointer itself inside bpf_dynptr becomes const but not what it 8644 * points to. 8645 * 8646 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 8647 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 8648 */ 8649 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 8650 enum bpf_arg_type arg_type, int clone_ref_obj_id) 8651 { 8652 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8653 int err; 8654 8655 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 8656 verbose(env, 8657 "arg#%d expected pointer to stack or const struct bpf_dynptr\n", 8658 regno - 1); 8659 return -EINVAL; 8660 } 8661 8662 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 8663 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 8664 */ 8665 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 8666 verifier_bug(env, "misconfigured dynptr helper type flags"); 8667 return -EFAULT; 8668 } 8669 8670 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 8671 * constructing a mutable bpf_dynptr object. 8672 * 8673 * Currently, this is only possible with PTR_TO_STACK 8674 * pointing to a region of at least 16 bytes which doesn't 8675 * contain an existing bpf_dynptr. 8676 * 8677 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 8678 * mutated or destroyed. However, the memory it points to 8679 * may be mutated. 8680 * 8681 * None - Points to a initialized dynptr that can be mutated and 8682 * destroyed, including mutation of the memory it points 8683 * to. 8684 */ 8685 if (arg_type & MEM_UNINIT) { 8686 int i; 8687 8688 if (!is_dynptr_reg_valid_uninit(env, reg)) { 8689 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 8690 return -EINVAL; 8691 } 8692 8693 /* we write BPF_DW bits (8 bytes) at a time */ 8694 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 8695 err = check_mem_access(env, insn_idx, regno, 8696 i, BPF_DW, BPF_WRITE, -1, false, false); 8697 if (err) 8698 return err; 8699 } 8700 8701 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 8702 } else /* MEM_RDONLY and None case from above */ { 8703 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 8704 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 8705 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 8706 return -EINVAL; 8707 } 8708 8709 if (!is_dynptr_reg_valid_init(env, reg)) { 8710 verbose(env, 8711 "Expected an initialized dynptr as arg #%d\n", 8712 regno - 1); 8713 return -EINVAL; 8714 } 8715 8716 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 8717 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 8718 verbose(env, 8719 "Expected a dynptr of type %s as arg #%d\n", 8720 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1); 8721 return -EINVAL; 8722 } 8723 8724 err = mark_dynptr_read(env, reg); 8725 } 8726 return err; 8727 } 8728 8729 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 8730 { 8731 struct bpf_func_state *state = func(env, reg); 8732 8733 return state->stack[spi].spilled_ptr.ref_obj_id; 8734 } 8735 8736 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8737 { 8738 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 8739 } 8740 8741 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8742 { 8743 return meta->kfunc_flags & KF_ITER_NEW; 8744 } 8745 8746 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8747 { 8748 return meta->kfunc_flags & KF_ITER_NEXT; 8749 } 8750 8751 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 8752 { 8753 return meta->kfunc_flags & KF_ITER_DESTROY; 8754 } 8755 8756 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 8757 const struct btf_param *arg) 8758 { 8759 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 8760 * kfunc is iter state pointer 8761 */ 8762 if (is_iter_kfunc(meta)) 8763 return arg_idx == 0; 8764 8765 /* iter passed as an argument to a generic kfunc */ 8766 return btf_param_match_suffix(meta->btf, arg, "__iter"); 8767 } 8768 8769 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 8770 struct bpf_kfunc_call_arg_meta *meta) 8771 { 8772 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8773 const struct btf_type *t; 8774 int spi, err, i, nr_slots, btf_id; 8775 8776 if (reg->type != PTR_TO_STACK) { 8777 verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1); 8778 return -EINVAL; 8779 } 8780 8781 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 8782 * ensures struct convention, so we wouldn't need to do any BTF 8783 * validation here. But given iter state can be passed as a parameter 8784 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 8785 * conservative here. 8786 */ 8787 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1); 8788 if (btf_id < 0) { 8789 verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1); 8790 return -EINVAL; 8791 } 8792 t = btf_type_by_id(meta->btf, btf_id); 8793 nr_slots = t->size / BPF_REG_SIZE; 8794 8795 if (is_iter_new_kfunc(meta)) { 8796 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 8797 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 8798 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 8799 iter_type_str(meta->btf, btf_id), regno - 1); 8800 return -EINVAL; 8801 } 8802 8803 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 8804 err = check_mem_access(env, insn_idx, regno, 8805 i, BPF_DW, BPF_WRITE, -1, false, false); 8806 if (err) 8807 return err; 8808 } 8809 8810 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 8811 if (err) 8812 return err; 8813 } else { 8814 /* iter_next() or iter_destroy(), as well as any kfunc 8815 * accepting iter argument, expect initialized iter state 8816 */ 8817 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 8818 switch (err) { 8819 case 0: 8820 break; 8821 case -EINVAL: 8822 verbose(env, "expected an initialized iter_%s as arg #%d\n", 8823 iter_type_str(meta->btf, btf_id), regno - 1); 8824 return err; 8825 case -EPROTO: 8826 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 8827 return err; 8828 default: 8829 return err; 8830 } 8831 8832 spi = iter_get_spi(env, reg, nr_slots); 8833 if (spi < 0) 8834 return spi; 8835 8836 err = mark_iter_read(env, reg, spi, nr_slots); 8837 if (err) 8838 return err; 8839 8840 /* remember meta->iter info for process_iter_next_call() */ 8841 meta->iter.spi = spi; 8842 meta->iter.frameno = reg->frameno; 8843 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 8844 8845 if (is_iter_destroy_kfunc(meta)) { 8846 err = unmark_stack_slots_iter(env, reg, nr_slots); 8847 if (err) 8848 return err; 8849 } 8850 } 8851 8852 return 0; 8853 } 8854 8855 /* Look for a previous loop entry at insn_idx: nearest parent state 8856 * stopped at insn_idx with callsites matching those in cur->frame. 8857 */ 8858 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 8859 struct bpf_verifier_state *cur, 8860 int insn_idx) 8861 { 8862 struct bpf_verifier_state_list *sl; 8863 struct bpf_verifier_state *st; 8864 struct list_head *pos, *head; 8865 8866 /* Explored states are pushed in stack order, most recent states come first */ 8867 head = explored_state(env, insn_idx); 8868 list_for_each(pos, head) { 8869 sl = container_of(pos, struct bpf_verifier_state_list, node); 8870 /* If st->branches != 0 state is a part of current DFS verification path, 8871 * hence cur & st for a loop. 8872 */ 8873 st = &sl->state; 8874 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 8875 st->dfs_depth < cur->dfs_depth) 8876 return st; 8877 } 8878 8879 return NULL; 8880 } 8881 8882 static void reset_idmap_scratch(struct bpf_verifier_env *env); 8883 static bool regs_exact(const struct bpf_reg_state *rold, 8884 const struct bpf_reg_state *rcur, 8885 struct bpf_idmap *idmap); 8886 8887 static void maybe_widen_reg(struct bpf_verifier_env *env, 8888 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 8889 struct bpf_idmap *idmap) 8890 { 8891 if (rold->type != SCALAR_VALUE) 8892 return; 8893 if (rold->type != rcur->type) 8894 return; 8895 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 8896 return; 8897 __mark_reg_unknown(env, rcur); 8898 } 8899 8900 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 8901 struct bpf_verifier_state *old, 8902 struct bpf_verifier_state *cur) 8903 { 8904 struct bpf_func_state *fold, *fcur; 8905 int i, fr; 8906 8907 reset_idmap_scratch(env); 8908 for (fr = old->curframe; fr >= 0; fr--) { 8909 fold = old->frame[fr]; 8910 fcur = cur->frame[fr]; 8911 8912 for (i = 0; i < MAX_BPF_REG; i++) 8913 maybe_widen_reg(env, 8914 &fold->regs[i], 8915 &fcur->regs[i], 8916 &env->idmap_scratch); 8917 8918 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 8919 if (!is_spilled_reg(&fold->stack[i]) || 8920 !is_spilled_reg(&fcur->stack[i])) 8921 continue; 8922 8923 maybe_widen_reg(env, 8924 &fold->stack[i].spilled_ptr, 8925 &fcur->stack[i].spilled_ptr, 8926 &env->idmap_scratch); 8927 } 8928 } 8929 return 0; 8930 } 8931 8932 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 8933 struct bpf_kfunc_call_arg_meta *meta) 8934 { 8935 int iter_frameno = meta->iter.frameno; 8936 int iter_spi = meta->iter.spi; 8937 8938 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8939 } 8940 8941 /* process_iter_next_call() is called when verifier gets to iterator's next 8942 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 8943 * to it as just "iter_next()" in comments below. 8944 * 8945 * BPF verifier relies on a crucial contract for any iter_next() 8946 * implementation: it should *eventually* return NULL, and once that happens 8947 * it should keep returning NULL. That is, once iterator exhausts elements to 8948 * iterate, it should never reset or spuriously return new elements. 8949 * 8950 * With the assumption of such contract, process_iter_next_call() simulates 8951 * a fork in the verifier state to validate loop logic correctness and safety 8952 * without having to simulate infinite amount of iterations. 8953 * 8954 * In current state, we first assume that iter_next() returned NULL and 8955 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 8956 * conditions we should not form an infinite loop and should eventually reach 8957 * exit. 8958 * 8959 * Besides that, we also fork current state and enqueue it for later 8960 * verification. In a forked state we keep iterator state as ACTIVE 8961 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 8962 * also bump iteration depth to prevent erroneous infinite loop detection 8963 * later on (see iter_active_depths_differ() comment for details). In this 8964 * state we assume that we'll eventually loop back to another iter_next() 8965 * calls (it could be in exactly same location or in some other instruction, 8966 * it doesn't matter, we don't make any unnecessary assumptions about this, 8967 * everything revolves around iterator state in a stack slot, not which 8968 * instruction is calling iter_next()). When that happens, we either will come 8969 * to iter_next() with equivalent state and can conclude that next iteration 8970 * will proceed in exactly the same way as we just verified, so it's safe to 8971 * assume that loop converges. If not, we'll go on another iteration 8972 * simulation with a different input state, until all possible starting states 8973 * are validated or we reach maximum number of instructions limit. 8974 * 8975 * This way, we will either exhaustively discover all possible input states 8976 * that iterator loop can start with and eventually will converge, or we'll 8977 * effectively regress into bounded loop simulation logic and either reach 8978 * maximum number of instructions if loop is not provably convergent, or there 8979 * is some statically known limit on number of iterations (e.g., if there is 8980 * an explicit `if n > 100 then break;` statement somewhere in the loop). 8981 * 8982 * Iteration convergence logic in is_state_visited() relies on exact 8983 * states comparison, which ignores read and precision marks. 8984 * This is necessary because read and precision marks are not finalized 8985 * while in the loop. Exact comparison might preclude convergence for 8986 * simple programs like below: 8987 * 8988 * i = 0; 8989 * while(iter_next(&it)) 8990 * i++; 8991 * 8992 * At each iteration step i++ would produce a new distinct state and 8993 * eventually instruction processing limit would be reached. 8994 * 8995 * To avoid such behavior speculatively forget (widen) range for 8996 * imprecise scalar registers, if those registers were not precise at the 8997 * end of the previous iteration and do not match exactly. 8998 * 8999 * This is a conservative heuristic that allows to verify wide range of programs, 9000 * however it precludes verification of programs that conjure an 9001 * imprecise value on the first loop iteration and use it as precise on a second. 9002 * For example, the following safe program would fail to verify: 9003 * 9004 * struct bpf_num_iter it; 9005 * int arr[10]; 9006 * int i = 0, a = 0; 9007 * bpf_iter_num_new(&it, 0, 10); 9008 * while (bpf_iter_num_next(&it)) { 9009 * if (a == 0) { 9010 * a = 1; 9011 * i = 7; // Because i changed verifier would forget 9012 * // it's range on second loop entry. 9013 * } else { 9014 * arr[i] = 42; // This would fail to verify. 9015 * } 9016 * } 9017 * bpf_iter_num_destroy(&it); 9018 */ 9019 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 9020 struct bpf_kfunc_call_arg_meta *meta) 9021 { 9022 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 9023 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 9024 struct bpf_reg_state *cur_iter, *queued_iter; 9025 9026 BTF_TYPE_EMIT(struct bpf_iter); 9027 9028 cur_iter = get_iter_from_state(cur_st, meta); 9029 9030 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 9031 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 9032 verifier_bug(env, "unexpected iterator state %d (%s)", 9033 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 9034 return -EFAULT; 9035 } 9036 9037 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 9038 /* Because iter_next() call is a checkpoint is_state_visitied() 9039 * should guarantee parent state with same call sites and insn_idx. 9040 */ 9041 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 9042 !same_callsites(cur_st->parent, cur_st)) { 9043 verifier_bug(env, "bad parent state for iter next call"); 9044 return -EFAULT; 9045 } 9046 /* Note cur_st->parent in the call below, it is necessary to skip 9047 * checkpoint created for cur_st by is_state_visited() 9048 * right at this instruction. 9049 */ 9050 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 9051 /* branch out active iter state */ 9052 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 9053 if (!queued_st) 9054 return -ENOMEM; 9055 9056 queued_iter = get_iter_from_state(queued_st, meta); 9057 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 9058 queued_iter->iter.depth++; 9059 if (prev_st) 9060 widen_imprecise_scalars(env, prev_st, queued_st); 9061 9062 queued_fr = queued_st->frame[queued_st->curframe]; 9063 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 9064 } 9065 9066 /* switch to DRAINED state, but keep the depth unchanged */ 9067 /* mark current iter state as drained and assume returned NULL */ 9068 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 9069 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 9070 9071 return 0; 9072 } 9073 9074 static bool arg_type_is_mem_size(enum bpf_arg_type type) 9075 { 9076 return type == ARG_CONST_SIZE || 9077 type == ARG_CONST_SIZE_OR_ZERO; 9078 } 9079 9080 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 9081 { 9082 return base_type(type) == ARG_PTR_TO_MEM && 9083 type & MEM_UNINIT; 9084 } 9085 9086 static bool arg_type_is_release(enum bpf_arg_type type) 9087 { 9088 return type & OBJ_RELEASE; 9089 } 9090 9091 static bool arg_type_is_dynptr(enum bpf_arg_type type) 9092 { 9093 return base_type(type) == ARG_PTR_TO_DYNPTR; 9094 } 9095 9096 static int resolve_map_arg_type(struct bpf_verifier_env *env, 9097 const struct bpf_call_arg_meta *meta, 9098 enum bpf_arg_type *arg_type) 9099 { 9100 if (!meta->map_ptr) { 9101 /* kernel subsystem misconfigured verifier */ 9102 verifier_bug(env, "invalid map_ptr to access map->type"); 9103 return -EFAULT; 9104 } 9105 9106 switch (meta->map_ptr->map_type) { 9107 case BPF_MAP_TYPE_SOCKMAP: 9108 case BPF_MAP_TYPE_SOCKHASH: 9109 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 9110 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 9111 } else { 9112 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 9113 return -EINVAL; 9114 } 9115 break; 9116 case BPF_MAP_TYPE_BLOOM_FILTER: 9117 if (meta->func_id == BPF_FUNC_map_peek_elem) 9118 *arg_type = ARG_PTR_TO_MAP_VALUE; 9119 break; 9120 default: 9121 break; 9122 } 9123 return 0; 9124 } 9125 9126 struct bpf_reg_types { 9127 const enum bpf_reg_type types[10]; 9128 u32 *btf_id; 9129 }; 9130 9131 static const struct bpf_reg_types sock_types = { 9132 .types = { 9133 PTR_TO_SOCK_COMMON, 9134 PTR_TO_SOCKET, 9135 PTR_TO_TCP_SOCK, 9136 PTR_TO_XDP_SOCK, 9137 }, 9138 }; 9139 9140 #ifdef CONFIG_NET 9141 static const struct bpf_reg_types btf_id_sock_common_types = { 9142 .types = { 9143 PTR_TO_SOCK_COMMON, 9144 PTR_TO_SOCKET, 9145 PTR_TO_TCP_SOCK, 9146 PTR_TO_XDP_SOCK, 9147 PTR_TO_BTF_ID, 9148 PTR_TO_BTF_ID | PTR_TRUSTED, 9149 }, 9150 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 9151 }; 9152 #endif 9153 9154 static const struct bpf_reg_types mem_types = { 9155 .types = { 9156 PTR_TO_STACK, 9157 PTR_TO_PACKET, 9158 PTR_TO_PACKET_META, 9159 PTR_TO_MAP_KEY, 9160 PTR_TO_MAP_VALUE, 9161 PTR_TO_MEM, 9162 PTR_TO_MEM | MEM_RINGBUF, 9163 PTR_TO_BUF, 9164 PTR_TO_BTF_ID | PTR_TRUSTED, 9165 }, 9166 }; 9167 9168 static const struct bpf_reg_types spin_lock_types = { 9169 .types = { 9170 PTR_TO_MAP_VALUE, 9171 PTR_TO_BTF_ID | MEM_ALLOC, 9172 } 9173 }; 9174 9175 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 9176 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 9177 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 9178 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 9179 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 9180 static const struct bpf_reg_types btf_ptr_types = { 9181 .types = { 9182 PTR_TO_BTF_ID, 9183 PTR_TO_BTF_ID | PTR_TRUSTED, 9184 PTR_TO_BTF_ID | MEM_RCU, 9185 }, 9186 }; 9187 static const struct bpf_reg_types percpu_btf_ptr_types = { 9188 .types = { 9189 PTR_TO_BTF_ID | MEM_PERCPU, 9190 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 9191 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 9192 } 9193 }; 9194 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 9195 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 9196 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 9197 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 9198 static const struct bpf_reg_types kptr_xchg_dest_types = { 9199 .types = { 9200 PTR_TO_MAP_VALUE, 9201 PTR_TO_BTF_ID | MEM_ALLOC 9202 } 9203 }; 9204 static const struct bpf_reg_types dynptr_types = { 9205 .types = { 9206 PTR_TO_STACK, 9207 CONST_PTR_TO_DYNPTR, 9208 } 9209 }; 9210 9211 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 9212 [ARG_PTR_TO_MAP_KEY] = &mem_types, 9213 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 9214 [ARG_CONST_SIZE] = &scalar_types, 9215 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 9216 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 9217 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 9218 [ARG_PTR_TO_CTX] = &context_types, 9219 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 9220 #ifdef CONFIG_NET 9221 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 9222 #endif 9223 [ARG_PTR_TO_SOCKET] = &fullsock_types, 9224 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 9225 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 9226 [ARG_PTR_TO_MEM] = &mem_types, 9227 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 9228 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 9229 [ARG_PTR_TO_FUNC] = &func_ptr_types, 9230 [ARG_PTR_TO_STACK] = &stack_ptr_types, 9231 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 9232 [ARG_PTR_TO_TIMER] = &timer_types, 9233 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 9234 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 9235 }; 9236 9237 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 9238 enum bpf_arg_type arg_type, 9239 const u32 *arg_btf_id, 9240 struct bpf_call_arg_meta *meta) 9241 { 9242 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 9243 enum bpf_reg_type expected, type = reg->type; 9244 const struct bpf_reg_types *compatible; 9245 int i, j; 9246 9247 compatible = compatible_reg_types[base_type(arg_type)]; 9248 if (!compatible) { 9249 verifier_bug(env, "unsupported arg type %d", arg_type); 9250 return -EFAULT; 9251 } 9252 9253 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 9254 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 9255 * 9256 * Same for MAYBE_NULL: 9257 * 9258 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 9259 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 9260 * 9261 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 9262 * 9263 * Therefore we fold these flags depending on the arg_type before comparison. 9264 */ 9265 if (arg_type & MEM_RDONLY) 9266 type &= ~MEM_RDONLY; 9267 if (arg_type & PTR_MAYBE_NULL) 9268 type &= ~PTR_MAYBE_NULL; 9269 if (base_type(arg_type) == ARG_PTR_TO_MEM) 9270 type &= ~DYNPTR_TYPE_FLAG_MASK; 9271 9272 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 9273 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) { 9274 type &= ~MEM_ALLOC; 9275 type &= ~MEM_PERCPU; 9276 } 9277 9278 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 9279 expected = compatible->types[i]; 9280 if (expected == NOT_INIT) 9281 break; 9282 9283 if (type == expected) 9284 goto found; 9285 } 9286 9287 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 9288 for (j = 0; j + 1 < i; j++) 9289 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 9290 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 9291 return -EACCES; 9292 9293 found: 9294 if (base_type(reg->type) != PTR_TO_BTF_ID) 9295 return 0; 9296 9297 if (compatible == &mem_types) { 9298 if (!(arg_type & MEM_RDONLY)) { 9299 verbose(env, 9300 "%s() may write into memory pointed by R%d type=%s\n", 9301 func_id_name(meta->func_id), 9302 regno, reg_type_str(env, reg->type)); 9303 return -EACCES; 9304 } 9305 return 0; 9306 } 9307 9308 switch ((int)reg->type) { 9309 case PTR_TO_BTF_ID: 9310 case PTR_TO_BTF_ID | PTR_TRUSTED: 9311 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 9312 case PTR_TO_BTF_ID | MEM_RCU: 9313 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 9314 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 9315 { 9316 /* For bpf_sk_release, it needs to match against first member 9317 * 'struct sock_common', hence make an exception for it. This 9318 * allows bpf_sk_release to work for multiple socket types. 9319 */ 9320 bool strict_type_match = arg_type_is_release(arg_type) && 9321 meta->func_id != BPF_FUNC_sk_release; 9322 9323 if (type_may_be_null(reg->type) && 9324 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 9325 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 9326 return -EACCES; 9327 } 9328 9329 if (!arg_btf_id) { 9330 if (!compatible->btf_id) { 9331 verifier_bug(env, "missing arg compatible BTF ID"); 9332 return -EFAULT; 9333 } 9334 arg_btf_id = compatible->btf_id; 9335 } 9336 9337 if (meta->func_id == BPF_FUNC_kptr_xchg) { 9338 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 9339 return -EACCES; 9340 } else { 9341 if (arg_btf_id == BPF_PTR_POISON) { 9342 verbose(env, "verifier internal error:"); 9343 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 9344 regno); 9345 return -EACCES; 9346 } 9347 9348 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 9349 btf_vmlinux, *arg_btf_id, 9350 strict_type_match)) { 9351 verbose(env, "R%d is of type %s but %s is expected\n", 9352 regno, btf_type_name(reg->btf, reg->btf_id), 9353 btf_type_name(btf_vmlinux, *arg_btf_id)); 9354 return -EACCES; 9355 } 9356 } 9357 break; 9358 } 9359 case PTR_TO_BTF_ID | MEM_ALLOC: 9360 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 9361 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 9362 meta->func_id != BPF_FUNC_kptr_xchg) { 9363 verifier_bug(env, "unimplemented handling of MEM_ALLOC"); 9364 return -EFAULT; 9365 } 9366 /* Check if local kptr in src arg matches kptr in dst arg */ 9367 if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) { 9368 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 9369 return -EACCES; 9370 } 9371 break; 9372 case PTR_TO_BTF_ID | MEM_PERCPU: 9373 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 9374 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 9375 /* Handled by helper specific checks */ 9376 break; 9377 default: 9378 verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match"); 9379 return -EFAULT; 9380 } 9381 return 0; 9382 } 9383 9384 static struct btf_field * 9385 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 9386 { 9387 struct btf_field *field; 9388 struct btf_record *rec; 9389 9390 rec = reg_btf_record(reg); 9391 if (!rec) 9392 return NULL; 9393 9394 field = btf_record_find(rec, off, fields); 9395 if (!field) 9396 return NULL; 9397 9398 return field; 9399 } 9400 9401 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 9402 const struct bpf_reg_state *reg, int regno, 9403 enum bpf_arg_type arg_type) 9404 { 9405 u32 type = reg->type; 9406 9407 /* When referenced register is passed to release function, its fixed 9408 * offset must be 0. 9409 * 9410 * We will check arg_type_is_release reg has ref_obj_id when storing 9411 * meta->release_regno. 9412 */ 9413 if (arg_type_is_release(arg_type)) { 9414 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 9415 * may not directly point to the object being released, but to 9416 * dynptr pointing to such object, which might be at some offset 9417 * on the stack. In that case, we simply to fallback to the 9418 * default handling. 9419 */ 9420 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 9421 return 0; 9422 9423 /* Doing check_ptr_off_reg check for the offset will catch this 9424 * because fixed_off_ok is false, but checking here allows us 9425 * to give the user a better error message. 9426 */ 9427 if (reg->off) { 9428 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 9429 regno); 9430 return -EINVAL; 9431 } 9432 return __check_ptr_off_reg(env, reg, regno, false); 9433 } 9434 9435 switch (type) { 9436 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 9437 case PTR_TO_STACK: 9438 case PTR_TO_PACKET: 9439 case PTR_TO_PACKET_META: 9440 case PTR_TO_MAP_KEY: 9441 case PTR_TO_MAP_VALUE: 9442 case PTR_TO_MEM: 9443 case PTR_TO_MEM | MEM_RDONLY: 9444 case PTR_TO_MEM | MEM_RINGBUF: 9445 case PTR_TO_BUF: 9446 case PTR_TO_BUF | MEM_RDONLY: 9447 case PTR_TO_ARENA: 9448 case SCALAR_VALUE: 9449 return 0; 9450 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 9451 * fixed offset. 9452 */ 9453 case PTR_TO_BTF_ID: 9454 case PTR_TO_BTF_ID | MEM_ALLOC: 9455 case PTR_TO_BTF_ID | PTR_TRUSTED: 9456 case PTR_TO_BTF_ID | MEM_RCU: 9457 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 9458 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 9459 /* When referenced PTR_TO_BTF_ID is passed to release function, 9460 * its fixed offset must be 0. In the other cases, fixed offset 9461 * can be non-zero. This was already checked above. So pass 9462 * fixed_off_ok as true to allow fixed offset for all other 9463 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 9464 * still need to do checks instead of returning. 9465 */ 9466 return __check_ptr_off_reg(env, reg, regno, true); 9467 default: 9468 return __check_ptr_off_reg(env, reg, regno, false); 9469 } 9470 } 9471 9472 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 9473 const struct bpf_func_proto *fn, 9474 struct bpf_reg_state *regs) 9475 { 9476 struct bpf_reg_state *state = NULL; 9477 int i; 9478 9479 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 9480 if (arg_type_is_dynptr(fn->arg_type[i])) { 9481 if (state) { 9482 verbose(env, "verifier internal error: multiple dynptr args\n"); 9483 return NULL; 9484 } 9485 state = ®s[BPF_REG_1 + i]; 9486 } 9487 9488 if (!state) 9489 verbose(env, "verifier internal error: no dynptr arg found\n"); 9490 9491 return state; 9492 } 9493 9494 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 9495 { 9496 struct bpf_func_state *state = func(env, reg); 9497 int spi; 9498 9499 if (reg->type == CONST_PTR_TO_DYNPTR) 9500 return reg->id; 9501 spi = dynptr_get_spi(env, reg); 9502 if (spi < 0) 9503 return spi; 9504 return state->stack[spi].spilled_ptr.id; 9505 } 9506 9507 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 9508 { 9509 struct bpf_func_state *state = func(env, reg); 9510 int spi; 9511 9512 if (reg->type == CONST_PTR_TO_DYNPTR) 9513 return reg->ref_obj_id; 9514 spi = dynptr_get_spi(env, reg); 9515 if (spi < 0) 9516 return spi; 9517 return state->stack[spi].spilled_ptr.ref_obj_id; 9518 } 9519 9520 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 9521 struct bpf_reg_state *reg) 9522 { 9523 struct bpf_func_state *state = func(env, reg); 9524 int spi; 9525 9526 if (reg->type == CONST_PTR_TO_DYNPTR) 9527 return reg->dynptr.type; 9528 9529 spi = __get_spi(reg->off); 9530 if (spi < 0) { 9531 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 9532 return BPF_DYNPTR_TYPE_INVALID; 9533 } 9534 9535 return state->stack[spi].spilled_ptr.dynptr.type; 9536 } 9537 9538 static int check_reg_const_str(struct bpf_verifier_env *env, 9539 struct bpf_reg_state *reg, u32 regno) 9540 { 9541 struct bpf_map *map = reg->map_ptr; 9542 int err; 9543 int map_off; 9544 u64 map_addr; 9545 char *str_ptr; 9546 9547 if (reg->type != PTR_TO_MAP_VALUE) 9548 return -EINVAL; 9549 9550 if (!bpf_map_is_rdonly(map)) { 9551 verbose(env, "R%d does not point to a readonly map'\n", regno); 9552 return -EACCES; 9553 } 9554 9555 if (!tnum_is_const(reg->var_off)) { 9556 verbose(env, "R%d is not a constant address'\n", regno); 9557 return -EACCES; 9558 } 9559 9560 if (!map->ops->map_direct_value_addr) { 9561 verbose(env, "no direct value access support for this map type\n"); 9562 return -EACCES; 9563 } 9564 9565 err = check_map_access(env, regno, reg->off, 9566 map->value_size - reg->off, false, 9567 ACCESS_HELPER); 9568 if (err) 9569 return err; 9570 9571 map_off = reg->off + reg->var_off.value; 9572 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 9573 if (err) { 9574 verbose(env, "direct value access on string failed\n"); 9575 return err; 9576 } 9577 9578 str_ptr = (char *)(long)(map_addr); 9579 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 9580 verbose(env, "string is not zero-terminated\n"); 9581 return -EINVAL; 9582 } 9583 return 0; 9584 } 9585 9586 /* Returns constant key value in `value` if possible, else negative error */ 9587 static int get_constant_map_key(struct bpf_verifier_env *env, 9588 struct bpf_reg_state *key, 9589 u32 key_size, 9590 s64 *value) 9591 { 9592 struct bpf_func_state *state = func(env, key); 9593 struct bpf_reg_state *reg; 9594 int slot, spi, off; 9595 int spill_size = 0; 9596 int zero_size = 0; 9597 int stack_off; 9598 int i, err; 9599 u8 *stype; 9600 9601 if (!env->bpf_capable) 9602 return -EOPNOTSUPP; 9603 if (key->type != PTR_TO_STACK) 9604 return -EOPNOTSUPP; 9605 if (!tnum_is_const(key->var_off)) 9606 return -EOPNOTSUPP; 9607 9608 stack_off = key->off + key->var_off.value; 9609 slot = -stack_off - 1; 9610 spi = slot / BPF_REG_SIZE; 9611 off = slot % BPF_REG_SIZE; 9612 stype = state->stack[spi].slot_type; 9613 9614 /* First handle precisely tracked STACK_ZERO */ 9615 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) 9616 zero_size++; 9617 if (zero_size >= key_size) { 9618 *value = 0; 9619 return 0; 9620 } 9621 9622 /* Check that stack contains a scalar spill of expected size */ 9623 if (!is_spilled_scalar_reg(&state->stack[spi])) 9624 return -EOPNOTSUPP; 9625 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) 9626 spill_size++; 9627 if (spill_size != key_size) 9628 return -EOPNOTSUPP; 9629 9630 reg = &state->stack[spi].spilled_ptr; 9631 if (!tnum_is_const(reg->var_off)) 9632 /* Stack value not statically known */ 9633 return -EOPNOTSUPP; 9634 9635 /* We are relying on a constant value. So mark as precise 9636 * to prevent pruning on it. 9637 */ 9638 bt_set_frame_slot(&env->bt, key->frameno, spi); 9639 err = mark_chain_precision_batch(env, env->cur_state); 9640 if (err < 0) 9641 return err; 9642 9643 *value = reg->var_off.value; 9644 return 0; 9645 } 9646 9647 static bool can_elide_value_nullness(enum bpf_map_type type); 9648 9649 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 9650 struct bpf_call_arg_meta *meta, 9651 const struct bpf_func_proto *fn, 9652 int insn_idx) 9653 { 9654 u32 regno = BPF_REG_1 + arg; 9655 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 9656 enum bpf_arg_type arg_type = fn->arg_type[arg]; 9657 enum bpf_reg_type type = reg->type; 9658 u32 *arg_btf_id = NULL; 9659 u32 key_size; 9660 int err = 0; 9661 9662 if (arg_type == ARG_DONTCARE) 9663 return 0; 9664 9665 err = check_reg_arg(env, regno, SRC_OP); 9666 if (err) 9667 return err; 9668 9669 if (arg_type == ARG_ANYTHING) { 9670 if (is_pointer_value(env, regno)) { 9671 verbose(env, "R%d leaks addr into helper function\n", 9672 regno); 9673 return -EACCES; 9674 } 9675 return 0; 9676 } 9677 9678 if (type_is_pkt_pointer(type) && 9679 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 9680 verbose(env, "helper access to the packet is not allowed\n"); 9681 return -EACCES; 9682 } 9683 9684 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 9685 err = resolve_map_arg_type(env, meta, &arg_type); 9686 if (err) 9687 return err; 9688 } 9689 9690 if (register_is_null(reg) && type_may_be_null(arg_type)) 9691 /* A NULL register has a SCALAR_VALUE type, so skip 9692 * type checking. 9693 */ 9694 goto skip_type_check; 9695 9696 /* arg_btf_id and arg_size are in a union. */ 9697 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 9698 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 9699 arg_btf_id = fn->arg_btf_id[arg]; 9700 9701 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 9702 if (err) 9703 return err; 9704 9705 err = check_func_arg_reg_off(env, reg, regno, arg_type); 9706 if (err) 9707 return err; 9708 9709 skip_type_check: 9710 if (arg_type_is_release(arg_type)) { 9711 if (arg_type_is_dynptr(arg_type)) { 9712 struct bpf_func_state *state = func(env, reg); 9713 int spi; 9714 9715 /* Only dynptr created on stack can be released, thus 9716 * the get_spi and stack state checks for spilled_ptr 9717 * should only be done before process_dynptr_func for 9718 * PTR_TO_STACK. 9719 */ 9720 if (reg->type == PTR_TO_STACK) { 9721 spi = dynptr_get_spi(env, reg); 9722 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 9723 verbose(env, "arg %d is an unacquired reference\n", regno); 9724 return -EINVAL; 9725 } 9726 } else { 9727 verbose(env, "cannot release unowned const bpf_dynptr\n"); 9728 return -EINVAL; 9729 } 9730 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 9731 verbose(env, "R%d must be referenced when passed to release function\n", 9732 regno); 9733 return -EINVAL; 9734 } 9735 if (meta->release_regno) { 9736 verifier_bug(env, "more than one release argument"); 9737 return -EFAULT; 9738 } 9739 meta->release_regno = regno; 9740 } 9741 9742 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) { 9743 if (meta->ref_obj_id) { 9744 verbose(env, "more than one arg with ref_obj_id R%d %u %u", 9745 regno, reg->ref_obj_id, 9746 meta->ref_obj_id); 9747 return -EACCES; 9748 } 9749 meta->ref_obj_id = reg->ref_obj_id; 9750 } 9751 9752 switch (base_type(arg_type)) { 9753 case ARG_CONST_MAP_PTR: 9754 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 9755 if (meta->map_ptr) { 9756 /* Use map_uid (which is unique id of inner map) to reject: 9757 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 9758 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 9759 * if (inner_map1 && inner_map2) { 9760 * timer = bpf_map_lookup_elem(inner_map1); 9761 * if (timer) 9762 * // mismatch would have been allowed 9763 * bpf_timer_init(timer, inner_map2); 9764 * } 9765 * 9766 * Comparing map_ptr is enough to distinguish normal and outer maps. 9767 */ 9768 if (meta->map_ptr != reg->map_ptr || 9769 meta->map_uid != reg->map_uid) { 9770 verbose(env, 9771 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 9772 meta->map_uid, reg->map_uid); 9773 return -EINVAL; 9774 } 9775 } 9776 meta->map_ptr = reg->map_ptr; 9777 meta->map_uid = reg->map_uid; 9778 break; 9779 case ARG_PTR_TO_MAP_KEY: 9780 /* bpf_map_xxx(..., map_ptr, ..., key) call: 9781 * check that [key, key + map->key_size) are within 9782 * stack limits and initialized 9783 */ 9784 if (!meta->map_ptr) { 9785 /* in function declaration map_ptr must come before 9786 * map_key, so that it's verified and known before 9787 * we have to check map_key here. Otherwise it means 9788 * that kernel subsystem misconfigured verifier 9789 */ 9790 verifier_bug(env, "invalid map_ptr to access map->key"); 9791 return -EFAULT; 9792 } 9793 key_size = meta->map_ptr->key_size; 9794 err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL); 9795 if (err) 9796 return err; 9797 if (can_elide_value_nullness(meta->map_ptr->map_type)) { 9798 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key); 9799 if (err < 0) { 9800 meta->const_map_key = -1; 9801 if (err == -EOPNOTSUPP) 9802 err = 0; 9803 else 9804 return err; 9805 } 9806 } 9807 break; 9808 case ARG_PTR_TO_MAP_VALUE: 9809 if (type_may_be_null(arg_type) && register_is_null(reg)) 9810 return 0; 9811 9812 /* bpf_map_xxx(..., map_ptr, ..., value) call: 9813 * check [value, value + map->value_size) validity 9814 */ 9815 if (!meta->map_ptr) { 9816 /* kernel subsystem misconfigured verifier */ 9817 verifier_bug(env, "invalid map_ptr to access map->value"); 9818 return -EFAULT; 9819 } 9820 meta->raw_mode = arg_type & MEM_UNINIT; 9821 err = check_helper_mem_access(env, regno, meta->map_ptr->value_size, 9822 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 9823 false, meta); 9824 break; 9825 case ARG_PTR_TO_PERCPU_BTF_ID: 9826 if (!reg->btf_id) { 9827 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 9828 return -EACCES; 9829 } 9830 meta->ret_btf = reg->btf; 9831 meta->ret_btf_id = reg->btf_id; 9832 break; 9833 case ARG_PTR_TO_SPIN_LOCK: 9834 if (in_rbtree_lock_required_cb(env)) { 9835 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 9836 return -EACCES; 9837 } 9838 if (meta->func_id == BPF_FUNC_spin_lock) { 9839 err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK); 9840 if (err) 9841 return err; 9842 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 9843 err = process_spin_lock(env, regno, 0); 9844 if (err) 9845 return err; 9846 } else { 9847 verifier_bug(env, "spin lock arg on unexpected helper"); 9848 return -EFAULT; 9849 } 9850 break; 9851 case ARG_PTR_TO_TIMER: 9852 err = process_timer_func(env, regno, meta); 9853 if (err) 9854 return err; 9855 break; 9856 case ARG_PTR_TO_FUNC: 9857 meta->subprogno = reg->subprogno; 9858 break; 9859 case ARG_PTR_TO_MEM: 9860 /* The access to this pointer is only checked when we hit the 9861 * next is_mem_size argument below. 9862 */ 9863 meta->raw_mode = arg_type & MEM_UNINIT; 9864 if (arg_type & MEM_FIXED_SIZE) { 9865 err = check_helper_mem_access(env, regno, fn->arg_size[arg], 9866 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 9867 false, meta); 9868 if (err) 9869 return err; 9870 if (arg_type & MEM_ALIGNED) 9871 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 9872 } 9873 break; 9874 case ARG_CONST_SIZE: 9875 err = check_mem_size_reg(env, reg, regno, 9876 fn->arg_type[arg - 1] & MEM_WRITE ? 9877 BPF_WRITE : BPF_READ, 9878 false, meta); 9879 break; 9880 case ARG_CONST_SIZE_OR_ZERO: 9881 err = check_mem_size_reg(env, reg, regno, 9882 fn->arg_type[arg - 1] & MEM_WRITE ? 9883 BPF_WRITE : BPF_READ, 9884 true, meta); 9885 break; 9886 case ARG_PTR_TO_DYNPTR: 9887 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 9888 if (err) 9889 return err; 9890 break; 9891 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 9892 if (!tnum_is_const(reg->var_off)) { 9893 verbose(env, "R%d is not a known constant'\n", 9894 regno); 9895 return -EACCES; 9896 } 9897 meta->mem_size = reg->var_off.value; 9898 err = mark_chain_precision(env, regno); 9899 if (err) 9900 return err; 9901 break; 9902 case ARG_PTR_TO_CONST_STR: 9903 { 9904 err = check_reg_const_str(env, reg, regno); 9905 if (err) 9906 return err; 9907 break; 9908 } 9909 case ARG_KPTR_XCHG_DEST: 9910 err = process_kptr_func(env, regno, meta); 9911 if (err) 9912 return err; 9913 break; 9914 } 9915 9916 return err; 9917 } 9918 9919 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 9920 { 9921 enum bpf_attach_type eatype = env->prog->expected_attach_type; 9922 enum bpf_prog_type type = resolve_prog_type(env->prog); 9923 9924 if (func_id != BPF_FUNC_map_update_elem && 9925 func_id != BPF_FUNC_map_delete_elem) 9926 return false; 9927 9928 /* It's not possible to get access to a locked struct sock in these 9929 * contexts, so updating is safe. 9930 */ 9931 switch (type) { 9932 case BPF_PROG_TYPE_TRACING: 9933 if (eatype == BPF_TRACE_ITER) 9934 return true; 9935 break; 9936 case BPF_PROG_TYPE_SOCK_OPS: 9937 /* map_update allowed only via dedicated helpers with event type checks */ 9938 if (func_id == BPF_FUNC_map_delete_elem) 9939 return true; 9940 break; 9941 case BPF_PROG_TYPE_SOCKET_FILTER: 9942 case BPF_PROG_TYPE_SCHED_CLS: 9943 case BPF_PROG_TYPE_SCHED_ACT: 9944 case BPF_PROG_TYPE_XDP: 9945 case BPF_PROG_TYPE_SK_REUSEPORT: 9946 case BPF_PROG_TYPE_FLOW_DISSECTOR: 9947 case BPF_PROG_TYPE_SK_LOOKUP: 9948 return true; 9949 default: 9950 break; 9951 } 9952 9953 verbose(env, "cannot update sockmap in this context\n"); 9954 return false; 9955 } 9956 9957 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 9958 { 9959 return env->prog->jit_requested && 9960 bpf_jit_supports_subprog_tailcalls(); 9961 } 9962 9963 static int check_map_func_compatibility(struct bpf_verifier_env *env, 9964 struct bpf_map *map, int func_id) 9965 { 9966 if (!map) 9967 return 0; 9968 9969 /* We need a two way check, first is from map perspective ... */ 9970 switch (map->map_type) { 9971 case BPF_MAP_TYPE_PROG_ARRAY: 9972 if (func_id != BPF_FUNC_tail_call) 9973 goto error; 9974 break; 9975 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 9976 if (func_id != BPF_FUNC_perf_event_read && 9977 func_id != BPF_FUNC_perf_event_output && 9978 func_id != BPF_FUNC_skb_output && 9979 func_id != BPF_FUNC_perf_event_read_value && 9980 func_id != BPF_FUNC_xdp_output) 9981 goto error; 9982 break; 9983 case BPF_MAP_TYPE_RINGBUF: 9984 if (func_id != BPF_FUNC_ringbuf_output && 9985 func_id != BPF_FUNC_ringbuf_reserve && 9986 func_id != BPF_FUNC_ringbuf_query && 9987 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 9988 func_id != BPF_FUNC_ringbuf_submit_dynptr && 9989 func_id != BPF_FUNC_ringbuf_discard_dynptr) 9990 goto error; 9991 break; 9992 case BPF_MAP_TYPE_USER_RINGBUF: 9993 if (func_id != BPF_FUNC_user_ringbuf_drain) 9994 goto error; 9995 break; 9996 case BPF_MAP_TYPE_STACK_TRACE: 9997 if (func_id != BPF_FUNC_get_stackid) 9998 goto error; 9999 break; 10000 case BPF_MAP_TYPE_CGROUP_ARRAY: 10001 if (func_id != BPF_FUNC_skb_under_cgroup && 10002 func_id != BPF_FUNC_current_task_under_cgroup) 10003 goto error; 10004 break; 10005 case BPF_MAP_TYPE_CGROUP_STORAGE: 10006 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 10007 if (func_id != BPF_FUNC_get_local_storage) 10008 goto error; 10009 break; 10010 case BPF_MAP_TYPE_DEVMAP: 10011 case BPF_MAP_TYPE_DEVMAP_HASH: 10012 if (func_id != BPF_FUNC_redirect_map && 10013 func_id != BPF_FUNC_map_lookup_elem) 10014 goto error; 10015 break; 10016 /* Restrict bpf side of cpumap and xskmap, open when use-cases 10017 * appear. 10018 */ 10019 case BPF_MAP_TYPE_CPUMAP: 10020 if (func_id != BPF_FUNC_redirect_map) 10021 goto error; 10022 break; 10023 case BPF_MAP_TYPE_XSKMAP: 10024 if (func_id != BPF_FUNC_redirect_map && 10025 func_id != BPF_FUNC_map_lookup_elem) 10026 goto error; 10027 break; 10028 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 10029 case BPF_MAP_TYPE_HASH_OF_MAPS: 10030 if (func_id != BPF_FUNC_map_lookup_elem) 10031 goto error; 10032 break; 10033 case BPF_MAP_TYPE_SOCKMAP: 10034 if (func_id != BPF_FUNC_sk_redirect_map && 10035 func_id != BPF_FUNC_sock_map_update && 10036 func_id != BPF_FUNC_msg_redirect_map && 10037 func_id != BPF_FUNC_sk_select_reuseport && 10038 func_id != BPF_FUNC_map_lookup_elem && 10039 !may_update_sockmap(env, func_id)) 10040 goto error; 10041 break; 10042 case BPF_MAP_TYPE_SOCKHASH: 10043 if (func_id != BPF_FUNC_sk_redirect_hash && 10044 func_id != BPF_FUNC_sock_hash_update && 10045 func_id != BPF_FUNC_msg_redirect_hash && 10046 func_id != BPF_FUNC_sk_select_reuseport && 10047 func_id != BPF_FUNC_map_lookup_elem && 10048 !may_update_sockmap(env, func_id)) 10049 goto error; 10050 break; 10051 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 10052 if (func_id != BPF_FUNC_sk_select_reuseport) 10053 goto error; 10054 break; 10055 case BPF_MAP_TYPE_QUEUE: 10056 case BPF_MAP_TYPE_STACK: 10057 if (func_id != BPF_FUNC_map_peek_elem && 10058 func_id != BPF_FUNC_map_pop_elem && 10059 func_id != BPF_FUNC_map_push_elem) 10060 goto error; 10061 break; 10062 case BPF_MAP_TYPE_SK_STORAGE: 10063 if (func_id != BPF_FUNC_sk_storage_get && 10064 func_id != BPF_FUNC_sk_storage_delete && 10065 func_id != BPF_FUNC_kptr_xchg) 10066 goto error; 10067 break; 10068 case BPF_MAP_TYPE_INODE_STORAGE: 10069 if (func_id != BPF_FUNC_inode_storage_get && 10070 func_id != BPF_FUNC_inode_storage_delete && 10071 func_id != BPF_FUNC_kptr_xchg) 10072 goto error; 10073 break; 10074 case BPF_MAP_TYPE_TASK_STORAGE: 10075 if (func_id != BPF_FUNC_task_storage_get && 10076 func_id != BPF_FUNC_task_storage_delete && 10077 func_id != BPF_FUNC_kptr_xchg) 10078 goto error; 10079 break; 10080 case BPF_MAP_TYPE_CGRP_STORAGE: 10081 if (func_id != BPF_FUNC_cgrp_storage_get && 10082 func_id != BPF_FUNC_cgrp_storage_delete && 10083 func_id != BPF_FUNC_kptr_xchg) 10084 goto error; 10085 break; 10086 case BPF_MAP_TYPE_BLOOM_FILTER: 10087 if (func_id != BPF_FUNC_map_peek_elem && 10088 func_id != BPF_FUNC_map_push_elem) 10089 goto error; 10090 break; 10091 default: 10092 break; 10093 } 10094 10095 /* ... and second from the function itself. */ 10096 switch (func_id) { 10097 case BPF_FUNC_tail_call: 10098 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 10099 goto error; 10100 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 10101 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n"); 10102 return -EINVAL; 10103 } 10104 break; 10105 case BPF_FUNC_perf_event_read: 10106 case BPF_FUNC_perf_event_output: 10107 case BPF_FUNC_perf_event_read_value: 10108 case BPF_FUNC_skb_output: 10109 case BPF_FUNC_xdp_output: 10110 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 10111 goto error; 10112 break; 10113 case BPF_FUNC_ringbuf_output: 10114 case BPF_FUNC_ringbuf_reserve: 10115 case BPF_FUNC_ringbuf_query: 10116 case BPF_FUNC_ringbuf_reserve_dynptr: 10117 case BPF_FUNC_ringbuf_submit_dynptr: 10118 case BPF_FUNC_ringbuf_discard_dynptr: 10119 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 10120 goto error; 10121 break; 10122 case BPF_FUNC_user_ringbuf_drain: 10123 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 10124 goto error; 10125 break; 10126 case BPF_FUNC_get_stackid: 10127 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 10128 goto error; 10129 break; 10130 case BPF_FUNC_current_task_under_cgroup: 10131 case BPF_FUNC_skb_under_cgroup: 10132 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 10133 goto error; 10134 break; 10135 case BPF_FUNC_redirect_map: 10136 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 10137 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 10138 map->map_type != BPF_MAP_TYPE_CPUMAP && 10139 map->map_type != BPF_MAP_TYPE_XSKMAP) 10140 goto error; 10141 break; 10142 case BPF_FUNC_sk_redirect_map: 10143 case BPF_FUNC_msg_redirect_map: 10144 case BPF_FUNC_sock_map_update: 10145 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 10146 goto error; 10147 break; 10148 case BPF_FUNC_sk_redirect_hash: 10149 case BPF_FUNC_msg_redirect_hash: 10150 case BPF_FUNC_sock_hash_update: 10151 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 10152 goto error; 10153 break; 10154 case BPF_FUNC_get_local_storage: 10155 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 10156 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 10157 goto error; 10158 break; 10159 case BPF_FUNC_sk_select_reuseport: 10160 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 10161 map->map_type != BPF_MAP_TYPE_SOCKMAP && 10162 map->map_type != BPF_MAP_TYPE_SOCKHASH) 10163 goto error; 10164 break; 10165 case BPF_FUNC_map_pop_elem: 10166 if (map->map_type != BPF_MAP_TYPE_QUEUE && 10167 map->map_type != BPF_MAP_TYPE_STACK) 10168 goto error; 10169 break; 10170 case BPF_FUNC_map_peek_elem: 10171 case BPF_FUNC_map_push_elem: 10172 if (map->map_type != BPF_MAP_TYPE_QUEUE && 10173 map->map_type != BPF_MAP_TYPE_STACK && 10174 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 10175 goto error; 10176 break; 10177 case BPF_FUNC_map_lookup_percpu_elem: 10178 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 10179 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 10180 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 10181 goto error; 10182 break; 10183 case BPF_FUNC_sk_storage_get: 10184 case BPF_FUNC_sk_storage_delete: 10185 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 10186 goto error; 10187 break; 10188 case BPF_FUNC_inode_storage_get: 10189 case BPF_FUNC_inode_storage_delete: 10190 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 10191 goto error; 10192 break; 10193 case BPF_FUNC_task_storage_get: 10194 case BPF_FUNC_task_storage_delete: 10195 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 10196 goto error; 10197 break; 10198 case BPF_FUNC_cgrp_storage_get: 10199 case BPF_FUNC_cgrp_storage_delete: 10200 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 10201 goto error; 10202 break; 10203 default: 10204 break; 10205 } 10206 10207 return 0; 10208 error: 10209 verbose(env, "cannot pass map_type %d into func %s#%d\n", 10210 map->map_type, func_id_name(func_id), func_id); 10211 return -EINVAL; 10212 } 10213 10214 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 10215 { 10216 int count = 0; 10217 10218 if (arg_type_is_raw_mem(fn->arg1_type)) 10219 count++; 10220 if (arg_type_is_raw_mem(fn->arg2_type)) 10221 count++; 10222 if (arg_type_is_raw_mem(fn->arg3_type)) 10223 count++; 10224 if (arg_type_is_raw_mem(fn->arg4_type)) 10225 count++; 10226 if (arg_type_is_raw_mem(fn->arg5_type)) 10227 count++; 10228 10229 /* We only support one arg being in raw mode at the moment, 10230 * which is sufficient for the helper functions we have 10231 * right now. 10232 */ 10233 return count <= 1; 10234 } 10235 10236 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 10237 { 10238 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 10239 bool has_size = fn->arg_size[arg] != 0; 10240 bool is_next_size = false; 10241 10242 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 10243 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 10244 10245 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 10246 return is_next_size; 10247 10248 return has_size == is_next_size || is_next_size == is_fixed; 10249 } 10250 10251 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 10252 { 10253 /* bpf_xxx(..., buf, len) call will access 'len' 10254 * bytes from memory 'buf'. Both arg types need 10255 * to be paired, so make sure there's no buggy 10256 * helper function specification. 10257 */ 10258 if (arg_type_is_mem_size(fn->arg1_type) || 10259 check_args_pair_invalid(fn, 0) || 10260 check_args_pair_invalid(fn, 1) || 10261 check_args_pair_invalid(fn, 2) || 10262 check_args_pair_invalid(fn, 3) || 10263 check_args_pair_invalid(fn, 4)) 10264 return false; 10265 10266 return true; 10267 } 10268 10269 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 10270 { 10271 int i; 10272 10273 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 10274 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 10275 return !!fn->arg_btf_id[i]; 10276 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 10277 return fn->arg_btf_id[i] == BPF_PTR_POISON; 10278 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 10279 /* arg_btf_id and arg_size are in a union. */ 10280 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 10281 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 10282 return false; 10283 } 10284 10285 return true; 10286 } 10287 10288 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 10289 { 10290 return check_raw_mode_ok(fn) && 10291 check_arg_pair_ok(fn) && 10292 check_btf_id_ok(fn) ? 0 : -EINVAL; 10293 } 10294 10295 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 10296 * are now invalid, so turn them into unknown SCALAR_VALUE. 10297 * 10298 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 10299 * since these slices point to packet data. 10300 */ 10301 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 10302 { 10303 struct bpf_func_state *state; 10304 struct bpf_reg_state *reg; 10305 10306 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10307 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 10308 mark_reg_invalid(env, reg); 10309 })); 10310 } 10311 10312 enum { 10313 AT_PKT_END = -1, 10314 BEYOND_PKT_END = -2, 10315 }; 10316 10317 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 10318 { 10319 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 10320 struct bpf_reg_state *reg = &state->regs[regn]; 10321 10322 if (reg->type != PTR_TO_PACKET) 10323 /* PTR_TO_PACKET_META is not supported yet */ 10324 return; 10325 10326 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 10327 * How far beyond pkt_end it goes is unknown. 10328 * if (!range_open) it's the case of pkt >= pkt_end 10329 * if (range_open) it's the case of pkt > pkt_end 10330 * hence this pointer is at least 1 byte bigger than pkt_end 10331 */ 10332 if (range_open) 10333 reg->range = BEYOND_PKT_END; 10334 else 10335 reg->range = AT_PKT_END; 10336 } 10337 10338 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id) 10339 { 10340 int i; 10341 10342 for (i = 0; i < state->acquired_refs; i++) { 10343 if (state->refs[i].type != REF_TYPE_PTR) 10344 continue; 10345 if (state->refs[i].id == ref_obj_id) { 10346 release_reference_state(state, i); 10347 return 0; 10348 } 10349 } 10350 return -EINVAL; 10351 } 10352 10353 /* The pointer with the specified id has released its reference to kernel 10354 * resources. Identify all copies of the same pointer and clear the reference. 10355 * 10356 * This is the release function corresponding to acquire_reference(). Idempotent. 10357 */ 10358 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id) 10359 { 10360 struct bpf_verifier_state *vstate = env->cur_state; 10361 struct bpf_func_state *state; 10362 struct bpf_reg_state *reg; 10363 int err; 10364 10365 err = release_reference_nomark(vstate, ref_obj_id); 10366 if (err) 10367 return err; 10368 10369 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 10370 if (reg->ref_obj_id == ref_obj_id) 10371 mark_reg_invalid(env, reg); 10372 })); 10373 10374 return 0; 10375 } 10376 10377 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 10378 { 10379 struct bpf_func_state *unused; 10380 struct bpf_reg_state *reg; 10381 10382 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10383 if (type_is_non_owning_ref(reg->type)) 10384 mark_reg_invalid(env, reg); 10385 })); 10386 } 10387 10388 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 10389 struct bpf_reg_state *regs) 10390 { 10391 int i; 10392 10393 /* after the call registers r0 - r5 were scratched */ 10394 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10395 mark_reg_not_init(env, regs, caller_saved[i]); 10396 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 10397 } 10398 } 10399 10400 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 10401 struct bpf_func_state *caller, 10402 struct bpf_func_state *callee, 10403 int insn_idx); 10404 10405 static int set_callee_state(struct bpf_verifier_env *env, 10406 struct bpf_func_state *caller, 10407 struct bpf_func_state *callee, int insn_idx); 10408 10409 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 10410 set_callee_state_fn set_callee_state_cb, 10411 struct bpf_verifier_state *state) 10412 { 10413 struct bpf_func_state *caller, *callee; 10414 int err; 10415 10416 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 10417 verbose(env, "the call stack of %d frames is too deep\n", 10418 state->curframe + 2); 10419 return -E2BIG; 10420 } 10421 10422 if (state->frame[state->curframe + 1]) { 10423 verifier_bug(env, "Frame %d already allocated", state->curframe + 1); 10424 return -EFAULT; 10425 } 10426 10427 caller = state->frame[state->curframe]; 10428 callee = kzalloc(sizeof(*callee), GFP_KERNEL_ACCOUNT); 10429 if (!callee) 10430 return -ENOMEM; 10431 state->frame[state->curframe + 1] = callee; 10432 10433 /* callee cannot access r0, r6 - r9 for reading and has to write 10434 * into its own stack before reading from it. 10435 * callee can read/write into caller's stack 10436 */ 10437 init_func_state(env, callee, 10438 /* remember the callsite, it will be used by bpf_exit */ 10439 callsite, 10440 state->curframe + 1 /* frameno within this callchain */, 10441 subprog /* subprog number within this prog */); 10442 err = set_callee_state_cb(env, caller, callee, callsite); 10443 if (err) 10444 goto err_out; 10445 10446 /* only increment it after check_reg_arg() finished */ 10447 state->curframe++; 10448 10449 return 0; 10450 10451 err_out: 10452 free_func_state(callee); 10453 state->frame[state->curframe + 1] = NULL; 10454 return err; 10455 } 10456 10457 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 10458 const struct btf *btf, 10459 struct bpf_reg_state *regs) 10460 { 10461 struct bpf_subprog_info *sub = subprog_info(env, subprog); 10462 struct bpf_verifier_log *log = &env->log; 10463 u32 i; 10464 int ret; 10465 10466 ret = btf_prepare_func_args(env, subprog); 10467 if (ret) 10468 return ret; 10469 10470 /* check that BTF function arguments match actual types that the 10471 * verifier sees. 10472 */ 10473 for (i = 0; i < sub->arg_cnt; i++) { 10474 u32 regno = i + 1; 10475 struct bpf_reg_state *reg = ®s[regno]; 10476 struct bpf_subprog_arg_info *arg = &sub->args[i]; 10477 10478 if (arg->arg_type == ARG_ANYTHING) { 10479 if (reg->type != SCALAR_VALUE) { 10480 bpf_log(log, "R%d is not a scalar\n", regno); 10481 return -EINVAL; 10482 } 10483 } else if (arg->arg_type & PTR_UNTRUSTED) { 10484 /* 10485 * Anything is allowed for untrusted arguments, as these are 10486 * read-only and probe read instructions would protect against 10487 * invalid memory access. 10488 */ 10489 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 10490 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 10491 if (ret < 0) 10492 return ret; 10493 /* If function expects ctx type in BTF check that caller 10494 * is passing PTR_TO_CTX. 10495 */ 10496 if (reg->type != PTR_TO_CTX) { 10497 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 10498 return -EINVAL; 10499 } 10500 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 10501 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 10502 if (ret < 0) 10503 return ret; 10504 if (check_mem_reg(env, reg, regno, arg->mem_size)) 10505 return -EINVAL; 10506 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 10507 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 10508 return -EINVAL; 10509 } 10510 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 10511 /* 10512 * Can pass any value and the kernel won't crash, but 10513 * only PTR_TO_ARENA or SCALAR make sense. Everything 10514 * else is a bug in the bpf program. Point it out to 10515 * the user at the verification time instead of 10516 * run-time debug nightmare. 10517 */ 10518 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 10519 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 10520 return -EINVAL; 10521 } 10522 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 10523 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR); 10524 if (ret) 10525 return ret; 10526 10527 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 10528 if (ret) 10529 return ret; 10530 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 10531 struct bpf_call_arg_meta meta; 10532 int err; 10533 10534 if (register_is_null(reg) && type_may_be_null(arg->arg_type)) 10535 continue; 10536 10537 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 10538 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 10539 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 10540 if (err) 10541 return err; 10542 } else { 10543 verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type); 10544 return -EFAULT; 10545 } 10546 } 10547 10548 return 0; 10549 } 10550 10551 /* Compare BTF of a function call with given bpf_reg_state. 10552 * Returns: 10553 * EFAULT - there is a verifier bug. Abort verification. 10554 * EINVAL - there is a type mismatch or BTF is not available. 10555 * 0 - BTF matches with what bpf_reg_state expects. 10556 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 10557 */ 10558 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 10559 struct bpf_reg_state *regs) 10560 { 10561 struct bpf_prog *prog = env->prog; 10562 struct btf *btf = prog->aux->btf; 10563 u32 btf_id; 10564 int err; 10565 10566 if (!prog->aux->func_info) 10567 return -EINVAL; 10568 10569 btf_id = prog->aux->func_info[subprog].type_id; 10570 if (!btf_id) 10571 return -EFAULT; 10572 10573 if (prog->aux->func_info_aux[subprog].unreliable) 10574 return -EINVAL; 10575 10576 err = btf_check_func_arg_match(env, subprog, btf, regs); 10577 /* Compiler optimizations can remove arguments from static functions 10578 * or mismatched type can be passed into a global function. 10579 * In such cases mark the function as unreliable from BTF point of view. 10580 */ 10581 if (err) 10582 prog->aux->func_info_aux[subprog].unreliable = true; 10583 return err; 10584 } 10585 10586 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10587 int insn_idx, int subprog, 10588 set_callee_state_fn set_callee_state_cb) 10589 { 10590 struct bpf_verifier_state *state = env->cur_state, *callback_state; 10591 struct bpf_func_state *caller, *callee; 10592 int err; 10593 10594 caller = state->frame[state->curframe]; 10595 err = btf_check_subprog_call(env, subprog, caller->regs); 10596 if (err == -EFAULT) 10597 return err; 10598 10599 /* set_callee_state is used for direct subprog calls, but we are 10600 * interested in validating only BPF helpers that can call subprogs as 10601 * callbacks 10602 */ 10603 env->subprog_info[subprog].is_cb = true; 10604 if (bpf_pseudo_kfunc_call(insn) && 10605 !is_callback_calling_kfunc(insn->imm)) { 10606 verifier_bug(env, "kfunc %s#%d not marked as callback-calling", 10607 func_id_name(insn->imm), insn->imm); 10608 return -EFAULT; 10609 } else if (!bpf_pseudo_kfunc_call(insn) && 10610 !is_callback_calling_function(insn->imm)) { /* helper */ 10611 verifier_bug(env, "helper %s#%d not marked as callback-calling", 10612 func_id_name(insn->imm), insn->imm); 10613 return -EFAULT; 10614 } 10615 10616 if (is_async_callback_calling_insn(insn)) { 10617 struct bpf_verifier_state *async_cb; 10618 10619 /* there is no real recursion here. timer and workqueue callbacks are async */ 10620 env->subprog_info[subprog].is_async_cb = true; 10621 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 10622 insn_idx, subprog, 10623 is_bpf_wq_set_callback_impl_kfunc(insn->imm)); 10624 if (!async_cb) 10625 return -EFAULT; 10626 callee = async_cb->frame[0]; 10627 callee->async_entry_cnt = caller->async_entry_cnt + 1; 10628 10629 /* Convert bpf_timer_set_callback() args into timer callback args */ 10630 err = set_callee_state_cb(env, caller, callee, insn_idx); 10631 if (err) 10632 return err; 10633 10634 return 0; 10635 } 10636 10637 /* for callback functions enqueue entry to callback and 10638 * proceed with next instruction within current frame. 10639 */ 10640 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 10641 if (!callback_state) 10642 return -ENOMEM; 10643 10644 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 10645 callback_state); 10646 if (err) 10647 return err; 10648 10649 callback_state->callback_unroll_depth++; 10650 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 10651 caller->callback_depth = 0; 10652 return 0; 10653 } 10654 10655 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10656 int *insn_idx) 10657 { 10658 struct bpf_verifier_state *state = env->cur_state; 10659 struct bpf_func_state *caller; 10660 int err, subprog, target_insn; 10661 10662 target_insn = *insn_idx + insn->imm + 1; 10663 subprog = find_subprog(env, target_insn); 10664 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program", 10665 target_insn)) 10666 return -EFAULT; 10667 10668 caller = state->frame[state->curframe]; 10669 err = btf_check_subprog_call(env, subprog, caller->regs); 10670 if (err == -EFAULT) 10671 return err; 10672 if (subprog_is_global(env, subprog)) { 10673 const char *sub_name = subprog_name(env, subprog); 10674 10675 if (env->cur_state->active_locks) { 10676 verbose(env, "global function calls are not allowed while holding a lock,\n" 10677 "use static function instead\n"); 10678 return -EINVAL; 10679 } 10680 10681 if (env->subprog_info[subprog].might_sleep && 10682 (env->cur_state->active_rcu_lock || env->cur_state->active_preempt_locks || 10683 env->cur_state->active_irq_id || !in_sleepable(env))) { 10684 verbose(env, "global functions that may sleep are not allowed in non-sleepable context,\n" 10685 "i.e., in a RCU/IRQ/preempt-disabled section, or in\n" 10686 "a non-sleepable BPF program context\n"); 10687 return -EINVAL; 10688 } 10689 10690 if (err) { 10691 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 10692 subprog, sub_name); 10693 return err; 10694 } 10695 10696 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 10697 subprog, sub_name); 10698 if (env->subprog_info[subprog].changes_pkt_data) 10699 clear_all_pkt_pointers(env); 10700 /* mark global subprog for verifying after main prog */ 10701 subprog_aux(env, subprog)->called = true; 10702 clear_caller_saved_regs(env, caller->regs); 10703 10704 /* All global functions return a 64-bit SCALAR_VALUE */ 10705 mark_reg_unknown(env, caller->regs, BPF_REG_0); 10706 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10707 10708 /* continue with next insn after call */ 10709 return 0; 10710 } 10711 10712 /* for regular function entry setup new frame and continue 10713 * from that frame. 10714 */ 10715 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 10716 if (err) 10717 return err; 10718 10719 clear_caller_saved_regs(env, caller->regs); 10720 10721 /* and go analyze first insn of the callee */ 10722 *insn_idx = env->subprog_info[subprog].start - 1; 10723 10724 if (env->log.level & BPF_LOG_LEVEL) { 10725 verbose(env, "caller:\n"); 10726 print_verifier_state(env, state, caller->frameno, true); 10727 verbose(env, "callee:\n"); 10728 print_verifier_state(env, state, state->curframe, true); 10729 } 10730 10731 return 0; 10732 } 10733 10734 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 10735 struct bpf_func_state *caller, 10736 struct bpf_func_state *callee) 10737 { 10738 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 10739 * void *callback_ctx, u64 flags); 10740 * callback_fn(struct bpf_map *map, void *key, void *value, 10741 * void *callback_ctx); 10742 */ 10743 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 10744 10745 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 10746 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10747 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 10748 10749 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 10750 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 10751 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 10752 10753 /* pointer to stack or null */ 10754 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 10755 10756 /* unused */ 10757 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10758 return 0; 10759 } 10760 10761 static int set_callee_state(struct bpf_verifier_env *env, 10762 struct bpf_func_state *caller, 10763 struct bpf_func_state *callee, int insn_idx) 10764 { 10765 int i; 10766 10767 /* copy r1 - r5 args that callee can access. The copy includes parent 10768 * pointers, which connects us up to the liveness chain 10769 */ 10770 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 10771 callee->regs[i] = caller->regs[i]; 10772 return 0; 10773 } 10774 10775 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 10776 struct bpf_func_state *caller, 10777 struct bpf_func_state *callee, 10778 int insn_idx) 10779 { 10780 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 10781 struct bpf_map *map; 10782 int err; 10783 10784 /* valid map_ptr and poison value does not matter */ 10785 map = insn_aux->map_ptr_state.map_ptr; 10786 if (!map->ops->map_set_for_each_callback_args || 10787 !map->ops->map_for_each_callback) { 10788 verbose(env, "callback function not allowed for map\n"); 10789 return -ENOTSUPP; 10790 } 10791 10792 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 10793 if (err) 10794 return err; 10795 10796 callee->in_callback_fn = true; 10797 callee->callback_ret_range = retval_range(0, 1); 10798 return 0; 10799 } 10800 10801 static int set_loop_callback_state(struct bpf_verifier_env *env, 10802 struct bpf_func_state *caller, 10803 struct bpf_func_state *callee, 10804 int insn_idx) 10805 { 10806 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 10807 * u64 flags); 10808 * callback_fn(u64 index, void *callback_ctx); 10809 */ 10810 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 10811 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 10812 10813 /* unused */ 10814 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10815 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10816 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10817 10818 callee->in_callback_fn = true; 10819 callee->callback_ret_range = retval_range(0, 1); 10820 return 0; 10821 } 10822 10823 static int set_timer_callback_state(struct bpf_verifier_env *env, 10824 struct bpf_func_state *caller, 10825 struct bpf_func_state *callee, 10826 int insn_idx) 10827 { 10828 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 10829 10830 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 10831 * callback_fn(struct bpf_map *map, void *key, void *value); 10832 */ 10833 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 10834 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 10835 callee->regs[BPF_REG_1].map_ptr = map_ptr; 10836 10837 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 10838 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10839 callee->regs[BPF_REG_2].map_ptr = map_ptr; 10840 10841 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 10842 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 10843 callee->regs[BPF_REG_3].map_ptr = map_ptr; 10844 10845 /* unused */ 10846 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10847 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10848 callee->in_async_callback_fn = true; 10849 callee->callback_ret_range = retval_range(0, 1); 10850 return 0; 10851 } 10852 10853 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 10854 struct bpf_func_state *caller, 10855 struct bpf_func_state *callee, 10856 int insn_idx) 10857 { 10858 /* bpf_find_vma(struct task_struct *task, u64 addr, 10859 * void *callback_fn, void *callback_ctx, u64 flags) 10860 * (callback_fn)(struct task_struct *task, 10861 * struct vm_area_struct *vma, void *callback_ctx); 10862 */ 10863 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 10864 10865 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 10866 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 10867 callee->regs[BPF_REG_2].btf = btf_vmlinux; 10868 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 10869 10870 /* pointer to stack or null */ 10871 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 10872 10873 /* unused */ 10874 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10875 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10876 callee->in_callback_fn = true; 10877 callee->callback_ret_range = retval_range(0, 1); 10878 return 0; 10879 } 10880 10881 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 10882 struct bpf_func_state *caller, 10883 struct bpf_func_state *callee, 10884 int insn_idx) 10885 { 10886 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 10887 * callback_ctx, u64 flags); 10888 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 10889 */ 10890 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 10891 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 10892 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 10893 10894 /* unused */ 10895 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10896 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10897 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10898 10899 callee->in_callback_fn = true; 10900 callee->callback_ret_range = retval_range(0, 1); 10901 return 0; 10902 } 10903 10904 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 10905 struct bpf_func_state *caller, 10906 struct bpf_func_state *callee, 10907 int insn_idx) 10908 { 10909 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 10910 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 10911 * 10912 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 10913 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 10914 * by this point, so look at 'root' 10915 */ 10916 struct btf_field *field; 10917 10918 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 10919 BPF_RB_ROOT); 10920 if (!field || !field->graph_root.value_btf_id) 10921 return -EFAULT; 10922 10923 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 10924 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 10925 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 10926 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 10927 10928 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 10929 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 10930 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 10931 callee->in_callback_fn = true; 10932 callee->callback_ret_range = retval_range(0, 1); 10933 return 0; 10934 } 10935 10936 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 10937 10938 /* Are we currently verifying the callback for a rbtree helper that must 10939 * be called with lock held? If so, no need to complain about unreleased 10940 * lock 10941 */ 10942 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 10943 { 10944 struct bpf_verifier_state *state = env->cur_state; 10945 struct bpf_insn *insn = env->prog->insnsi; 10946 struct bpf_func_state *callee; 10947 int kfunc_btf_id; 10948 10949 if (!state->curframe) 10950 return false; 10951 10952 callee = state->frame[state->curframe]; 10953 10954 if (!callee->in_callback_fn) 10955 return false; 10956 10957 kfunc_btf_id = insn[callee->callsite].imm; 10958 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 10959 } 10960 10961 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg, 10962 bool return_32bit) 10963 { 10964 if (return_32bit) 10965 return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval; 10966 else 10967 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 10968 } 10969 10970 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 10971 { 10972 struct bpf_verifier_state *state = env->cur_state, *prev_st; 10973 struct bpf_func_state *caller, *callee; 10974 struct bpf_reg_state *r0; 10975 bool in_callback_fn; 10976 int err; 10977 10978 callee = state->frame[state->curframe]; 10979 r0 = &callee->regs[BPF_REG_0]; 10980 if (r0->type == PTR_TO_STACK) { 10981 /* technically it's ok to return caller's stack pointer 10982 * (or caller's caller's pointer) back to the caller, 10983 * since these pointers are valid. Only current stack 10984 * pointer will be invalid as soon as function exits, 10985 * but let's be conservative 10986 */ 10987 verbose(env, "cannot return stack pointer to the caller\n"); 10988 return -EINVAL; 10989 } 10990 10991 caller = state->frame[state->curframe - 1]; 10992 if (callee->in_callback_fn) { 10993 if (r0->type != SCALAR_VALUE) { 10994 verbose(env, "R0 not a scalar value\n"); 10995 return -EACCES; 10996 } 10997 10998 /* we are going to rely on register's precise value */ 10999 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 11000 err = err ?: mark_chain_precision(env, BPF_REG_0); 11001 if (err) 11002 return err; 11003 11004 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 11005 if (!retval_range_within(callee->callback_ret_range, r0, false)) { 11006 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 11007 "At callback return", "R0"); 11008 return -EINVAL; 11009 } 11010 if (!calls_callback(env, callee->callsite)) { 11011 verifier_bug(env, "in callback at %d, callsite %d !calls_callback", 11012 *insn_idx, callee->callsite); 11013 return -EFAULT; 11014 } 11015 } else { 11016 /* return to the caller whatever r0 had in the callee */ 11017 caller->regs[BPF_REG_0] = *r0; 11018 } 11019 11020 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 11021 * there function call logic would reschedule callback visit. If iteration 11022 * converges is_state_visited() would prune that visit eventually. 11023 */ 11024 in_callback_fn = callee->in_callback_fn; 11025 if (in_callback_fn) 11026 *insn_idx = callee->callsite; 11027 else 11028 *insn_idx = callee->callsite + 1; 11029 11030 if (env->log.level & BPF_LOG_LEVEL) { 11031 verbose(env, "returning from callee:\n"); 11032 print_verifier_state(env, state, callee->frameno, true); 11033 verbose(env, "to caller at %d:\n", *insn_idx); 11034 print_verifier_state(env, state, caller->frameno, true); 11035 } 11036 /* clear everything in the callee. In case of exceptional exits using 11037 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 11038 free_func_state(callee); 11039 state->frame[state->curframe--] = NULL; 11040 11041 /* for callbacks widen imprecise scalars to make programs like below verify: 11042 * 11043 * struct ctx { int i; } 11044 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 11045 * ... 11046 * struct ctx = { .i = 0; } 11047 * bpf_loop(100, cb, &ctx, 0); 11048 * 11049 * This is similar to what is done in process_iter_next_call() for open 11050 * coded iterators. 11051 */ 11052 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 11053 if (prev_st) { 11054 err = widen_imprecise_scalars(env, prev_st, state); 11055 if (err) 11056 return err; 11057 } 11058 return 0; 11059 } 11060 11061 static int do_refine_retval_range(struct bpf_verifier_env *env, 11062 struct bpf_reg_state *regs, int ret_type, 11063 int func_id, 11064 struct bpf_call_arg_meta *meta) 11065 { 11066 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 11067 11068 if (ret_type != RET_INTEGER) 11069 return 0; 11070 11071 switch (func_id) { 11072 case BPF_FUNC_get_stack: 11073 case BPF_FUNC_get_task_stack: 11074 case BPF_FUNC_probe_read_str: 11075 case BPF_FUNC_probe_read_kernel_str: 11076 case BPF_FUNC_probe_read_user_str: 11077 ret_reg->smax_value = meta->msize_max_value; 11078 ret_reg->s32_max_value = meta->msize_max_value; 11079 ret_reg->smin_value = -MAX_ERRNO; 11080 ret_reg->s32_min_value = -MAX_ERRNO; 11081 reg_bounds_sync(ret_reg); 11082 break; 11083 case BPF_FUNC_get_smp_processor_id: 11084 ret_reg->umax_value = nr_cpu_ids - 1; 11085 ret_reg->u32_max_value = nr_cpu_ids - 1; 11086 ret_reg->smax_value = nr_cpu_ids - 1; 11087 ret_reg->s32_max_value = nr_cpu_ids - 1; 11088 ret_reg->umin_value = 0; 11089 ret_reg->u32_min_value = 0; 11090 ret_reg->smin_value = 0; 11091 ret_reg->s32_min_value = 0; 11092 reg_bounds_sync(ret_reg); 11093 break; 11094 } 11095 11096 return reg_bounds_sanity_check(env, ret_reg, "retval"); 11097 } 11098 11099 static int 11100 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 11101 int func_id, int insn_idx) 11102 { 11103 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 11104 struct bpf_map *map = meta->map_ptr; 11105 11106 if (func_id != BPF_FUNC_tail_call && 11107 func_id != BPF_FUNC_map_lookup_elem && 11108 func_id != BPF_FUNC_map_update_elem && 11109 func_id != BPF_FUNC_map_delete_elem && 11110 func_id != BPF_FUNC_map_push_elem && 11111 func_id != BPF_FUNC_map_pop_elem && 11112 func_id != BPF_FUNC_map_peek_elem && 11113 func_id != BPF_FUNC_for_each_map_elem && 11114 func_id != BPF_FUNC_redirect_map && 11115 func_id != BPF_FUNC_map_lookup_percpu_elem) 11116 return 0; 11117 11118 if (map == NULL) { 11119 verifier_bug(env, "expected map for helper call"); 11120 return -EFAULT; 11121 } 11122 11123 /* In case of read-only, some additional restrictions 11124 * need to be applied in order to prevent altering the 11125 * state of the map from program side. 11126 */ 11127 if ((map->map_flags & BPF_F_RDONLY_PROG) && 11128 (func_id == BPF_FUNC_map_delete_elem || 11129 func_id == BPF_FUNC_map_update_elem || 11130 func_id == BPF_FUNC_map_push_elem || 11131 func_id == BPF_FUNC_map_pop_elem)) { 11132 verbose(env, "write into map forbidden\n"); 11133 return -EACCES; 11134 } 11135 11136 if (!aux->map_ptr_state.map_ptr) 11137 bpf_map_ptr_store(aux, meta->map_ptr, 11138 !meta->map_ptr->bypass_spec_v1, false); 11139 else if (aux->map_ptr_state.map_ptr != meta->map_ptr) 11140 bpf_map_ptr_store(aux, meta->map_ptr, 11141 !meta->map_ptr->bypass_spec_v1, true); 11142 return 0; 11143 } 11144 11145 static int 11146 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 11147 int func_id, int insn_idx) 11148 { 11149 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 11150 struct bpf_reg_state *regs = cur_regs(env), *reg; 11151 struct bpf_map *map = meta->map_ptr; 11152 u64 val, max; 11153 int err; 11154 11155 if (func_id != BPF_FUNC_tail_call) 11156 return 0; 11157 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 11158 verbose(env, "expected prog array map for tail call"); 11159 return -EINVAL; 11160 } 11161 11162 reg = ®s[BPF_REG_3]; 11163 val = reg->var_off.value; 11164 max = map->max_entries; 11165 11166 if (!(is_reg_const(reg, false) && val < max)) { 11167 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 11168 return 0; 11169 } 11170 11171 err = mark_chain_precision(env, BPF_REG_3); 11172 if (err) 11173 return err; 11174 if (bpf_map_key_unseen(aux)) 11175 bpf_map_key_store(aux, val); 11176 else if (!bpf_map_key_poisoned(aux) && 11177 bpf_map_key_immediate(aux) != val) 11178 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 11179 return 0; 11180 } 11181 11182 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 11183 { 11184 struct bpf_verifier_state *state = env->cur_state; 11185 enum bpf_prog_type type = resolve_prog_type(env->prog); 11186 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 11187 bool refs_lingering = false; 11188 int i; 11189 11190 if (!exception_exit && cur_func(env)->frameno) 11191 return 0; 11192 11193 for (i = 0; i < state->acquired_refs; i++) { 11194 if (state->refs[i].type != REF_TYPE_PTR) 11195 continue; 11196 /* Allow struct_ops programs to return a referenced kptr back to 11197 * kernel. Type checks are performed later in check_return_code. 11198 */ 11199 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && 11200 reg->ref_obj_id == state->refs[i].id) 11201 continue; 11202 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 11203 state->refs[i].id, state->refs[i].insn_idx); 11204 refs_lingering = true; 11205 } 11206 return refs_lingering ? -EINVAL : 0; 11207 } 11208 11209 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 11210 { 11211 int err; 11212 11213 if (check_lock && env->cur_state->active_locks) { 11214 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 11215 return -EINVAL; 11216 } 11217 11218 err = check_reference_leak(env, exception_exit); 11219 if (err) { 11220 verbose(env, "%s would lead to reference leak\n", prefix); 11221 return err; 11222 } 11223 11224 if (check_lock && env->cur_state->active_irq_id) { 11225 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix); 11226 return -EINVAL; 11227 } 11228 11229 if (check_lock && env->cur_state->active_rcu_lock) { 11230 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 11231 return -EINVAL; 11232 } 11233 11234 if (check_lock && env->cur_state->active_preempt_locks) { 11235 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 11236 return -EINVAL; 11237 } 11238 11239 return 0; 11240 } 11241 11242 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 11243 struct bpf_reg_state *regs) 11244 { 11245 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 11246 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 11247 struct bpf_map *fmt_map = fmt_reg->map_ptr; 11248 struct bpf_bprintf_data data = {}; 11249 int err, fmt_map_off, num_args; 11250 u64 fmt_addr; 11251 char *fmt; 11252 11253 /* data must be an array of u64 */ 11254 if (data_len_reg->var_off.value % 8) 11255 return -EINVAL; 11256 num_args = data_len_reg->var_off.value / 8; 11257 11258 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 11259 * and map_direct_value_addr is set. 11260 */ 11261 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 11262 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 11263 fmt_map_off); 11264 if (err) { 11265 verbose(env, "failed to retrieve map value address\n"); 11266 return -EFAULT; 11267 } 11268 fmt = (char *)(long)fmt_addr + fmt_map_off; 11269 11270 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 11271 * can focus on validating the format specifiers. 11272 */ 11273 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 11274 if (err < 0) 11275 verbose(env, "Invalid format string\n"); 11276 11277 return err; 11278 } 11279 11280 static int check_get_func_ip(struct bpf_verifier_env *env) 11281 { 11282 enum bpf_prog_type type = resolve_prog_type(env->prog); 11283 int func_id = BPF_FUNC_get_func_ip; 11284 11285 if (type == BPF_PROG_TYPE_TRACING) { 11286 if (!bpf_prog_has_trampoline(env->prog)) { 11287 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 11288 func_id_name(func_id), func_id); 11289 return -ENOTSUPP; 11290 } 11291 return 0; 11292 } else if (type == BPF_PROG_TYPE_KPROBE) { 11293 return 0; 11294 } 11295 11296 verbose(env, "func %s#%d not supported for program type %d\n", 11297 func_id_name(func_id), func_id, type); 11298 return -ENOTSUPP; 11299 } 11300 11301 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env) 11302 { 11303 return &env->insn_aux_data[env->insn_idx]; 11304 } 11305 11306 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 11307 { 11308 struct bpf_reg_state *regs = cur_regs(env); 11309 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 11310 bool reg_is_null = register_is_null(reg); 11311 11312 if (reg_is_null) 11313 mark_chain_precision(env, BPF_REG_4); 11314 11315 return reg_is_null; 11316 } 11317 11318 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 11319 { 11320 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 11321 11322 if (!state->initialized) { 11323 state->initialized = 1; 11324 state->fit_for_inline = loop_flag_is_zero(env); 11325 state->callback_subprogno = subprogno; 11326 return; 11327 } 11328 11329 if (!state->fit_for_inline) 11330 return; 11331 11332 state->fit_for_inline = (loop_flag_is_zero(env) && 11333 state->callback_subprogno == subprogno); 11334 } 11335 11336 /* Returns whether or not the given map type can potentially elide 11337 * lookup return value nullness check. This is possible if the key 11338 * is statically known. 11339 */ 11340 static bool can_elide_value_nullness(enum bpf_map_type type) 11341 { 11342 switch (type) { 11343 case BPF_MAP_TYPE_ARRAY: 11344 case BPF_MAP_TYPE_PERCPU_ARRAY: 11345 return true; 11346 default: 11347 return false; 11348 } 11349 } 11350 11351 static int get_helper_proto(struct bpf_verifier_env *env, int func_id, 11352 const struct bpf_func_proto **ptr) 11353 { 11354 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 11355 return -ERANGE; 11356 11357 if (!env->ops->get_func_proto) 11358 return -EINVAL; 11359 11360 *ptr = env->ops->get_func_proto(func_id, env->prog); 11361 return *ptr && (*ptr)->func ? 0 : -EINVAL; 11362 } 11363 11364 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 11365 int *insn_idx_p) 11366 { 11367 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11368 bool returns_cpu_specific_alloc_ptr = false; 11369 const struct bpf_func_proto *fn = NULL; 11370 enum bpf_return_type ret_type; 11371 enum bpf_type_flag ret_flag; 11372 struct bpf_reg_state *regs; 11373 struct bpf_call_arg_meta meta; 11374 int insn_idx = *insn_idx_p; 11375 bool changes_data; 11376 int i, err, func_id; 11377 11378 /* find function prototype */ 11379 func_id = insn->imm; 11380 err = get_helper_proto(env, insn->imm, &fn); 11381 if (err == -ERANGE) { 11382 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 11383 return -EINVAL; 11384 } 11385 11386 if (err) { 11387 verbose(env, "program of this type cannot use helper %s#%d\n", 11388 func_id_name(func_id), func_id); 11389 return err; 11390 } 11391 11392 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 11393 if (!env->prog->gpl_compatible && fn->gpl_only) { 11394 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 11395 return -EINVAL; 11396 } 11397 11398 if (fn->allowed && !fn->allowed(env->prog)) { 11399 verbose(env, "helper call is not allowed in probe\n"); 11400 return -EINVAL; 11401 } 11402 11403 if (!in_sleepable(env) && fn->might_sleep) { 11404 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 11405 return -EINVAL; 11406 } 11407 11408 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 11409 changes_data = bpf_helper_changes_pkt_data(func_id); 11410 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 11411 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id); 11412 return -EFAULT; 11413 } 11414 11415 memset(&meta, 0, sizeof(meta)); 11416 meta.pkt_access = fn->pkt_access; 11417 11418 err = check_func_proto(fn, func_id); 11419 if (err) { 11420 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id); 11421 return err; 11422 } 11423 11424 if (env->cur_state->active_rcu_lock) { 11425 if (fn->might_sleep) { 11426 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 11427 func_id_name(func_id), func_id); 11428 return -EINVAL; 11429 } 11430 11431 if (in_sleepable(env) && is_storage_get_function(func_id)) 11432 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 11433 } 11434 11435 if (env->cur_state->active_preempt_locks) { 11436 if (fn->might_sleep) { 11437 verbose(env, "sleepable helper %s#%d in non-preemptible region\n", 11438 func_id_name(func_id), func_id); 11439 return -EINVAL; 11440 } 11441 11442 if (in_sleepable(env) && is_storage_get_function(func_id)) 11443 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 11444 } 11445 11446 if (env->cur_state->active_irq_id) { 11447 if (fn->might_sleep) { 11448 verbose(env, "sleepable helper %s#%d in IRQ-disabled region\n", 11449 func_id_name(func_id), func_id); 11450 return -EINVAL; 11451 } 11452 11453 if (in_sleepable(env) && is_storage_get_function(func_id)) 11454 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 11455 } 11456 11457 meta.func_id = func_id; 11458 /* check args */ 11459 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 11460 err = check_func_arg(env, i, &meta, fn, insn_idx); 11461 if (err) 11462 return err; 11463 } 11464 11465 err = record_func_map(env, &meta, func_id, insn_idx); 11466 if (err) 11467 return err; 11468 11469 err = record_func_key(env, &meta, func_id, insn_idx); 11470 if (err) 11471 return err; 11472 11473 /* Mark slots with STACK_MISC in case of raw mode, stack offset 11474 * is inferred from register state. 11475 */ 11476 for (i = 0; i < meta.access_size; i++) { 11477 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 11478 BPF_WRITE, -1, false, false); 11479 if (err) 11480 return err; 11481 } 11482 11483 regs = cur_regs(env); 11484 11485 if (meta.release_regno) { 11486 err = -EINVAL; 11487 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 11488 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 11489 * is safe to do directly. 11490 */ 11491 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 11492 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 11493 verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released"); 11494 return -EFAULT; 11495 } 11496 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 11497 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 11498 u32 ref_obj_id = meta.ref_obj_id; 11499 bool in_rcu = in_rcu_cs(env); 11500 struct bpf_func_state *state; 11501 struct bpf_reg_state *reg; 11502 11503 err = release_reference_nomark(env->cur_state, ref_obj_id); 11504 if (!err) { 11505 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 11506 if (reg->ref_obj_id == ref_obj_id) { 11507 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 11508 reg->ref_obj_id = 0; 11509 reg->type &= ~MEM_ALLOC; 11510 reg->type |= MEM_RCU; 11511 } else { 11512 mark_reg_invalid(env, reg); 11513 } 11514 } 11515 })); 11516 } 11517 } else if (meta.ref_obj_id) { 11518 err = release_reference(env, meta.ref_obj_id); 11519 } else if (register_is_null(®s[meta.release_regno])) { 11520 /* meta.ref_obj_id can only be 0 if register that is meant to be 11521 * released is NULL, which must be > R0. 11522 */ 11523 err = 0; 11524 } 11525 if (err) { 11526 verbose(env, "func %s#%d reference has not been acquired before\n", 11527 func_id_name(func_id), func_id); 11528 return err; 11529 } 11530 } 11531 11532 switch (func_id) { 11533 case BPF_FUNC_tail_call: 11534 err = check_resource_leak(env, false, true, "tail_call"); 11535 if (err) 11536 return err; 11537 break; 11538 case BPF_FUNC_get_local_storage: 11539 /* check that flags argument in get_local_storage(map, flags) is 0, 11540 * this is required because get_local_storage() can't return an error. 11541 */ 11542 if (!register_is_null(®s[BPF_REG_2])) { 11543 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 11544 return -EINVAL; 11545 } 11546 break; 11547 case BPF_FUNC_for_each_map_elem: 11548 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11549 set_map_elem_callback_state); 11550 break; 11551 case BPF_FUNC_timer_set_callback: 11552 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11553 set_timer_callback_state); 11554 break; 11555 case BPF_FUNC_find_vma: 11556 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11557 set_find_vma_callback_state); 11558 break; 11559 case BPF_FUNC_snprintf: 11560 err = check_bpf_snprintf_call(env, regs); 11561 break; 11562 case BPF_FUNC_loop: 11563 update_loop_inline_state(env, meta.subprogno); 11564 /* Verifier relies on R1 value to determine if bpf_loop() iteration 11565 * is finished, thus mark it precise. 11566 */ 11567 err = mark_chain_precision(env, BPF_REG_1); 11568 if (err) 11569 return err; 11570 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 11571 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11572 set_loop_callback_state); 11573 } else { 11574 cur_func(env)->callback_depth = 0; 11575 if (env->log.level & BPF_LOG_LEVEL2) 11576 verbose(env, "frame%d bpf_loop iteration limit reached\n", 11577 env->cur_state->curframe); 11578 } 11579 break; 11580 case BPF_FUNC_dynptr_from_mem: 11581 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 11582 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 11583 reg_type_str(env, regs[BPF_REG_1].type)); 11584 return -EACCES; 11585 } 11586 break; 11587 case BPF_FUNC_set_retval: 11588 if (prog_type == BPF_PROG_TYPE_LSM && 11589 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 11590 if (!env->prog->aux->attach_func_proto->type) { 11591 /* Make sure programs that attach to void 11592 * hooks don't try to modify return value. 11593 */ 11594 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 11595 return -EINVAL; 11596 } 11597 } 11598 break; 11599 case BPF_FUNC_dynptr_data: 11600 { 11601 struct bpf_reg_state *reg; 11602 int id, ref_obj_id; 11603 11604 reg = get_dynptr_arg_reg(env, fn, regs); 11605 if (!reg) 11606 return -EFAULT; 11607 11608 11609 if (meta.dynptr_id) { 11610 verifier_bug(env, "meta.dynptr_id already set"); 11611 return -EFAULT; 11612 } 11613 if (meta.ref_obj_id) { 11614 verifier_bug(env, "meta.ref_obj_id already set"); 11615 return -EFAULT; 11616 } 11617 11618 id = dynptr_id(env, reg); 11619 if (id < 0) { 11620 verifier_bug(env, "failed to obtain dynptr id"); 11621 return id; 11622 } 11623 11624 ref_obj_id = dynptr_ref_obj_id(env, reg); 11625 if (ref_obj_id < 0) { 11626 verifier_bug(env, "failed to obtain dynptr ref_obj_id"); 11627 return ref_obj_id; 11628 } 11629 11630 meta.dynptr_id = id; 11631 meta.ref_obj_id = ref_obj_id; 11632 11633 break; 11634 } 11635 case BPF_FUNC_dynptr_write: 11636 { 11637 enum bpf_dynptr_type dynptr_type; 11638 struct bpf_reg_state *reg; 11639 11640 reg = get_dynptr_arg_reg(env, fn, regs); 11641 if (!reg) 11642 return -EFAULT; 11643 11644 dynptr_type = dynptr_get_type(env, reg); 11645 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 11646 return -EFAULT; 11647 11648 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 11649 /* this will trigger clear_all_pkt_pointers(), which will 11650 * invalidate all dynptr slices associated with the skb 11651 */ 11652 changes_data = true; 11653 11654 break; 11655 } 11656 case BPF_FUNC_per_cpu_ptr: 11657 case BPF_FUNC_this_cpu_ptr: 11658 { 11659 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 11660 const struct btf_type *type; 11661 11662 if (reg->type & MEM_RCU) { 11663 type = btf_type_by_id(reg->btf, reg->btf_id); 11664 if (!type || !btf_type_is_struct(type)) { 11665 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 11666 return -EFAULT; 11667 } 11668 returns_cpu_specific_alloc_ptr = true; 11669 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 11670 } 11671 break; 11672 } 11673 case BPF_FUNC_user_ringbuf_drain: 11674 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 11675 set_user_ringbuf_callback_state); 11676 break; 11677 } 11678 11679 if (err) 11680 return err; 11681 11682 /* reset caller saved regs */ 11683 for (i = 0; i < CALLER_SAVED_REGS; i++) { 11684 mark_reg_not_init(env, regs, caller_saved[i]); 11685 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 11686 } 11687 11688 /* helper call returns 64-bit value. */ 11689 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 11690 11691 /* update return register (already marked as written above) */ 11692 ret_type = fn->ret_type; 11693 ret_flag = type_flag(ret_type); 11694 11695 switch (base_type(ret_type)) { 11696 case RET_INTEGER: 11697 /* sets type to SCALAR_VALUE */ 11698 mark_reg_unknown(env, regs, BPF_REG_0); 11699 break; 11700 case RET_VOID: 11701 regs[BPF_REG_0].type = NOT_INIT; 11702 break; 11703 case RET_PTR_TO_MAP_VALUE: 11704 /* There is no offset yet applied, variable or fixed */ 11705 mark_reg_known_zero(env, regs, BPF_REG_0); 11706 /* remember map_ptr, so that check_map_access() 11707 * can check 'value_size' boundary of memory access 11708 * to map element returned from bpf_map_lookup_elem() 11709 */ 11710 if (meta.map_ptr == NULL) { 11711 verifier_bug(env, "unexpected null map_ptr"); 11712 return -EFAULT; 11713 } 11714 11715 if (func_id == BPF_FUNC_map_lookup_elem && 11716 can_elide_value_nullness(meta.map_ptr->map_type) && 11717 meta.const_map_key >= 0 && 11718 meta.const_map_key < meta.map_ptr->max_entries) 11719 ret_flag &= ~PTR_MAYBE_NULL; 11720 11721 regs[BPF_REG_0].map_ptr = meta.map_ptr; 11722 regs[BPF_REG_0].map_uid = meta.map_uid; 11723 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 11724 if (!type_may_be_null(ret_flag) && 11725 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 11726 regs[BPF_REG_0].id = ++env->id_gen; 11727 } 11728 break; 11729 case RET_PTR_TO_SOCKET: 11730 mark_reg_known_zero(env, regs, BPF_REG_0); 11731 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 11732 break; 11733 case RET_PTR_TO_SOCK_COMMON: 11734 mark_reg_known_zero(env, regs, BPF_REG_0); 11735 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 11736 break; 11737 case RET_PTR_TO_TCP_SOCK: 11738 mark_reg_known_zero(env, regs, BPF_REG_0); 11739 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 11740 break; 11741 case RET_PTR_TO_MEM: 11742 mark_reg_known_zero(env, regs, BPF_REG_0); 11743 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 11744 regs[BPF_REG_0].mem_size = meta.mem_size; 11745 break; 11746 case RET_PTR_TO_MEM_OR_BTF_ID: 11747 { 11748 const struct btf_type *t; 11749 11750 mark_reg_known_zero(env, regs, BPF_REG_0); 11751 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 11752 if (!btf_type_is_struct(t)) { 11753 u32 tsize; 11754 const struct btf_type *ret; 11755 const char *tname; 11756 11757 /* resolve the type size of ksym. */ 11758 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 11759 if (IS_ERR(ret)) { 11760 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 11761 verbose(env, "unable to resolve the size of type '%s': %ld\n", 11762 tname, PTR_ERR(ret)); 11763 return -EINVAL; 11764 } 11765 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 11766 regs[BPF_REG_0].mem_size = tsize; 11767 } else { 11768 if (returns_cpu_specific_alloc_ptr) { 11769 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 11770 } else { 11771 /* MEM_RDONLY may be carried from ret_flag, but it 11772 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 11773 * it will confuse the check of PTR_TO_BTF_ID in 11774 * check_mem_access(). 11775 */ 11776 ret_flag &= ~MEM_RDONLY; 11777 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 11778 } 11779 11780 regs[BPF_REG_0].btf = meta.ret_btf; 11781 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11782 } 11783 break; 11784 } 11785 case RET_PTR_TO_BTF_ID: 11786 { 11787 struct btf *ret_btf; 11788 int ret_btf_id; 11789 11790 mark_reg_known_zero(env, regs, BPF_REG_0); 11791 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 11792 if (func_id == BPF_FUNC_kptr_xchg) { 11793 ret_btf = meta.kptr_field->kptr.btf; 11794 ret_btf_id = meta.kptr_field->kptr.btf_id; 11795 if (!btf_is_kernel(ret_btf)) { 11796 regs[BPF_REG_0].type |= MEM_ALLOC; 11797 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 11798 regs[BPF_REG_0].type |= MEM_PERCPU; 11799 } 11800 } else { 11801 if (fn->ret_btf_id == BPF_PTR_POISON) { 11802 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type", 11803 func_id_name(func_id)); 11804 return -EFAULT; 11805 } 11806 ret_btf = btf_vmlinux; 11807 ret_btf_id = *fn->ret_btf_id; 11808 } 11809 if (ret_btf_id == 0) { 11810 verbose(env, "invalid return type %u of func %s#%d\n", 11811 base_type(ret_type), func_id_name(func_id), 11812 func_id); 11813 return -EINVAL; 11814 } 11815 regs[BPF_REG_0].btf = ret_btf; 11816 regs[BPF_REG_0].btf_id = ret_btf_id; 11817 break; 11818 } 11819 default: 11820 verbose(env, "unknown return type %u of func %s#%d\n", 11821 base_type(ret_type), func_id_name(func_id), func_id); 11822 return -EINVAL; 11823 } 11824 11825 if (type_may_be_null(regs[BPF_REG_0].type)) 11826 regs[BPF_REG_0].id = ++env->id_gen; 11827 11828 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 11829 verifier_bug(env, "func %s#%d sets ref_obj_id more than once", 11830 func_id_name(func_id), func_id); 11831 return -EFAULT; 11832 } 11833 11834 if (is_dynptr_ref_function(func_id)) 11835 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 11836 11837 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 11838 /* For release_reference() */ 11839 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 11840 } else if (is_acquire_function(func_id, meta.map_ptr)) { 11841 int id = acquire_reference(env, insn_idx); 11842 11843 if (id < 0) 11844 return id; 11845 /* For mark_ptr_or_null_reg() */ 11846 regs[BPF_REG_0].id = id; 11847 /* For release_reference() */ 11848 regs[BPF_REG_0].ref_obj_id = id; 11849 } 11850 11851 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 11852 if (err) 11853 return err; 11854 11855 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 11856 if (err) 11857 return err; 11858 11859 if ((func_id == BPF_FUNC_get_stack || 11860 func_id == BPF_FUNC_get_task_stack) && 11861 !env->prog->has_callchain_buf) { 11862 const char *err_str; 11863 11864 #ifdef CONFIG_PERF_EVENTS 11865 err = get_callchain_buffers(sysctl_perf_event_max_stack); 11866 err_str = "cannot get callchain buffer for func %s#%d\n"; 11867 #else 11868 err = -ENOTSUPP; 11869 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 11870 #endif 11871 if (err) { 11872 verbose(env, err_str, func_id_name(func_id), func_id); 11873 return err; 11874 } 11875 11876 env->prog->has_callchain_buf = true; 11877 } 11878 11879 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 11880 env->prog->call_get_stack = true; 11881 11882 if (func_id == BPF_FUNC_get_func_ip) { 11883 if (check_get_func_ip(env)) 11884 return -ENOTSUPP; 11885 env->prog->call_get_func_ip = true; 11886 } 11887 11888 if (changes_data) 11889 clear_all_pkt_pointers(env); 11890 return 0; 11891 } 11892 11893 /* mark_btf_func_reg_size() is used when the reg size is determined by 11894 * the BTF func_proto's return value size and argument. 11895 */ 11896 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs, 11897 u32 regno, size_t reg_size) 11898 { 11899 struct bpf_reg_state *reg = ®s[regno]; 11900 11901 if (regno == BPF_REG_0) { 11902 /* Function return value */ 11903 reg->live |= REG_LIVE_WRITTEN; 11904 reg->subreg_def = reg_size == sizeof(u64) ? 11905 DEF_NOT_SUBREG : env->insn_idx + 1; 11906 } else { 11907 /* Function argument */ 11908 if (reg_size == sizeof(u64)) { 11909 mark_insn_zext(env, reg); 11910 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 11911 } else { 11912 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 11913 } 11914 } 11915 } 11916 11917 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 11918 size_t reg_size) 11919 { 11920 return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size); 11921 } 11922 11923 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 11924 { 11925 return meta->kfunc_flags & KF_ACQUIRE; 11926 } 11927 11928 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 11929 { 11930 return meta->kfunc_flags & KF_RELEASE; 11931 } 11932 11933 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 11934 { 11935 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 11936 } 11937 11938 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 11939 { 11940 return meta->kfunc_flags & KF_SLEEPABLE; 11941 } 11942 11943 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 11944 { 11945 return meta->kfunc_flags & KF_DESTRUCTIVE; 11946 } 11947 11948 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 11949 { 11950 return meta->kfunc_flags & KF_RCU; 11951 } 11952 11953 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 11954 { 11955 return meta->kfunc_flags & KF_RCU_PROTECTED; 11956 } 11957 11958 static bool is_kfunc_arg_mem_size(const struct btf *btf, 11959 const struct btf_param *arg, 11960 const struct bpf_reg_state *reg) 11961 { 11962 const struct btf_type *t; 11963 11964 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11965 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11966 return false; 11967 11968 return btf_param_match_suffix(btf, arg, "__sz"); 11969 } 11970 11971 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 11972 const struct btf_param *arg, 11973 const struct bpf_reg_state *reg) 11974 { 11975 const struct btf_type *t; 11976 11977 t = btf_type_skip_modifiers(btf, arg->type, NULL); 11978 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 11979 return false; 11980 11981 return btf_param_match_suffix(btf, arg, "__szk"); 11982 } 11983 11984 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 11985 { 11986 return btf_param_match_suffix(btf, arg, "__opt"); 11987 } 11988 11989 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 11990 { 11991 return btf_param_match_suffix(btf, arg, "__k"); 11992 } 11993 11994 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 11995 { 11996 return btf_param_match_suffix(btf, arg, "__ign"); 11997 } 11998 11999 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 12000 { 12001 return btf_param_match_suffix(btf, arg, "__map"); 12002 } 12003 12004 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 12005 { 12006 return btf_param_match_suffix(btf, arg, "__alloc"); 12007 } 12008 12009 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 12010 { 12011 return btf_param_match_suffix(btf, arg, "__uninit"); 12012 } 12013 12014 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 12015 { 12016 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 12017 } 12018 12019 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 12020 { 12021 return btf_param_match_suffix(btf, arg, "__nullable"); 12022 } 12023 12024 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 12025 { 12026 return btf_param_match_suffix(btf, arg, "__str"); 12027 } 12028 12029 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg) 12030 { 12031 return btf_param_match_suffix(btf, arg, "__irq_flag"); 12032 } 12033 12034 static bool is_kfunc_arg_prog(const struct btf *btf, const struct btf_param *arg) 12035 { 12036 return btf_param_match_suffix(btf, arg, "__prog"); 12037 } 12038 12039 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 12040 const struct btf_param *arg, 12041 const char *name) 12042 { 12043 int len, target_len = strlen(name); 12044 const char *param_name; 12045 12046 param_name = btf_name_by_offset(btf, arg->name_off); 12047 if (str_is_empty(param_name)) 12048 return false; 12049 len = strlen(param_name); 12050 if (len != target_len) 12051 return false; 12052 if (strcmp(param_name, name)) 12053 return false; 12054 12055 return true; 12056 } 12057 12058 enum { 12059 KF_ARG_DYNPTR_ID, 12060 KF_ARG_LIST_HEAD_ID, 12061 KF_ARG_LIST_NODE_ID, 12062 KF_ARG_RB_ROOT_ID, 12063 KF_ARG_RB_NODE_ID, 12064 KF_ARG_WORKQUEUE_ID, 12065 KF_ARG_RES_SPIN_LOCK_ID, 12066 }; 12067 12068 BTF_ID_LIST(kf_arg_btf_ids) 12069 BTF_ID(struct, bpf_dynptr) 12070 BTF_ID(struct, bpf_list_head) 12071 BTF_ID(struct, bpf_list_node) 12072 BTF_ID(struct, bpf_rb_root) 12073 BTF_ID(struct, bpf_rb_node) 12074 BTF_ID(struct, bpf_wq) 12075 BTF_ID(struct, bpf_res_spin_lock) 12076 12077 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 12078 const struct btf_param *arg, int type) 12079 { 12080 const struct btf_type *t; 12081 u32 res_id; 12082 12083 t = btf_type_skip_modifiers(btf, arg->type, NULL); 12084 if (!t) 12085 return false; 12086 if (!btf_type_is_ptr(t)) 12087 return false; 12088 t = btf_type_skip_modifiers(btf, t->type, &res_id); 12089 if (!t) 12090 return false; 12091 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 12092 } 12093 12094 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 12095 { 12096 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 12097 } 12098 12099 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 12100 { 12101 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 12102 } 12103 12104 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 12105 { 12106 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 12107 } 12108 12109 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 12110 { 12111 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 12112 } 12113 12114 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 12115 { 12116 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 12117 } 12118 12119 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 12120 { 12121 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 12122 } 12123 12124 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg) 12125 { 12126 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID); 12127 } 12128 12129 static bool is_rbtree_node_type(const struct btf_type *t) 12130 { 12131 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]); 12132 } 12133 12134 static bool is_list_node_type(const struct btf_type *t) 12135 { 12136 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]); 12137 } 12138 12139 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 12140 const struct btf_param *arg) 12141 { 12142 const struct btf_type *t; 12143 12144 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 12145 if (!t) 12146 return false; 12147 12148 return true; 12149 } 12150 12151 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 12152 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 12153 const struct btf *btf, 12154 const struct btf_type *t, int rec) 12155 { 12156 const struct btf_type *member_type; 12157 const struct btf_member *member; 12158 u32 i; 12159 12160 if (!btf_type_is_struct(t)) 12161 return false; 12162 12163 for_each_member(i, t, member) { 12164 const struct btf_array *array; 12165 12166 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 12167 if (btf_type_is_struct(member_type)) { 12168 if (rec >= 3) { 12169 verbose(env, "max struct nesting depth exceeded\n"); 12170 return false; 12171 } 12172 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 12173 return false; 12174 continue; 12175 } 12176 if (btf_type_is_array(member_type)) { 12177 array = btf_array(member_type); 12178 if (!array->nelems) 12179 return false; 12180 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 12181 if (!btf_type_is_scalar(member_type)) 12182 return false; 12183 continue; 12184 } 12185 if (!btf_type_is_scalar(member_type)) 12186 return false; 12187 } 12188 return true; 12189 } 12190 12191 enum kfunc_ptr_arg_type { 12192 KF_ARG_PTR_TO_CTX, 12193 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 12194 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 12195 KF_ARG_PTR_TO_DYNPTR, 12196 KF_ARG_PTR_TO_ITER, 12197 KF_ARG_PTR_TO_LIST_HEAD, 12198 KF_ARG_PTR_TO_LIST_NODE, 12199 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 12200 KF_ARG_PTR_TO_MEM, 12201 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 12202 KF_ARG_PTR_TO_CALLBACK, 12203 KF_ARG_PTR_TO_RB_ROOT, 12204 KF_ARG_PTR_TO_RB_NODE, 12205 KF_ARG_PTR_TO_NULL, 12206 KF_ARG_PTR_TO_CONST_STR, 12207 KF_ARG_PTR_TO_MAP, 12208 KF_ARG_PTR_TO_WORKQUEUE, 12209 KF_ARG_PTR_TO_IRQ_FLAG, 12210 KF_ARG_PTR_TO_RES_SPIN_LOCK, 12211 }; 12212 12213 enum special_kfunc_type { 12214 KF_bpf_obj_new_impl, 12215 KF_bpf_obj_drop_impl, 12216 KF_bpf_refcount_acquire_impl, 12217 KF_bpf_list_push_front_impl, 12218 KF_bpf_list_push_back_impl, 12219 KF_bpf_list_pop_front, 12220 KF_bpf_list_pop_back, 12221 KF_bpf_list_front, 12222 KF_bpf_list_back, 12223 KF_bpf_cast_to_kern_ctx, 12224 KF_bpf_rdonly_cast, 12225 KF_bpf_rcu_read_lock, 12226 KF_bpf_rcu_read_unlock, 12227 KF_bpf_rbtree_remove, 12228 KF_bpf_rbtree_add_impl, 12229 KF_bpf_rbtree_first, 12230 KF_bpf_rbtree_root, 12231 KF_bpf_rbtree_left, 12232 KF_bpf_rbtree_right, 12233 KF_bpf_dynptr_from_skb, 12234 KF_bpf_dynptr_from_xdp, 12235 KF_bpf_dynptr_slice, 12236 KF_bpf_dynptr_slice_rdwr, 12237 KF_bpf_dynptr_clone, 12238 KF_bpf_percpu_obj_new_impl, 12239 KF_bpf_percpu_obj_drop_impl, 12240 KF_bpf_throw, 12241 KF_bpf_wq_set_callback_impl, 12242 KF_bpf_preempt_disable, 12243 KF_bpf_preempt_enable, 12244 KF_bpf_iter_css_task_new, 12245 KF_bpf_session_cookie, 12246 KF_bpf_get_kmem_cache, 12247 KF_bpf_local_irq_save, 12248 KF_bpf_local_irq_restore, 12249 KF_bpf_iter_num_new, 12250 KF_bpf_iter_num_next, 12251 KF_bpf_iter_num_destroy, 12252 KF_bpf_set_dentry_xattr, 12253 KF_bpf_remove_dentry_xattr, 12254 KF_bpf_res_spin_lock, 12255 KF_bpf_res_spin_unlock, 12256 KF_bpf_res_spin_lock_irqsave, 12257 KF_bpf_res_spin_unlock_irqrestore, 12258 KF___bpf_trap, 12259 }; 12260 12261 BTF_ID_LIST(special_kfunc_list) 12262 BTF_ID(func, bpf_obj_new_impl) 12263 BTF_ID(func, bpf_obj_drop_impl) 12264 BTF_ID(func, bpf_refcount_acquire_impl) 12265 BTF_ID(func, bpf_list_push_front_impl) 12266 BTF_ID(func, bpf_list_push_back_impl) 12267 BTF_ID(func, bpf_list_pop_front) 12268 BTF_ID(func, bpf_list_pop_back) 12269 BTF_ID(func, bpf_list_front) 12270 BTF_ID(func, bpf_list_back) 12271 BTF_ID(func, bpf_cast_to_kern_ctx) 12272 BTF_ID(func, bpf_rdonly_cast) 12273 BTF_ID(func, bpf_rcu_read_lock) 12274 BTF_ID(func, bpf_rcu_read_unlock) 12275 BTF_ID(func, bpf_rbtree_remove) 12276 BTF_ID(func, bpf_rbtree_add_impl) 12277 BTF_ID(func, bpf_rbtree_first) 12278 BTF_ID(func, bpf_rbtree_root) 12279 BTF_ID(func, bpf_rbtree_left) 12280 BTF_ID(func, bpf_rbtree_right) 12281 #ifdef CONFIG_NET 12282 BTF_ID(func, bpf_dynptr_from_skb) 12283 BTF_ID(func, bpf_dynptr_from_xdp) 12284 #else 12285 BTF_ID_UNUSED 12286 BTF_ID_UNUSED 12287 #endif 12288 BTF_ID(func, bpf_dynptr_slice) 12289 BTF_ID(func, bpf_dynptr_slice_rdwr) 12290 BTF_ID(func, bpf_dynptr_clone) 12291 BTF_ID(func, bpf_percpu_obj_new_impl) 12292 BTF_ID(func, bpf_percpu_obj_drop_impl) 12293 BTF_ID(func, bpf_throw) 12294 BTF_ID(func, bpf_wq_set_callback_impl) 12295 BTF_ID(func, bpf_preempt_disable) 12296 BTF_ID(func, bpf_preempt_enable) 12297 #ifdef CONFIG_CGROUPS 12298 BTF_ID(func, bpf_iter_css_task_new) 12299 #else 12300 BTF_ID_UNUSED 12301 #endif 12302 #ifdef CONFIG_BPF_EVENTS 12303 BTF_ID(func, bpf_session_cookie) 12304 #else 12305 BTF_ID_UNUSED 12306 #endif 12307 BTF_ID(func, bpf_get_kmem_cache) 12308 BTF_ID(func, bpf_local_irq_save) 12309 BTF_ID(func, bpf_local_irq_restore) 12310 BTF_ID(func, bpf_iter_num_new) 12311 BTF_ID(func, bpf_iter_num_next) 12312 BTF_ID(func, bpf_iter_num_destroy) 12313 #ifdef CONFIG_BPF_LSM 12314 BTF_ID(func, bpf_set_dentry_xattr) 12315 BTF_ID(func, bpf_remove_dentry_xattr) 12316 #else 12317 BTF_ID_UNUSED 12318 BTF_ID_UNUSED 12319 #endif 12320 BTF_ID(func, bpf_res_spin_lock) 12321 BTF_ID(func, bpf_res_spin_unlock) 12322 BTF_ID(func, bpf_res_spin_lock_irqsave) 12323 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 12324 BTF_ID(func, __bpf_trap) 12325 12326 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 12327 { 12328 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 12329 meta->arg_owning_ref) { 12330 return false; 12331 } 12332 12333 return meta->kfunc_flags & KF_RET_NULL; 12334 } 12335 12336 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 12337 { 12338 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 12339 } 12340 12341 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 12342 { 12343 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 12344 } 12345 12346 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 12347 { 12348 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 12349 } 12350 12351 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 12352 { 12353 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 12354 } 12355 12356 static enum kfunc_ptr_arg_type 12357 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 12358 struct bpf_kfunc_call_arg_meta *meta, 12359 const struct btf_type *t, const struct btf_type *ref_t, 12360 const char *ref_tname, const struct btf_param *args, 12361 int argno, int nargs) 12362 { 12363 u32 regno = argno + 1; 12364 struct bpf_reg_state *regs = cur_regs(env); 12365 struct bpf_reg_state *reg = ®s[regno]; 12366 bool arg_mem_size = false; 12367 12368 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 12369 return KF_ARG_PTR_TO_CTX; 12370 12371 /* In this function, we verify the kfunc's BTF as per the argument type, 12372 * leaving the rest of the verification with respect to the register 12373 * type to our caller. When a set of conditions hold in the BTF type of 12374 * arguments, we resolve it to a known kfunc_ptr_arg_type. 12375 */ 12376 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 12377 return KF_ARG_PTR_TO_CTX; 12378 12379 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 12380 return KF_ARG_PTR_TO_NULL; 12381 12382 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 12383 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 12384 12385 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 12386 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 12387 12388 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 12389 return KF_ARG_PTR_TO_DYNPTR; 12390 12391 if (is_kfunc_arg_iter(meta, argno, &args[argno])) 12392 return KF_ARG_PTR_TO_ITER; 12393 12394 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 12395 return KF_ARG_PTR_TO_LIST_HEAD; 12396 12397 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 12398 return KF_ARG_PTR_TO_LIST_NODE; 12399 12400 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 12401 return KF_ARG_PTR_TO_RB_ROOT; 12402 12403 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 12404 return KF_ARG_PTR_TO_RB_NODE; 12405 12406 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 12407 return KF_ARG_PTR_TO_CONST_STR; 12408 12409 if (is_kfunc_arg_map(meta->btf, &args[argno])) 12410 return KF_ARG_PTR_TO_MAP; 12411 12412 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 12413 return KF_ARG_PTR_TO_WORKQUEUE; 12414 12415 if (is_kfunc_arg_irq_flag(meta->btf, &args[argno])) 12416 return KF_ARG_PTR_TO_IRQ_FLAG; 12417 12418 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno])) 12419 return KF_ARG_PTR_TO_RES_SPIN_LOCK; 12420 12421 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 12422 if (!btf_type_is_struct(ref_t)) { 12423 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 12424 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 12425 return -EINVAL; 12426 } 12427 return KF_ARG_PTR_TO_BTF_ID; 12428 } 12429 12430 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 12431 return KF_ARG_PTR_TO_CALLBACK; 12432 12433 if (argno + 1 < nargs && 12434 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 12435 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 12436 arg_mem_size = true; 12437 12438 /* This is the catch all argument type of register types supported by 12439 * check_helper_mem_access. However, we only allow when argument type is 12440 * pointer to scalar, or struct composed (recursively) of scalars. When 12441 * arg_mem_size is true, the pointer can be void *. 12442 */ 12443 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 12444 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 12445 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 12446 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 12447 return -EINVAL; 12448 } 12449 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 12450 } 12451 12452 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 12453 struct bpf_reg_state *reg, 12454 const struct btf_type *ref_t, 12455 const char *ref_tname, u32 ref_id, 12456 struct bpf_kfunc_call_arg_meta *meta, 12457 int argno) 12458 { 12459 const struct btf_type *reg_ref_t; 12460 bool strict_type_match = false; 12461 const struct btf *reg_btf; 12462 const char *reg_ref_tname; 12463 bool taking_projection; 12464 bool struct_same; 12465 u32 reg_ref_id; 12466 12467 if (base_type(reg->type) == PTR_TO_BTF_ID) { 12468 reg_btf = reg->btf; 12469 reg_ref_id = reg->btf_id; 12470 } else { 12471 reg_btf = btf_vmlinux; 12472 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 12473 } 12474 12475 /* Enforce strict type matching for calls to kfuncs that are acquiring 12476 * or releasing a reference, or are no-cast aliases. We do _not_ 12477 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 12478 * as we want to enable BPF programs to pass types that are bitwise 12479 * equivalent without forcing them to explicitly cast with something 12480 * like bpf_cast_to_kern_ctx(). 12481 * 12482 * For example, say we had a type like the following: 12483 * 12484 * struct bpf_cpumask { 12485 * cpumask_t cpumask; 12486 * refcount_t usage; 12487 * }; 12488 * 12489 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 12490 * to a struct cpumask, so it would be safe to pass a struct 12491 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 12492 * 12493 * The philosophy here is similar to how we allow scalars of different 12494 * types to be passed to kfuncs as long as the size is the same. The 12495 * only difference here is that we're simply allowing 12496 * btf_struct_ids_match() to walk the struct at the 0th offset, and 12497 * resolve types. 12498 */ 12499 if ((is_kfunc_release(meta) && reg->ref_obj_id) || 12500 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 12501 strict_type_match = true; 12502 12503 WARN_ON_ONCE(is_kfunc_release(meta) && 12504 (reg->off || !tnum_is_const(reg->var_off) || 12505 reg->var_off.value)); 12506 12507 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 12508 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 12509 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match); 12510 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 12511 * actually use it -- it must cast to the underlying type. So we allow 12512 * caller to pass in the underlying type. 12513 */ 12514 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 12515 if (!taking_projection && !struct_same) { 12516 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 12517 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 12518 btf_type_str(reg_ref_t), reg_ref_tname); 12519 return -EINVAL; 12520 } 12521 return 0; 12522 } 12523 12524 static int process_irq_flag(struct bpf_verifier_env *env, int regno, 12525 struct bpf_kfunc_call_arg_meta *meta) 12526 { 12527 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 12528 int err, kfunc_class = IRQ_NATIVE_KFUNC; 12529 bool irq_save; 12530 12531 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] || 12532 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) { 12533 irq_save = true; 12534 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 12535 kfunc_class = IRQ_LOCK_KFUNC; 12536 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] || 12537 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) { 12538 irq_save = false; 12539 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 12540 kfunc_class = IRQ_LOCK_KFUNC; 12541 } else { 12542 verifier_bug(env, "unknown irq flags kfunc"); 12543 return -EFAULT; 12544 } 12545 12546 if (irq_save) { 12547 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 12548 verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1); 12549 return -EINVAL; 12550 } 12551 12552 err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false); 12553 if (err) 12554 return err; 12555 12556 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 12557 if (err) 12558 return err; 12559 } else { 12560 err = is_irq_flag_reg_valid_init(env, reg); 12561 if (err) { 12562 verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1); 12563 return err; 12564 } 12565 12566 err = mark_irq_flag_read(env, reg); 12567 if (err) 12568 return err; 12569 12570 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 12571 if (err) 12572 return err; 12573 } 12574 return 0; 12575 } 12576 12577 12578 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 12579 { 12580 struct btf_record *rec = reg_btf_record(reg); 12581 12582 if (!env->cur_state->active_locks) { 12583 verifier_bug(env, "%s w/o active lock", __func__); 12584 return -EFAULT; 12585 } 12586 12587 if (type_flag(reg->type) & NON_OWN_REF) { 12588 verifier_bug(env, "NON_OWN_REF already set"); 12589 return -EFAULT; 12590 } 12591 12592 reg->type |= NON_OWN_REF; 12593 if (rec->refcount_off >= 0) 12594 reg->type |= MEM_RCU; 12595 12596 return 0; 12597 } 12598 12599 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 12600 { 12601 struct bpf_verifier_state *state = env->cur_state; 12602 struct bpf_func_state *unused; 12603 struct bpf_reg_state *reg; 12604 int i; 12605 12606 if (!ref_obj_id) { 12607 verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion"); 12608 return -EFAULT; 12609 } 12610 12611 for (i = 0; i < state->acquired_refs; i++) { 12612 if (state->refs[i].id != ref_obj_id) 12613 continue; 12614 12615 /* Clear ref_obj_id here so release_reference doesn't clobber 12616 * the whole reg 12617 */ 12618 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 12619 if (reg->ref_obj_id == ref_obj_id) { 12620 reg->ref_obj_id = 0; 12621 ref_set_non_owning(env, reg); 12622 } 12623 })); 12624 return 0; 12625 } 12626 12627 verifier_bug(env, "ref state missing for ref_obj_id"); 12628 return -EFAULT; 12629 } 12630 12631 /* Implementation details: 12632 * 12633 * Each register points to some region of memory, which we define as an 12634 * allocation. Each allocation may embed a bpf_spin_lock which protects any 12635 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 12636 * allocation. The lock and the data it protects are colocated in the same 12637 * memory region. 12638 * 12639 * Hence, everytime a register holds a pointer value pointing to such 12640 * allocation, the verifier preserves a unique reg->id for it. 12641 * 12642 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 12643 * bpf_spin_lock is called. 12644 * 12645 * To enable this, lock state in the verifier captures two values: 12646 * active_lock.ptr = Register's type specific pointer 12647 * active_lock.id = A unique ID for each register pointer value 12648 * 12649 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 12650 * supported register types. 12651 * 12652 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 12653 * allocated objects is the reg->btf pointer. 12654 * 12655 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 12656 * can establish the provenance of the map value statically for each distinct 12657 * lookup into such maps. They always contain a single map value hence unique 12658 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 12659 * 12660 * So, in case of global variables, they use array maps with max_entries = 1, 12661 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 12662 * into the same map value as max_entries is 1, as described above). 12663 * 12664 * In case of inner map lookups, the inner map pointer has same map_ptr as the 12665 * outer map pointer (in verifier context), but each lookup into an inner map 12666 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 12667 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 12668 * will get different reg->id assigned to each lookup, hence different 12669 * active_lock.id. 12670 * 12671 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 12672 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 12673 * returned from bpf_obj_new. Each allocation receives a new reg->id. 12674 */ 12675 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 12676 { 12677 struct bpf_reference_state *s; 12678 void *ptr; 12679 u32 id; 12680 12681 switch ((int)reg->type) { 12682 case PTR_TO_MAP_VALUE: 12683 ptr = reg->map_ptr; 12684 break; 12685 case PTR_TO_BTF_ID | MEM_ALLOC: 12686 ptr = reg->btf; 12687 break; 12688 default: 12689 verifier_bug(env, "unknown reg type for lock check"); 12690 return -EFAULT; 12691 } 12692 id = reg->id; 12693 12694 if (!env->cur_state->active_locks) 12695 return -EINVAL; 12696 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 12697 if (!s) { 12698 verbose(env, "held lock and object are not in the same allocation\n"); 12699 return -EINVAL; 12700 } 12701 return 0; 12702 } 12703 12704 static bool is_bpf_list_api_kfunc(u32 btf_id) 12705 { 12706 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12707 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12708 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 12709 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 12710 btf_id == special_kfunc_list[KF_bpf_list_front] || 12711 btf_id == special_kfunc_list[KF_bpf_list_back]; 12712 } 12713 12714 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 12715 { 12716 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 12717 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12718 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 12719 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 12720 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 12721 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 12722 } 12723 12724 static bool is_bpf_iter_num_api_kfunc(u32 btf_id) 12725 { 12726 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] || 12727 btf_id == special_kfunc_list[KF_bpf_iter_num_next] || 12728 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy]; 12729 } 12730 12731 static bool is_bpf_graph_api_kfunc(u32 btf_id) 12732 { 12733 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 12734 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 12735 } 12736 12737 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id) 12738 { 12739 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 12740 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 12741 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 12742 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]; 12743 } 12744 12745 static bool kfunc_spin_allowed(u32 btf_id) 12746 { 12747 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) || 12748 is_bpf_res_spin_lock_kfunc(btf_id); 12749 } 12750 12751 static bool is_sync_callback_calling_kfunc(u32 btf_id) 12752 { 12753 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 12754 } 12755 12756 static bool is_async_callback_calling_kfunc(u32 btf_id) 12757 { 12758 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 12759 } 12760 12761 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 12762 { 12763 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 12764 insn->imm == special_kfunc_list[KF_bpf_throw]; 12765 } 12766 12767 static bool is_bpf_wq_set_callback_impl_kfunc(u32 btf_id) 12768 { 12769 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback_impl]; 12770 } 12771 12772 static bool is_callback_calling_kfunc(u32 btf_id) 12773 { 12774 return is_sync_callback_calling_kfunc(btf_id) || 12775 is_async_callback_calling_kfunc(btf_id); 12776 } 12777 12778 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 12779 { 12780 return is_bpf_rbtree_api_kfunc(btf_id); 12781 } 12782 12783 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 12784 enum btf_field_type head_field_type, 12785 u32 kfunc_btf_id) 12786 { 12787 bool ret; 12788 12789 switch (head_field_type) { 12790 case BPF_LIST_HEAD: 12791 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 12792 break; 12793 case BPF_RB_ROOT: 12794 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 12795 break; 12796 default: 12797 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 12798 btf_field_type_name(head_field_type)); 12799 return false; 12800 } 12801 12802 if (!ret) 12803 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 12804 btf_field_type_name(head_field_type)); 12805 return ret; 12806 } 12807 12808 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 12809 enum btf_field_type node_field_type, 12810 u32 kfunc_btf_id) 12811 { 12812 bool ret; 12813 12814 switch (node_field_type) { 12815 case BPF_LIST_NODE: 12816 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12817 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 12818 break; 12819 case BPF_RB_NODE: 12820 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12821 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 12822 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 12823 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 12824 break; 12825 default: 12826 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 12827 btf_field_type_name(node_field_type)); 12828 return false; 12829 } 12830 12831 if (!ret) 12832 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 12833 btf_field_type_name(node_field_type)); 12834 return ret; 12835 } 12836 12837 static int 12838 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 12839 struct bpf_reg_state *reg, u32 regno, 12840 struct bpf_kfunc_call_arg_meta *meta, 12841 enum btf_field_type head_field_type, 12842 struct btf_field **head_field) 12843 { 12844 const char *head_type_name; 12845 struct btf_field *field; 12846 struct btf_record *rec; 12847 u32 head_off; 12848 12849 if (meta->btf != btf_vmlinux) { 12850 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 12851 return -EFAULT; 12852 } 12853 12854 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 12855 return -EFAULT; 12856 12857 head_type_name = btf_field_type_name(head_field_type); 12858 if (!tnum_is_const(reg->var_off)) { 12859 verbose(env, 12860 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 12861 regno, head_type_name); 12862 return -EINVAL; 12863 } 12864 12865 rec = reg_btf_record(reg); 12866 head_off = reg->off + reg->var_off.value; 12867 field = btf_record_find(rec, head_off, head_field_type); 12868 if (!field) { 12869 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 12870 return -EINVAL; 12871 } 12872 12873 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 12874 if (check_reg_allocation_locked(env, reg)) { 12875 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 12876 rec->spin_lock_off, head_type_name); 12877 return -EINVAL; 12878 } 12879 12880 if (*head_field) { 12881 verifier_bug(env, "repeating %s arg", head_type_name); 12882 return -EFAULT; 12883 } 12884 *head_field = field; 12885 return 0; 12886 } 12887 12888 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 12889 struct bpf_reg_state *reg, u32 regno, 12890 struct bpf_kfunc_call_arg_meta *meta) 12891 { 12892 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 12893 &meta->arg_list_head.field); 12894 } 12895 12896 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 12897 struct bpf_reg_state *reg, u32 regno, 12898 struct bpf_kfunc_call_arg_meta *meta) 12899 { 12900 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 12901 &meta->arg_rbtree_root.field); 12902 } 12903 12904 static int 12905 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 12906 struct bpf_reg_state *reg, u32 regno, 12907 struct bpf_kfunc_call_arg_meta *meta, 12908 enum btf_field_type head_field_type, 12909 enum btf_field_type node_field_type, 12910 struct btf_field **node_field) 12911 { 12912 const char *node_type_name; 12913 const struct btf_type *et, *t; 12914 struct btf_field *field; 12915 u32 node_off; 12916 12917 if (meta->btf != btf_vmlinux) { 12918 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 12919 return -EFAULT; 12920 } 12921 12922 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 12923 return -EFAULT; 12924 12925 node_type_name = btf_field_type_name(node_field_type); 12926 if (!tnum_is_const(reg->var_off)) { 12927 verbose(env, 12928 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 12929 regno, node_type_name); 12930 return -EINVAL; 12931 } 12932 12933 node_off = reg->off + reg->var_off.value; 12934 field = reg_find_field_offset(reg, node_off, node_field_type); 12935 if (!field) { 12936 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 12937 return -EINVAL; 12938 } 12939 12940 field = *node_field; 12941 12942 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 12943 t = btf_type_by_id(reg->btf, reg->btf_id); 12944 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 12945 field->graph_root.value_btf_id, true)) { 12946 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 12947 "in struct %s, but arg is at offset=%d in struct %s\n", 12948 btf_field_type_name(head_field_type), 12949 btf_field_type_name(node_field_type), 12950 field->graph_root.node_offset, 12951 btf_name_by_offset(field->graph_root.btf, et->name_off), 12952 node_off, btf_name_by_offset(reg->btf, t->name_off)); 12953 return -EINVAL; 12954 } 12955 meta->arg_btf = reg->btf; 12956 meta->arg_btf_id = reg->btf_id; 12957 12958 if (node_off != field->graph_root.node_offset) { 12959 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 12960 node_off, btf_field_type_name(node_field_type), 12961 field->graph_root.node_offset, 12962 btf_name_by_offset(field->graph_root.btf, et->name_off)); 12963 return -EINVAL; 12964 } 12965 12966 return 0; 12967 } 12968 12969 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 12970 struct bpf_reg_state *reg, u32 regno, 12971 struct bpf_kfunc_call_arg_meta *meta) 12972 { 12973 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 12974 BPF_LIST_HEAD, BPF_LIST_NODE, 12975 &meta->arg_list_head.field); 12976 } 12977 12978 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 12979 struct bpf_reg_state *reg, u32 regno, 12980 struct bpf_kfunc_call_arg_meta *meta) 12981 { 12982 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 12983 BPF_RB_ROOT, BPF_RB_NODE, 12984 &meta->arg_rbtree_root.field); 12985 } 12986 12987 /* 12988 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 12989 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 12990 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 12991 * them can only be attached to some specific hook points. 12992 */ 12993 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 12994 { 12995 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12996 12997 switch (prog_type) { 12998 case BPF_PROG_TYPE_LSM: 12999 return true; 13000 case BPF_PROG_TYPE_TRACING: 13001 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 13002 return true; 13003 fallthrough; 13004 default: 13005 return in_sleepable(env); 13006 } 13007 } 13008 13009 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 13010 int insn_idx) 13011 { 13012 const char *func_name = meta->func_name, *ref_tname; 13013 const struct btf *btf = meta->btf; 13014 const struct btf_param *args; 13015 struct btf_record *rec; 13016 u32 i, nargs; 13017 int ret; 13018 13019 args = (const struct btf_param *)(meta->func_proto + 1); 13020 nargs = btf_type_vlen(meta->func_proto); 13021 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 13022 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 13023 MAX_BPF_FUNC_REG_ARGS); 13024 return -EINVAL; 13025 } 13026 13027 /* Check that BTF function arguments match actual types that the 13028 * verifier sees. 13029 */ 13030 for (i = 0; i < nargs; i++) { 13031 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 13032 const struct btf_type *t, *ref_t, *resolve_ret; 13033 enum bpf_arg_type arg_type = ARG_DONTCARE; 13034 u32 regno = i + 1, ref_id, type_size; 13035 bool is_ret_buf_sz = false; 13036 int kf_arg_type; 13037 13038 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 13039 13040 if (is_kfunc_arg_ignore(btf, &args[i])) 13041 continue; 13042 13043 if (is_kfunc_arg_prog(btf, &args[i])) { 13044 /* Used to reject repeated use of __prog. */ 13045 if (meta->arg_prog) { 13046 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc"); 13047 return -EFAULT; 13048 } 13049 meta->arg_prog = true; 13050 cur_aux(env)->arg_prog = regno; 13051 continue; 13052 } 13053 13054 if (btf_type_is_scalar(t)) { 13055 if (reg->type != SCALAR_VALUE) { 13056 verbose(env, "R%d is not a scalar\n", regno); 13057 return -EINVAL; 13058 } 13059 13060 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 13061 if (meta->arg_constant.found) { 13062 verifier_bug(env, "only one constant argument permitted"); 13063 return -EFAULT; 13064 } 13065 if (!tnum_is_const(reg->var_off)) { 13066 verbose(env, "R%d must be a known constant\n", regno); 13067 return -EINVAL; 13068 } 13069 ret = mark_chain_precision(env, regno); 13070 if (ret < 0) 13071 return ret; 13072 meta->arg_constant.found = true; 13073 meta->arg_constant.value = reg->var_off.value; 13074 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 13075 meta->r0_rdonly = true; 13076 is_ret_buf_sz = true; 13077 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 13078 is_ret_buf_sz = true; 13079 } 13080 13081 if (is_ret_buf_sz) { 13082 if (meta->r0_size) { 13083 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 13084 return -EINVAL; 13085 } 13086 13087 if (!tnum_is_const(reg->var_off)) { 13088 verbose(env, "R%d is not a const\n", regno); 13089 return -EINVAL; 13090 } 13091 13092 meta->r0_size = reg->var_off.value; 13093 ret = mark_chain_precision(env, regno); 13094 if (ret) 13095 return ret; 13096 } 13097 continue; 13098 } 13099 13100 if (!btf_type_is_ptr(t)) { 13101 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 13102 return -EINVAL; 13103 } 13104 13105 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 13106 (register_is_null(reg) || type_may_be_null(reg->type)) && 13107 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 13108 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 13109 return -EACCES; 13110 } 13111 13112 if (reg->ref_obj_id) { 13113 if (is_kfunc_release(meta) && meta->ref_obj_id) { 13114 verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u", 13115 regno, reg->ref_obj_id, 13116 meta->ref_obj_id); 13117 return -EFAULT; 13118 } 13119 meta->ref_obj_id = reg->ref_obj_id; 13120 if (is_kfunc_release(meta)) 13121 meta->release_regno = regno; 13122 } 13123 13124 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 13125 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 13126 13127 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 13128 if (kf_arg_type < 0) 13129 return kf_arg_type; 13130 13131 switch (kf_arg_type) { 13132 case KF_ARG_PTR_TO_NULL: 13133 continue; 13134 case KF_ARG_PTR_TO_MAP: 13135 if (!reg->map_ptr) { 13136 verbose(env, "pointer in R%d isn't map pointer\n", regno); 13137 return -EINVAL; 13138 } 13139 if (meta->map.ptr && reg->map_ptr->record->wq_off >= 0) { 13140 /* Use map_uid (which is unique id of inner map) to reject: 13141 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 13142 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 13143 * if (inner_map1 && inner_map2) { 13144 * wq = bpf_map_lookup_elem(inner_map1); 13145 * if (wq) 13146 * // mismatch would have been allowed 13147 * bpf_wq_init(wq, inner_map2); 13148 * } 13149 * 13150 * Comparing map_ptr is enough to distinguish normal and outer maps. 13151 */ 13152 if (meta->map.ptr != reg->map_ptr || 13153 meta->map.uid != reg->map_uid) { 13154 verbose(env, 13155 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 13156 meta->map.uid, reg->map_uid); 13157 return -EINVAL; 13158 } 13159 } 13160 meta->map.ptr = reg->map_ptr; 13161 meta->map.uid = reg->map_uid; 13162 fallthrough; 13163 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 13164 case KF_ARG_PTR_TO_BTF_ID: 13165 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 13166 break; 13167 13168 if (!is_trusted_reg(reg)) { 13169 if (!is_kfunc_rcu(meta)) { 13170 verbose(env, "R%d must be referenced or trusted\n", regno); 13171 return -EINVAL; 13172 } 13173 if (!is_rcu_reg(reg)) { 13174 verbose(env, "R%d must be a rcu pointer\n", regno); 13175 return -EINVAL; 13176 } 13177 } 13178 fallthrough; 13179 case KF_ARG_PTR_TO_CTX: 13180 case KF_ARG_PTR_TO_DYNPTR: 13181 case KF_ARG_PTR_TO_ITER: 13182 case KF_ARG_PTR_TO_LIST_HEAD: 13183 case KF_ARG_PTR_TO_LIST_NODE: 13184 case KF_ARG_PTR_TO_RB_ROOT: 13185 case KF_ARG_PTR_TO_RB_NODE: 13186 case KF_ARG_PTR_TO_MEM: 13187 case KF_ARG_PTR_TO_MEM_SIZE: 13188 case KF_ARG_PTR_TO_CALLBACK: 13189 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 13190 case KF_ARG_PTR_TO_CONST_STR: 13191 case KF_ARG_PTR_TO_WORKQUEUE: 13192 case KF_ARG_PTR_TO_IRQ_FLAG: 13193 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 13194 break; 13195 default: 13196 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type); 13197 return -EFAULT; 13198 } 13199 13200 if (is_kfunc_release(meta) && reg->ref_obj_id) 13201 arg_type |= OBJ_RELEASE; 13202 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 13203 if (ret < 0) 13204 return ret; 13205 13206 switch (kf_arg_type) { 13207 case KF_ARG_PTR_TO_CTX: 13208 if (reg->type != PTR_TO_CTX) { 13209 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", 13210 i, reg_type_str(env, reg->type)); 13211 return -EINVAL; 13212 } 13213 13214 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 13215 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 13216 if (ret < 0) 13217 return -EINVAL; 13218 meta->ret_btf_id = ret; 13219 } 13220 break; 13221 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 13222 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 13223 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 13224 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 13225 return -EINVAL; 13226 } 13227 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 13228 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 13229 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 13230 return -EINVAL; 13231 } 13232 } else { 13233 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13234 return -EINVAL; 13235 } 13236 if (!reg->ref_obj_id) { 13237 verbose(env, "allocated object must be referenced\n"); 13238 return -EINVAL; 13239 } 13240 if (meta->btf == btf_vmlinux) { 13241 meta->arg_btf = reg->btf; 13242 meta->arg_btf_id = reg->btf_id; 13243 } 13244 break; 13245 case KF_ARG_PTR_TO_DYNPTR: 13246 { 13247 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 13248 int clone_ref_obj_id = 0; 13249 13250 if (reg->type == CONST_PTR_TO_DYNPTR) 13251 dynptr_arg_type |= MEM_RDONLY; 13252 13253 if (is_kfunc_arg_uninit(btf, &args[i])) 13254 dynptr_arg_type |= MEM_UNINIT; 13255 13256 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 13257 dynptr_arg_type |= DYNPTR_TYPE_SKB; 13258 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 13259 dynptr_arg_type |= DYNPTR_TYPE_XDP; 13260 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 13261 (dynptr_arg_type & MEM_UNINIT)) { 13262 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 13263 13264 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 13265 verifier_bug(env, "no dynptr type for parent of clone"); 13266 return -EFAULT; 13267 } 13268 13269 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 13270 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 13271 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 13272 verifier_bug(env, "missing ref obj id for parent of clone"); 13273 return -EFAULT; 13274 } 13275 } 13276 13277 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 13278 if (ret < 0) 13279 return ret; 13280 13281 if (!(dynptr_arg_type & MEM_UNINIT)) { 13282 int id = dynptr_id(env, reg); 13283 13284 if (id < 0) { 13285 verifier_bug(env, "failed to obtain dynptr id"); 13286 return id; 13287 } 13288 meta->initialized_dynptr.id = id; 13289 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 13290 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 13291 } 13292 13293 break; 13294 } 13295 case KF_ARG_PTR_TO_ITER: 13296 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 13297 if (!check_css_task_iter_allowlist(env)) { 13298 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 13299 return -EINVAL; 13300 } 13301 } 13302 ret = process_iter_arg(env, regno, insn_idx, meta); 13303 if (ret < 0) 13304 return ret; 13305 break; 13306 case KF_ARG_PTR_TO_LIST_HEAD: 13307 if (reg->type != PTR_TO_MAP_VALUE && 13308 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13309 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 13310 return -EINVAL; 13311 } 13312 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 13313 verbose(env, "allocated object must be referenced\n"); 13314 return -EINVAL; 13315 } 13316 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 13317 if (ret < 0) 13318 return ret; 13319 break; 13320 case KF_ARG_PTR_TO_RB_ROOT: 13321 if (reg->type != PTR_TO_MAP_VALUE && 13322 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13323 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 13324 return -EINVAL; 13325 } 13326 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 13327 verbose(env, "allocated object must be referenced\n"); 13328 return -EINVAL; 13329 } 13330 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 13331 if (ret < 0) 13332 return ret; 13333 break; 13334 case KF_ARG_PTR_TO_LIST_NODE: 13335 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13336 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13337 return -EINVAL; 13338 } 13339 if (!reg->ref_obj_id) { 13340 verbose(env, "allocated object must be referenced\n"); 13341 return -EINVAL; 13342 } 13343 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 13344 if (ret < 0) 13345 return ret; 13346 break; 13347 case KF_ARG_PTR_TO_RB_NODE: 13348 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13349 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13350 verbose(env, "arg#%d expected pointer to allocated object\n", i); 13351 return -EINVAL; 13352 } 13353 if (!reg->ref_obj_id) { 13354 verbose(env, "allocated object must be referenced\n"); 13355 return -EINVAL; 13356 } 13357 } else { 13358 if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) { 13359 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name); 13360 return -EINVAL; 13361 } 13362 if (in_rbtree_lock_required_cb(env)) { 13363 verbose(env, "%s not allowed in rbtree cb\n", func_name); 13364 return -EINVAL; 13365 } 13366 } 13367 13368 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 13369 if (ret < 0) 13370 return ret; 13371 break; 13372 case KF_ARG_PTR_TO_MAP: 13373 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 13374 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 13375 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 13376 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 13377 fallthrough; 13378 case KF_ARG_PTR_TO_BTF_ID: 13379 /* Only base_type is checked, further checks are done here */ 13380 if ((base_type(reg->type) != PTR_TO_BTF_ID || 13381 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 13382 !reg2btf_ids[base_type(reg->type)]) { 13383 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 13384 verbose(env, "expected %s or socket\n", 13385 reg_type_str(env, base_type(reg->type) | 13386 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 13387 return -EINVAL; 13388 } 13389 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 13390 if (ret < 0) 13391 return ret; 13392 break; 13393 case KF_ARG_PTR_TO_MEM: 13394 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 13395 if (IS_ERR(resolve_ret)) { 13396 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 13397 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 13398 return -EINVAL; 13399 } 13400 ret = check_mem_reg(env, reg, regno, type_size); 13401 if (ret < 0) 13402 return ret; 13403 break; 13404 case KF_ARG_PTR_TO_MEM_SIZE: 13405 { 13406 struct bpf_reg_state *buff_reg = ®s[regno]; 13407 const struct btf_param *buff_arg = &args[i]; 13408 struct bpf_reg_state *size_reg = ®s[regno + 1]; 13409 const struct btf_param *size_arg = &args[i + 1]; 13410 13411 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 13412 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 13413 if (ret < 0) { 13414 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 13415 return ret; 13416 } 13417 } 13418 13419 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 13420 if (meta->arg_constant.found) { 13421 verifier_bug(env, "only one constant argument permitted"); 13422 return -EFAULT; 13423 } 13424 if (!tnum_is_const(size_reg->var_off)) { 13425 verbose(env, "R%d must be a known constant\n", regno + 1); 13426 return -EINVAL; 13427 } 13428 meta->arg_constant.found = true; 13429 meta->arg_constant.value = size_reg->var_off.value; 13430 } 13431 13432 /* Skip next '__sz' or '__szk' argument */ 13433 i++; 13434 break; 13435 } 13436 case KF_ARG_PTR_TO_CALLBACK: 13437 if (reg->type != PTR_TO_FUNC) { 13438 verbose(env, "arg%d expected pointer to func\n", i); 13439 return -EINVAL; 13440 } 13441 meta->subprogno = reg->subprogno; 13442 break; 13443 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 13444 if (!type_is_ptr_alloc_obj(reg->type)) { 13445 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 13446 return -EINVAL; 13447 } 13448 if (!type_is_non_owning_ref(reg->type)) 13449 meta->arg_owning_ref = true; 13450 13451 rec = reg_btf_record(reg); 13452 if (!rec) { 13453 verifier_bug(env, "Couldn't find btf_record"); 13454 return -EFAULT; 13455 } 13456 13457 if (rec->refcount_off < 0) { 13458 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 13459 return -EINVAL; 13460 } 13461 13462 meta->arg_btf = reg->btf; 13463 meta->arg_btf_id = reg->btf_id; 13464 break; 13465 case KF_ARG_PTR_TO_CONST_STR: 13466 if (reg->type != PTR_TO_MAP_VALUE) { 13467 verbose(env, "arg#%d doesn't point to a const string\n", i); 13468 return -EINVAL; 13469 } 13470 ret = check_reg_const_str(env, reg, regno); 13471 if (ret) 13472 return ret; 13473 break; 13474 case KF_ARG_PTR_TO_WORKQUEUE: 13475 if (reg->type != PTR_TO_MAP_VALUE) { 13476 verbose(env, "arg#%d doesn't point to a map value\n", i); 13477 return -EINVAL; 13478 } 13479 ret = process_wq_func(env, regno, meta); 13480 if (ret < 0) 13481 return ret; 13482 break; 13483 case KF_ARG_PTR_TO_IRQ_FLAG: 13484 if (reg->type != PTR_TO_STACK) { 13485 verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i); 13486 return -EINVAL; 13487 } 13488 ret = process_irq_flag(env, regno, meta); 13489 if (ret < 0) 13490 return ret; 13491 break; 13492 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 13493 { 13494 int flags = PROCESS_RES_LOCK; 13495 13496 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 13497 verbose(env, "arg#%d doesn't point to map value or allocated object\n", i); 13498 return -EINVAL; 13499 } 13500 13501 if (!is_bpf_res_spin_lock_kfunc(meta->func_id)) 13502 return -EFAULT; 13503 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13504 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 13505 flags |= PROCESS_SPIN_LOCK; 13506 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 13507 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 13508 flags |= PROCESS_LOCK_IRQ; 13509 ret = process_spin_lock(env, regno, flags); 13510 if (ret < 0) 13511 return ret; 13512 break; 13513 } 13514 } 13515 } 13516 13517 if (is_kfunc_release(meta) && !meta->release_regno) { 13518 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 13519 func_name); 13520 return -EINVAL; 13521 } 13522 13523 return 0; 13524 } 13525 13526 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 13527 struct bpf_insn *insn, 13528 struct bpf_kfunc_call_arg_meta *meta, 13529 const char **kfunc_name) 13530 { 13531 const struct btf_type *func, *func_proto; 13532 u32 func_id, *kfunc_flags; 13533 const char *func_name; 13534 struct btf *desc_btf; 13535 13536 if (kfunc_name) 13537 *kfunc_name = NULL; 13538 13539 if (!insn->imm) 13540 return -EINVAL; 13541 13542 desc_btf = find_kfunc_desc_btf(env, insn->off); 13543 if (IS_ERR(desc_btf)) 13544 return PTR_ERR(desc_btf); 13545 13546 func_id = insn->imm; 13547 func = btf_type_by_id(desc_btf, func_id); 13548 func_name = btf_name_by_offset(desc_btf, func->name_off); 13549 if (kfunc_name) 13550 *kfunc_name = func_name; 13551 func_proto = btf_type_by_id(desc_btf, func->type); 13552 13553 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 13554 if (!kfunc_flags) { 13555 return -EACCES; 13556 } 13557 13558 memset(meta, 0, sizeof(*meta)); 13559 meta->btf = desc_btf; 13560 meta->func_id = func_id; 13561 meta->kfunc_flags = *kfunc_flags; 13562 meta->func_proto = func_proto; 13563 meta->func_name = func_name; 13564 13565 return 0; 13566 } 13567 13568 /* check special kfuncs and return: 13569 * 1 - not fall-through to 'else' branch, continue verification 13570 * 0 - fall-through to 'else' branch 13571 * < 0 - not fall-through to 'else' branch, return error 13572 */ 13573 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 13574 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 13575 const struct btf_type *ptr_type, struct btf *desc_btf) 13576 { 13577 const struct btf_type *ret_t; 13578 int err = 0; 13579 13580 if (meta->btf != btf_vmlinux) 13581 return 0; 13582 13583 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 13584 meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13585 struct btf_struct_meta *struct_meta; 13586 struct btf *ret_btf; 13587 u32 ret_btf_id; 13588 13589 if (meta->func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 13590 return -ENOMEM; 13591 13592 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 13593 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 13594 return -EINVAL; 13595 } 13596 13597 ret_btf = env->prog->aux->btf; 13598 ret_btf_id = meta->arg_constant.value; 13599 13600 /* This may be NULL due to user not supplying a BTF */ 13601 if (!ret_btf) { 13602 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 13603 return -EINVAL; 13604 } 13605 13606 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 13607 if (!ret_t || !__btf_type_is_struct(ret_t)) { 13608 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 13609 return -EINVAL; 13610 } 13611 13612 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13613 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 13614 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 13615 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 13616 return -EINVAL; 13617 } 13618 13619 if (!bpf_global_percpu_ma_set) { 13620 mutex_lock(&bpf_percpu_ma_lock); 13621 if (!bpf_global_percpu_ma_set) { 13622 /* Charge memory allocated with bpf_global_percpu_ma to 13623 * root memcg. The obj_cgroup for root memcg is NULL. 13624 */ 13625 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 13626 if (!err) 13627 bpf_global_percpu_ma_set = true; 13628 } 13629 mutex_unlock(&bpf_percpu_ma_lock); 13630 if (err) 13631 return err; 13632 } 13633 13634 mutex_lock(&bpf_percpu_ma_lock); 13635 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 13636 mutex_unlock(&bpf_percpu_ma_lock); 13637 if (err) 13638 return err; 13639 } 13640 13641 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 13642 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 13643 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 13644 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 13645 return -EINVAL; 13646 } 13647 13648 if (struct_meta) { 13649 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 13650 return -EINVAL; 13651 } 13652 } 13653 13654 mark_reg_known_zero(env, regs, BPF_REG_0); 13655 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 13656 regs[BPF_REG_0].btf = ret_btf; 13657 regs[BPF_REG_0].btf_id = ret_btf_id; 13658 if (meta->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 13659 regs[BPF_REG_0].type |= MEM_PERCPU; 13660 13661 insn_aux->obj_new_size = ret_t->size; 13662 insn_aux->kptr_struct_meta = struct_meta; 13663 } else if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 13664 mark_reg_known_zero(env, regs, BPF_REG_0); 13665 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 13666 regs[BPF_REG_0].btf = meta->arg_btf; 13667 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 13668 13669 insn_aux->kptr_struct_meta = 13670 btf_find_struct_meta(meta->arg_btf, 13671 meta->arg_btf_id); 13672 } else if (is_list_node_type(ptr_type)) { 13673 struct btf_field *field = meta->arg_list_head.field; 13674 13675 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 13676 } else if (is_rbtree_node_type(ptr_type)) { 13677 struct btf_field *field = meta->arg_rbtree_root.field; 13678 13679 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 13680 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 13681 mark_reg_known_zero(env, regs, BPF_REG_0); 13682 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 13683 regs[BPF_REG_0].btf = desc_btf; 13684 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 13685 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 13686 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 13687 if (!ret_t) { 13688 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n", 13689 meta->arg_constant.value); 13690 return -EINVAL; 13691 } else if (btf_type_is_struct(ret_t)) { 13692 mark_reg_known_zero(env, regs, BPF_REG_0); 13693 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 13694 regs[BPF_REG_0].btf = desc_btf; 13695 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 13696 } else if (btf_type_is_void(ret_t)) { 13697 mark_reg_known_zero(env, regs, BPF_REG_0); 13698 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED; 13699 regs[BPF_REG_0].mem_size = 0; 13700 } else { 13701 verbose(env, 13702 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n"); 13703 return -EINVAL; 13704 } 13705 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 13706 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 13707 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type); 13708 13709 mark_reg_known_zero(env, regs, BPF_REG_0); 13710 13711 if (!meta->arg_constant.found) { 13712 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size"); 13713 return -EFAULT; 13714 } 13715 13716 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 13717 13718 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 13719 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 13720 13721 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 13722 regs[BPF_REG_0].type |= MEM_RDONLY; 13723 } else { 13724 /* this will set env->seen_direct_write to true */ 13725 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 13726 verbose(env, "the prog does not allow writes to packet data\n"); 13727 return -EINVAL; 13728 } 13729 } 13730 13731 if (!meta->initialized_dynptr.id) { 13732 verifier_bug(env, "no dynptr id"); 13733 return -EFAULT; 13734 } 13735 regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id; 13736 13737 /* we don't need to set BPF_REG_0's ref obj id 13738 * because packet slices are not refcounted (see 13739 * dynptr_type_refcounted) 13740 */ 13741 } else { 13742 return 0; 13743 } 13744 13745 return 1; 13746 } 13747 13748 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 13749 13750 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 13751 int *insn_idx_p) 13752 { 13753 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 13754 u32 i, nargs, ptr_type_id, release_ref_obj_id; 13755 struct bpf_reg_state *regs = cur_regs(env); 13756 const char *func_name, *ptr_type_name; 13757 const struct btf_type *t, *ptr_type; 13758 struct bpf_kfunc_call_arg_meta meta; 13759 struct bpf_insn_aux_data *insn_aux; 13760 int err, insn_idx = *insn_idx_p; 13761 const struct btf_param *args; 13762 struct btf *desc_btf; 13763 13764 /* skip for now, but return error when we find this in fixup_kfunc_call */ 13765 if (!insn->imm) 13766 return 0; 13767 13768 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 13769 if (err == -EACCES && func_name) 13770 verbose(env, "calling kernel function %s is not allowed\n", func_name); 13771 if (err) 13772 return err; 13773 desc_btf = meta.btf; 13774 insn_aux = &env->insn_aux_data[insn_idx]; 13775 13776 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 13777 13778 if (!insn->off && 13779 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 13780 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 13781 struct bpf_verifier_state *branch; 13782 struct bpf_reg_state *regs; 13783 13784 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 13785 if (!branch) { 13786 verbose(env, "failed to push state for failed lock acquisition\n"); 13787 return -ENOMEM; 13788 } 13789 13790 regs = branch->frame[branch->curframe]->regs; 13791 13792 /* Clear r0-r5 registers in forked state */ 13793 for (i = 0; i < CALLER_SAVED_REGS; i++) 13794 mark_reg_not_init(env, regs, caller_saved[i]); 13795 13796 mark_reg_unknown(env, regs, BPF_REG_0); 13797 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 13798 if (err) { 13799 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 13800 return err; 13801 } 13802 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32)); 13803 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 13804 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 13805 return -EFAULT; 13806 } 13807 13808 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 13809 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 13810 return -EACCES; 13811 } 13812 13813 sleepable = is_kfunc_sleepable(&meta); 13814 if (sleepable && !in_sleepable(env)) { 13815 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 13816 return -EACCES; 13817 } 13818 13819 /* Check the arguments */ 13820 err = check_kfunc_args(env, &meta, insn_idx); 13821 if (err < 0) 13822 return err; 13823 13824 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13825 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13826 set_rbtree_add_callback_state); 13827 if (err) { 13828 verbose(env, "kfunc %s#%d failed callback verification\n", 13829 func_name, meta.func_id); 13830 return err; 13831 } 13832 } 13833 13834 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 13835 meta.r0_size = sizeof(u64); 13836 meta.r0_rdonly = false; 13837 } 13838 13839 if (is_bpf_wq_set_callback_impl_kfunc(meta.func_id)) { 13840 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13841 set_timer_callback_state); 13842 if (err) { 13843 verbose(env, "kfunc %s#%d failed callback verification\n", 13844 func_name, meta.func_id); 13845 return err; 13846 } 13847 } 13848 13849 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 13850 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 13851 13852 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 13853 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 13854 13855 if (env->cur_state->active_rcu_lock) { 13856 struct bpf_func_state *state; 13857 struct bpf_reg_state *reg; 13858 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 13859 13860 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 13861 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 13862 return -EACCES; 13863 } 13864 13865 if (rcu_lock) { 13866 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 13867 return -EINVAL; 13868 } else if (rcu_unlock) { 13869 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 13870 if (reg->type & MEM_RCU) { 13871 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 13872 reg->type |= PTR_UNTRUSTED; 13873 } 13874 })); 13875 env->cur_state->active_rcu_lock = false; 13876 } else if (sleepable) { 13877 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 13878 return -EACCES; 13879 } 13880 } else if (rcu_lock) { 13881 env->cur_state->active_rcu_lock = true; 13882 } else if (rcu_unlock) { 13883 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 13884 return -EINVAL; 13885 } 13886 13887 if (env->cur_state->active_preempt_locks) { 13888 if (preempt_disable) { 13889 env->cur_state->active_preempt_locks++; 13890 } else if (preempt_enable) { 13891 env->cur_state->active_preempt_locks--; 13892 } else if (sleepable) { 13893 verbose(env, "kernel func %s is sleepable within non-preemptible region\n", func_name); 13894 return -EACCES; 13895 } 13896 } else if (preempt_disable) { 13897 env->cur_state->active_preempt_locks++; 13898 } else if (preempt_enable) { 13899 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 13900 return -EINVAL; 13901 } 13902 13903 if (env->cur_state->active_irq_id && sleepable) { 13904 verbose(env, "kernel func %s is sleepable within IRQ-disabled region\n", func_name); 13905 return -EACCES; 13906 } 13907 13908 /* In case of release function, we get register number of refcounted 13909 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 13910 */ 13911 if (meta.release_regno) { 13912 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 13913 if (err) { 13914 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13915 func_name, meta.func_id); 13916 return err; 13917 } 13918 } 13919 13920 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 13921 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 13922 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 13923 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 13924 insn_aux->insert_off = regs[BPF_REG_2].off; 13925 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13926 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 13927 if (err) { 13928 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 13929 func_name, meta.func_id); 13930 return err; 13931 } 13932 13933 err = release_reference(env, release_ref_obj_id); 13934 if (err) { 13935 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13936 func_name, meta.func_id); 13937 return err; 13938 } 13939 } 13940 13941 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 13942 if (!bpf_jit_supports_exceptions()) { 13943 verbose(env, "JIT does not support calling kfunc %s#%d\n", 13944 func_name, meta.func_id); 13945 return -ENOTSUPP; 13946 } 13947 env->seen_exception = true; 13948 13949 /* In the case of the default callback, the cookie value passed 13950 * to bpf_throw becomes the return value of the program. 13951 */ 13952 if (!env->exception_callback_subprog) { 13953 err = check_return_code(env, BPF_REG_1, "R1"); 13954 if (err < 0) 13955 return err; 13956 } 13957 } 13958 13959 for (i = 0; i < CALLER_SAVED_REGS; i++) 13960 mark_reg_not_init(env, regs, caller_saved[i]); 13961 13962 /* Check return type */ 13963 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13964 13965 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13966 /* Only exception is bpf_obj_new_impl */ 13967 if (meta.btf != btf_vmlinux || 13968 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 13969 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 13970 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 13971 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13972 return -EINVAL; 13973 } 13974 } 13975 13976 if (btf_type_is_scalar(t)) { 13977 mark_reg_unknown(env, regs, BPF_REG_0); 13978 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13979 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13980 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 13981 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 13982 } else if (btf_type_is_ptr(t)) { 13983 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 13984 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 13985 if (err) { 13986 if (err < 0) 13987 return err; 13988 } else if (btf_type_is_void(ptr_type)) { 13989 /* kfunc returning 'void *' is equivalent to returning scalar */ 13990 mark_reg_unknown(env, regs, BPF_REG_0); 13991 } else if (!__btf_type_is_struct(ptr_type)) { 13992 if (!meta.r0_size) { 13993 __u32 sz; 13994 13995 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 13996 meta.r0_size = sz; 13997 meta.r0_rdonly = true; 13998 } 13999 } 14000 if (!meta.r0_size) { 14001 ptr_type_name = btf_name_by_offset(desc_btf, 14002 ptr_type->name_off); 14003 verbose(env, 14004 "kernel function %s returns pointer type %s %s is not supported\n", 14005 func_name, 14006 btf_type_str(ptr_type), 14007 ptr_type_name); 14008 return -EINVAL; 14009 } 14010 14011 mark_reg_known_zero(env, regs, BPF_REG_0); 14012 regs[BPF_REG_0].type = PTR_TO_MEM; 14013 regs[BPF_REG_0].mem_size = meta.r0_size; 14014 14015 if (meta.r0_rdonly) 14016 regs[BPF_REG_0].type |= MEM_RDONLY; 14017 14018 /* Ensures we don't access the memory after a release_reference() */ 14019 if (meta.ref_obj_id) 14020 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 14021 } else { 14022 mark_reg_known_zero(env, regs, BPF_REG_0); 14023 regs[BPF_REG_0].btf = desc_btf; 14024 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 14025 regs[BPF_REG_0].btf_id = ptr_type_id; 14026 14027 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 14028 regs[BPF_REG_0].type |= PTR_UNTRUSTED; 14029 14030 if (is_iter_next_kfunc(&meta)) { 14031 struct bpf_reg_state *cur_iter; 14032 14033 cur_iter = get_iter_from_state(env->cur_state, &meta); 14034 14035 if (cur_iter->type & MEM_RCU) /* KF_RCU_PROTECTED */ 14036 regs[BPF_REG_0].type |= MEM_RCU; 14037 else 14038 regs[BPF_REG_0].type |= PTR_TRUSTED; 14039 } 14040 } 14041 14042 if (is_kfunc_ret_null(&meta)) { 14043 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 14044 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 14045 regs[BPF_REG_0].id = ++env->id_gen; 14046 } 14047 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 14048 if (is_kfunc_acquire(&meta)) { 14049 int id = acquire_reference(env, insn_idx); 14050 14051 if (id < 0) 14052 return id; 14053 if (is_kfunc_ret_null(&meta)) 14054 regs[BPF_REG_0].id = id; 14055 regs[BPF_REG_0].ref_obj_id = id; 14056 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 14057 ref_set_non_owning(env, ®s[BPF_REG_0]); 14058 } 14059 14060 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 14061 regs[BPF_REG_0].id = ++env->id_gen; 14062 } else if (btf_type_is_void(t)) { 14063 if (meta.btf == btf_vmlinux) { 14064 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 14065 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 14066 insn_aux->kptr_struct_meta = 14067 btf_find_struct_meta(meta.arg_btf, 14068 meta.arg_btf_id); 14069 } 14070 } 14071 } 14072 14073 nargs = btf_type_vlen(meta.func_proto); 14074 args = (const struct btf_param *)(meta.func_proto + 1); 14075 for (i = 0; i < nargs; i++) { 14076 u32 regno = i + 1; 14077 14078 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 14079 if (btf_type_is_ptr(t)) 14080 mark_btf_func_reg_size(env, regno, sizeof(void *)); 14081 else 14082 /* scalar. ensured by btf_check_kfunc_arg_match() */ 14083 mark_btf_func_reg_size(env, regno, t->size); 14084 } 14085 14086 if (is_iter_next_kfunc(&meta)) { 14087 err = process_iter_next_call(env, insn_idx, &meta); 14088 if (err) 14089 return err; 14090 } 14091 14092 return 0; 14093 } 14094 14095 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 14096 const struct bpf_reg_state *reg, 14097 enum bpf_reg_type type) 14098 { 14099 bool known = tnum_is_const(reg->var_off); 14100 s64 val = reg->var_off.value; 14101 s64 smin = reg->smin_value; 14102 14103 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 14104 verbose(env, "math between %s pointer and %lld is not allowed\n", 14105 reg_type_str(env, type), val); 14106 return false; 14107 } 14108 14109 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 14110 verbose(env, "%s pointer offset %d is not allowed\n", 14111 reg_type_str(env, type), reg->off); 14112 return false; 14113 } 14114 14115 if (smin == S64_MIN) { 14116 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 14117 reg_type_str(env, type)); 14118 return false; 14119 } 14120 14121 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 14122 verbose(env, "value %lld makes %s pointer be out of bounds\n", 14123 smin, reg_type_str(env, type)); 14124 return false; 14125 } 14126 14127 return true; 14128 } 14129 14130 enum { 14131 REASON_BOUNDS = -1, 14132 REASON_TYPE = -2, 14133 REASON_PATHS = -3, 14134 REASON_LIMIT = -4, 14135 REASON_STACK = -5, 14136 }; 14137 14138 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 14139 u32 *alu_limit, bool mask_to_left) 14140 { 14141 u32 max = 0, ptr_limit = 0; 14142 14143 switch (ptr_reg->type) { 14144 case PTR_TO_STACK: 14145 /* Offset 0 is out-of-bounds, but acceptable start for the 14146 * left direction, see BPF_REG_FP. Also, unknown scalar 14147 * offset where we would need to deal with min/max bounds is 14148 * currently prohibited for unprivileged. 14149 */ 14150 max = MAX_BPF_STACK + mask_to_left; 14151 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 14152 break; 14153 case PTR_TO_MAP_VALUE: 14154 max = ptr_reg->map_ptr->value_size; 14155 ptr_limit = (mask_to_left ? 14156 ptr_reg->smin_value : 14157 ptr_reg->umax_value) + ptr_reg->off; 14158 break; 14159 default: 14160 return REASON_TYPE; 14161 } 14162 14163 if (ptr_limit >= max) 14164 return REASON_LIMIT; 14165 *alu_limit = ptr_limit; 14166 return 0; 14167 } 14168 14169 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 14170 const struct bpf_insn *insn) 14171 { 14172 return env->bypass_spec_v1 || 14173 BPF_SRC(insn->code) == BPF_K || 14174 cur_aux(env)->nospec; 14175 } 14176 14177 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 14178 u32 alu_state, u32 alu_limit) 14179 { 14180 /* If we arrived here from different branches with different 14181 * state or limits to sanitize, then this won't work. 14182 */ 14183 if (aux->alu_state && 14184 (aux->alu_state != alu_state || 14185 aux->alu_limit != alu_limit)) 14186 return REASON_PATHS; 14187 14188 /* Corresponding fixup done in do_misc_fixups(). */ 14189 aux->alu_state = alu_state; 14190 aux->alu_limit = alu_limit; 14191 return 0; 14192 } 14193 14194 static int sanitize_val_alu(struct bpf_verifier_env *env, 14195 struct bpf_insn *insn) 14196 { 14197 struct bpf_insn_aux_data *aux = cur_aux(env); 14198 14199 if (can_skip_alu_sanitation(env, insn)) 14200 return 0; 14201 14202 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 14203 } 14204 14205 static bool sanitize_needed(u8 opcode) 14206 { 14207 return opcode == BPF_ADD || opcode == BPF_SUB; 14208 } 14209 14210 struct bpf_sanitize_info { 14211 struct bpf_insn_aux_data aux; 14212 bool mask_to_left; 14213 }; 14214 14215 static struct bpf_verifier_state * 14216 sanitize_speculative_path(struct bpf_verifier_env *env, 14217 const struct bpf_insn *insn, 14218 u32 next_idx, u32 curr_idx) 14219 { 14220 struct bpf_verifier_state *branch; 14221 struct bpf_reg_state *regs; 14222 14223 branch = push_stack(env, next_idx, curr_idx, true); 14224 if (branch && insn) { 14225 regs = branch->frame[branch->curframe]->regs; 14226 if (BPF_SRC(insn->code) == BPF_K) { 14227 mark_reg_unknown(env, regs, insn->dst_reg); 14228 } else if (BPF_SRC(insn->code) == BPF_X) { 14229 mark_reg_unknown(env, regs, insn->dst_reg); 14230 mark_reg_unknown(env, regs, insn->src_reg); 14231 } 14232 } 14233 return branch; 14234 } 14235 14236 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 14237 struct bpf_insn *insn, 14238 const struct bpf_reg_state *ptr_reg, 14239 const struct bpf_reg_state *off_reg, 14240 struct bpf_reg_state *dst_reg, 14241 struct bpf_sanitize_info *info, 14242 const bool commit_window) 14243 { 14244 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 14245 struct bpf_verifier_state *vstate = env->cur_state; 14246 bool off_is_imm = tnum_is_const(off_reg->var_off); 14247 bool off_is_neg = off_reg->smin_value < 0; 14248 bool ptr_is_dst_reg = ptr_reg == dst_reg; 14249 u8 opcode = BPF_OP(insn->code); 14250 u32 alu_state, alu_limit; 14251 struct bpf_reg_state tmp; 14252 bool ret; 14253 int err; 14254 14255 if (can_skip_alu_sanitation(env, insn)) 14256 return 0; 14257 14258 /* We already marked aux for masking from non-speculative 14259 * paths, thus we got here in the first place. We only care 14260 * to explore bad access from here. 14261 */ 14262 if (vstate->speculative) 14263 goto do_sim; 14264 14265 if (!commit_window) { 14266 if (!tnum_is_const(off_reg->var_off) && 14267 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 14268 return REASON_BOUNDS; 14269 14270 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 14271 (opcode == BPF_SUB && !off_is_neg); 14272 } 14273 14274 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 14275 if (err < 0) 14276 return err; 14277 14278 if (commit_window) { 14279 /* In commit phase we narrow the masking window based on 14280 * the observed pointer move after the simulated operation. 14281 */ 14282 alu_state = info->aux.alu_state; 14283 alu_limit = abs(info->aux.alu_limit - alu_limit); 14284 } else { 14285 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 14286 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 14287 alu_state |= ptr_is_dst_reg ? 14288 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 14289 14290 /* Limit pruning on unknown scalars to enable deep search for 14291 * potential masking differences from other program paths. 14292 */ 14293 if (!off_is_imm) 14294 env->explore_alu_limits = true; 14295 } 14296 14297 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 14298 if (err < 0) 14299 return err; 14300 do_sim: 14301 /* If we're in commit phase, we're done here given we already 14302 * pushed the truncated dst_reg into the speculative verification 14303 * stack. 14304 * 14305 * Also, when register is a known constant, we rewrite register-based 14306 * operation to immediate-based, and thus do not need masking (and as 14307 * a consequence, do not need to simulate the zero-truncation either). 14308 */ 14309 if (commit_window || off_is_imm) 14310 return 0; 14311 14312 /* Simulate and find potential out-of-bounds access under 14313 * speculative execution from truncation as a result of 14314 * masking when off was not within expected range. If off 14315 * sits in dst, then we temporarily need to move ptr there 14316 * to simulate dst (== 0) +/-= ptr. Needed, for example, 14317 * for cases where we use K-based arithmetic in one direction 14318 * and truncated reg-based in the other in order to explore 14319 * bad access. 14320 */ 14321 if (!ptr_is_dst_reg) { 14322 tmp = *dst_reg; 14323 copy_register_state(dst_reg, ptr_reg); 14324 } 14325 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 14326 env->insn_idx); 14327 if (!ptr_is_dst_reg && ret) 14328 *dst_reg = tmp; 14329 return !ret ? REASON_STACK : 0; 14330 } 14331 14332 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 14333 { 14334 struct bpf_verifier_state *vstate = env->cur_state; 14335 14336 /* If we simulate paths under speculation, we don't update the 14337 * insn as 'seen' such that when we verify unreachable paths in 14338 * the non-speculative domain, sanitize_dead_code() can still 14339 * rewrite/sanitize them. 14340 */ 14341 if (!vstate->speculative) 14342 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 14343 } 14344 14345 static int sanitize_err(struct bpf_verifier_env *env, 14346 const struct bpf_insn *insn, int reason, 14347 const struct bpf_reg_state *off_reg, 14348 const struct bpf_reg_state *dst_reg) 14349 { 14350 static const char *err = "pointer arithmetic with it prohibited for !root"; 14351 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 14352 u32 dst = insn->dst_reg, src = insn->src_reg; 14353 14354 switch (reason) { 14355 case REASON_BOUNDS: 14356 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 14357 off_reg == dst_reg ? dst : src, err); 14358 break; 14359 case REASON_TYPE: 14360 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 14361 off_reg == dst_reg ? src : dst, err); 14362 break; 14363 case REASON_PATHS: 14364 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 14365 dst, op, err); 14366 break; 14367 case REASON_LIMIT: 14368 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 14369 dst, op, err); 14370 break; 14371 case REASON_STACK: 14372 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 14373 dst, err); 14374 return -ENOMEM; 14375 default: 14376 verifier_bug(env, "unknown reason (%d)", reason); 14377 break; 14378 } 14379 14380 return -EACCES; 14381 } 14382 14383 /* check that stack access falls within stack limits and that 'reg' doesn't 14384 * have a variable offset. 14385 * 14386 * Variable offset is prohibited for unprivileged mode for simplicity since it 14387 * requires corresponding support in Spectre masking for stack ALU. See also 14388 * retrieve_ptr_limit(). 14389 * 14390 * 14391 * 'off' includes 'reg->off'. 14392 */ 14393 static int check_stack_access_for_ptr_arithmetic( 14394 struct bpf_verifier_env *env, 14395 int regno, 14396 const struct bpf_reg_state *reg, 14397 int off) 14398 { 14399 if (!tnum_is_const(reg->var_off)) { 14400 char tn_buf[48]; 14401 14402 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 14403 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 14404 regno, tn_buf, off); 14405 return -EACCES; 14406 } 14407 14408 if (off >= 0 || off < -MAX_BPF_STACK) { 14409 verbose(env, "R%d stack pointer arithmetic goes out of range, " 14410 "prohibited for !root; off=%d\n", regno, off); 14411 return -EACCES; 14412 } 14413 14414 return 0; 14415 } 14416 14417 static int sanitize_check_bounds(struct bpf_verifier_env *env, 14418 const struct bpf_insn *insn, 14419 const struct bpf_reg_state *dst_reg) 14420 { 14421 u32 dst = insn->dst_reg; 14422 14423 /* For unprivileged we require that resulting offset must be in bounds 14424 * in order to be able to sanitize access later on. 14425 */ 14426 if (env->bypass_spec_v1) 14427 return 0; 14428 14429 switch (dst_reg->type) { 14430 case PTR_TO_STACK: 14431 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 14432 dst_reg->off + dst_reg->var_off.value)) 14433 return -EACCES; 14434 break; 14435 case PTR_TO_MAP_VALUE: 14436 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 14437 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 14438 "prohibited for !root\n", dst); 14439 return -EACCES; 14440 } 14441 break; 14442 default: 14443 return -EOPNOTSUPP; 14444 } 14445 14446 return 0; 14447 } 14448 14449 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 14450 * Caller should also handle BPF_MOV case separately. 14451 * If we return -EACCES, caller may want to try again treating pointer as a 14452 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 14453 */ 14454 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 14455 struct bpf_insn *insn, 14456 const struct bpf_reg_state *ptr_reg, 14457 const struct bpf_reg_state *off_reg) 14458 { 14459 struct bpf_verifier_state *vstate = env->cur_state; 14460 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14461 struct bpf_reg_state *regs = state->regs, *dst_reg; 14462 bool known = tnum_is_const(off_reg->var_off); 14463 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 14464 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 14465 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 14466 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 14467 struct bpf_sanitize_info info = {}; 14468 u8 opcode = BPF_OP(insn->code); 14469 u32 dst = insn->dst_reg; 14470 int ret, bounds_ret; 14471 14472 dst_reg = ®s[dst]; 14473 14474 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 14475 smin_val > smax_val || umin_val > umax_val) { 14476 /* Taint dst register if offset had invalid bounds derived from 14477 * e.g. dead branches. 14478 */ 14479 __mark_reg_unknown(env, dst_reg); 14480 return 0; 14481 } 14482 14483 if (BPF_CLASS(insn->code) != BPF_ALU64) { 14484 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 14485 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14486 __mark_reg_unknown(env, dst_reg); 14487 return 0; 14488 } 14489 14490 verbose(env, 14491 "R%d 32-bit pointer arithmetic prohibited\n", 14492 dst); 14493 return -EACCES; 14494 } 14495 14496 if (ptr_reg->type & PTR_MAYBE_NULL) { 14497 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 14498 dst, reg_type_str(env, ptr_reg->type)); 14499 return -EACCES; 14500 } 14501 14502 /* 14503 * Accesses to untrusted PTR_TO_MEM are done through probe 14504 * instructions, hence no need to track offsets. 14505 */ 14506 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 14507 return 0; 14508 14509 switch (base_type(ptr_reg->type)) { 14510 case PTR_TO_CTX: 14511 case PTR_TO_MAP_VALUE: 14512 case PTR_TO_MAP_KEY: 14513 case PTR_TO_STACK: 14514 case PTR_TO_PACKET_META: 14515 case PTR_TO_PACKET: 14516 case PTR_TO_TP_BUFFER: 14517 case PTR_TO_BTF_ID: 14518 case PTR_TO_MEM: 14519 case PTR_TO_BUF: 14520 case PTR_TO_FUNC: 14521 case CONST_PTR_TO_DYNPTR: 14522 break; 14523 case PTR_TO_FLOW_KEYS: 14524 if (known) 14525 break; 14526 fallthrough; 14527 case CONST_PTR_TO_MAP: 14528 /* smin_val represents the known value */ 14529 if (known && smin_val == 0 && opcode == BPF_ADD) 14530 break; 14531 fallthrough; 14532 default: 14533 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 14534 dst, reg_type_str(env, ptr_reg->type)); 14535 return -EACCES; 14536 } 14537 14538 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 14539 * The id may be overwritten later if we create a new variable offset. 14540 */ 14541 dst_reg->type = ptr_reg->type; 14542 dst_reg->id = ptr_reg->id; 14543 14544 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 14545 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 14546 return -EINVAL; 14547 14548 /* pointer types do not carry 32-bit bounds at the moment. */ 14549 __mark_reg32_unbounded(dst_reg); 14550 14551 if (sanitize_needed(opcode)) { 14552 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 14553 &info, false); 14554 if (ret < 0) 14555 return sanitize_err(env, insn, ret, off_reg, dst_reg); 14556 } 14557 14558 switch (opcode) { 14559 case BPF_ADD: 14560 /* We can take a fixed offset as long as it doesn't overflow 14561 * the s32 'off' field 14562 */ 14563 if (known && (ptr_reg->off + smin_val == 14564 (s64)(s32)(ptr_reg->off + smin_val))) { 14565 /* pointer += K. Accumulate it into fixed offset */ 14566 dst_reg->smin_value = smin_ptr; 14567 dst_reg->smax_value = smax_ptr; 14568 dst_reg->umin_value = umin_ptr; 14569 dst_reg->umax_value = umax_ptr; 14570 dst_reg->var_off = ptr_reg->var_off; 14571 dst_reg->off = ptr_reg->off + smin_val; 14572 dst_reg->raw = ptr_reg->raw; 14573 break; 14574 } 14575 /* A new variable offset is created. Note that off_reg->off 14576 * == 0, since it's a scalar. 14577 * dst_reg gets the pointer type and since some positive 14578 * integer value was added to the pointer, give it a new 'id' 14579 * if it's a PTR_TO_PACKET. 14580 * this creates a new 'base' pointer, off_reg (variable) gets 14581 * added into the variable offset, and we copy the fixed offset 14582 * from ptr_reg. 14583 */ 14584 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) || 14585 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) { 14586 dst_reg->smin_value = S64_MIN; 14587 dst_reg->smax_value = S64_MAX; 14588 } 14589 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) || 14590 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) { 14591 dst_reg->umin_value = 0; 14592 dst_reg->umax_value = U64_MAX; 14593 } 14594 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 14595 dst_reg->off = ptr_reg->off; 14596 dst_reg->raw = ptr_reg->raw; 14597 if (reg_is_pkt_pointer(ptr_reg)) { 14598 dst_reg->id = ++env->id_gen; 14599 /* something was added to pkt_ptr, set range to zero */ 14600 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 14601 } 14602 break; 14603 case BPF_SUB: 14604 if (dst_reg == off_reg) { 14605 /* scalar -= pointer. Creates an unknown scalar */ 14606 verbose(env, "R%d tried to subtract pointer from scalar\n", 14607 dst); 14608 return -EACCES; 14609 } 14610 /* We don't allow subtraction from FP, because (according to 14611 * test_verifier.c test "invalid fp arithmetic", JITs might not 14612 * be able to deal with it. 14613 */ 14614 if (ptr_reg->type == PTR_TO_STACK) { 14615 verbose(env, "R%d subtraction from stack pointer prohibited\n", 14616 dst); 14617 return -EACCES; 14618 } 14619 if (known && (ptr_reg->off - smin_val == 14620 (s64)(s32)(ptr_reg->off - smin_val))) { 14621 /* pointer -= K. Subtract it from fixed offset */ 14622 dst_reg->smin_value = smin_ptr; 14623 dst_reg->smax_value = smax_ptr; 14624 dst_reg->umin_value = umin_ptr; 14625 dst_reg->umax_value = umax_ptr; 14626 dst_reg->var_off = ptr_reg->var_off; 14627 dst_reg->id = ptr_reg->id; 14628 dst_reg->off = ptr_reg->off - smin_val; 14629 dst_reg->raw = ptr_reg->raw; 14630 break; 14631 } 14632 /* A new variable offset is created. If the subtrahend is known 14633 * nonnegative, then any reg->range we had before is still good. 14634 */ 14635 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) || 14636 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) { 14637 /* Overflow possible, we know nothing */ 14638 dst_reg->smin_value = S64_MIN; 14639 dst_reg->smax_value = S64_MAX; 14640 } 14641 if (umin_ptr < umax_val) { 14642 /* Overflow possible, we know nothing */ 14643 dst_reg->umin_value = 0; 14644 dst_reg->umax_value = U64_MAX; 14645 } else { 14646 /* Cannot overflow (as long as bounds are consistent) */ 14647 dst_reg->umin_value = umin_ptr - umax_val; 14648 dst_reg->umax_value = umax_ptr - umin_val; 14649 } 14650 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 14651 dst_reg->off = ptr_reg->off; 14652 dst_reg->raw = ptr_reg->raw; 14653 if (reg_is_pkt_pointer(ptr_reg)) { 14654 dst_reg->id = ++env->id_gen; 14655 /* something was added to pkt_ptr, set range to zero */ 14656 if (smin_val < 0) 14657 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 14658 } 14659 break; 14660 case BPF_AND: 14661 case BPF_OR: 14662 case BPF_XOR: 14663 /* bitwise ops on pointers are troublesome, prohibit. */ 14664 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 14665 dst, bpf_alu_string[opcode >> 4]); 14666 return -EACCES; 14667 default: 14668 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 14669 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 14670 dst, bpf_alu_string[opcode >> 4]); 14671 return -EACCES; 14672 } 14673 14674 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 14675 return -EINVAL; 14676 reg_bounds_sync(dst_reg); 14677 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 14678 if (bounds_ret == -EACCES) 14679 return bounds_ret; 14680 if (sanitize_needed(opcode)) { 14681 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 14682 &info, true); 14683 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 14684 && !env->cur_state->speculative 14685 && bounds_ret 14686 && !ret, 14687 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 14688 return -EFAULT; 14689 } 14690 if (ret < 0) 14691 return sanitize_err(env, insn, ret, off_reg, dst_reg); 14692 } 14693 14694 return 0; 14695 } 14696 14697 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 14698 struct bpf_reg_state *src_reg) 14699 { 14700 s32 *dst_smin = &dst_reg->s32_min_value; 14701 s32 *dst_smax = &dst_reg->s32_max_value; 14702 u32 *dst_umin = &dst_reg->u32_min_value; 14703 u32 *dst_umax = &dst_reg->u32_max_value; 14704 u32 umin_val = src_reg->u32_min_value; 14705 u32 umax_val = src_reg->u32_max_value; 14706 bool min_overflow, max_overflow; 14707 14708 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) || 14709 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) { 14710 *dst_smin = S32_MIN; 14711 *dst_smax = S32_MAX; 14712 } 14713 14714 /* If either all additions overflow or no additions overflow, then 14715 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax = 14716 * dst_umax + src_umax. Otherwise (some additions overflow), set 14717 * the output bounds to unbounded. 14718 */ 14719 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin); 14720 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax); 14721 14722 if (!min_overflow && max_overflow) { 14723 *dst_umin = 0; 14724 *dst_umax = U32_MAX; 14725 } 14726 } 14727 14728 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 14729 struct bpf_reg_state *src_reg) 14730 { 14731 s64 *dst_smin = &dst_reg->smin_value; 14732 s64 *dst_smax = &dst_reg->smax_value; 14733 u64 *dst_umin = &dst_reg->umin_value; 14734 u64 *dst_umax = &dst_reg->umax_value; 14735 u64 umin_val = src_reg->umin_value; 14736 u64 umax_val = src_reg->umax_value; 14737 bool min_overflow, max_overflow; 14738 14739 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) || 14740 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) { 14741 *dst_smin = S64_MIN; 14742 *dst_smax = S64_MAX; 14743 } 14744 14745 /* If either all additions overflow or no additions overflow, then 14746 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax = 14747 * dst_umax + src_umax. Otherwise (some additions overflow), set 14748 * the output bounds to unbounded. 14749 */ 14750 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin); 14751 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax); 14752 14753 if (!min_overflow && max_overflow) { 14754 *dst_umin = 0; 14755 *dst_umax = U64_MAX; 14756 } 14757 } 14758 14759 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 14760 struct bpf_reg_state *src_reg) 14761 { 14762 s32 *dst_smin = &dst_reg->s32_min_value; 14763 s32 *dst_smax = &dst_reg->s32_max_value; 14764 u32 *dst_umin = &dst_reg->u32_min_value; 14765 u32 *dst_umax = &dst_reg->u32_max_value; 14766 u32 umin_val = src_reg->u32_min_value; 14767 u32 umax_val = src_reg->u32_max_value; 14768 bool min_underflow, max_underflow; 14769 14770 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) || 14771 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) { 14772 /* Overflow possible, we know nothing */ 14773 *dst_smin = S32_MIN; 14774 *dst_smax = S32_MAX; 14775 } 14776 14777 /* If either all subtractions underflow or no subtractions 14778 * underflow, it is okay to set: dst_umin = dst_umin - src_umax, 14779 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions 14780 * underflow), set the output bounds to unbounded. 14781 */ 14782 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin); 14783 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax); 14784 14785 if (min_underflow && !max_underflow) { 14786 *dst_umin = 0; 14787 *dst_umax = U32_MAX; 14788 } 14789 } 14790 14791 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 14792 struct bpf_reg_state *src_reg) 14793 { 14794 s64 *dst_smin = &dst_reg->smin_value; 14795 s64 *dst_smax = &dst_reg->smax_value; 14796 u64 *dst_umin = &dst_reg->umin_value; 14797 u64 *dst_umax = &dst_reg->umax_value; 14798 u64 umin_val = src_reg->umin_value; 14799 u64 umax_val = src_reg->umax_value; 14800 bool min_underflow, max_underflow; 14801 14802 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) || 14803 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) { 14804 /* Overflow possible, we know nothing */ 14805 *dst_smin = S64_MIN; 14806 *dst_smax = S64_MAX; 14807 } 14808 14809 /* If either all subtractions underflow or no subtractions 14810 * underflow, it is okay to set: dst_umin = dst_umin - src_umax, 14811 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions 14812 * underflow), set the output bounds to unbounded. 14813 */ 14814 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin); 14815 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax); 14816 14817 if (min_underflow && !max_underflow) { 14818 *dst_umin = 0; 14819 *dst_umax = U64_MAX; 14820 } 14821 } 14822 14823 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 14824 struct bpf_reg_state *src_reg) 14825 { 14826 s32 *dst_smin = &dst_reg->s32_min_value; 14827 s32 *dst_smax = &dst_reg->s32_max_value; 14828 u32 *dst_umin = &dst_reg->u32_min_value; 14829 u32 *dst_umax = &dst_reg->u32_max_value; 14830 s32 tmp_prod[4]; 14831 14832 if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) || 14833 check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) { 14834 /* Overflow possible, we know nothing */ 14835 *dst_umin = 0; 14836 *dst_umax = U32_MAX; 14837 } 14838 if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) || 14839 check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) || 14840 check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) || 14841 check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) { 14842 /* Overflow possible, we know nothing */ 14843 *dst_smin = S32_MIN; 14844 *dst_smax = S32_MAX; 14845 } else { 14846 *dst_smin = min_array(tmp_prod, 4); 14847 *dst_smax = max_array(tmp_prod, 4); 14848 } 14849 } 14850 14851 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 14852 struct bpf_reg_state *src_reg) 14853 { 14854 s64 *dst_smin = &dst_reg->smin_value; 14855 s64 *dst_smax = &dst_reg->smax_value; 14856 u64 *dst_umin = &dst_reg->umin_value; 14857 u64 *dst_umax = &dst_reg->umax_value; 14858 s64 tmp_prod[4]; 14859 14860 if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) || 14861 check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) { 14862 /* Overflow possible, we know nothing */ 14863 *dst_umin = 0; 14864 *dst_umax = U64_MAX; 14865 } 14866 if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) || 14867 check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) || 14868 check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) || 14869 check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) { 14870 /* Overflow possible, we know nothing */ 14871 *dst_smin = S64_MIN; 14872 *dst_smax = S64_MAX; 14873 } else { 14874 *dst_smin = min_array(tmp_prod, 4); 14875 *dst_smax = max_array(tmp_prod, 4); 14876 } 14877 } 14878 14879 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14880 struct bpf_reg_state *src_reg) 14881 { 14882 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14883 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14884 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14885 u32 umax_val = src_reg->u32_max_value; 14886 14887 if (src_known && dst_known) { 14888 __mark_reg32_known(dst_reg, var32_off.value); 14889 return; 14890 } 14891 14892 /* We get our minimum from the var_off, since that's inherently 14893 * bitwise. Our maximum is the minimum of the operands' maxima. 14894 */ 14895 dst_reg->u32_min_value = var32_off.value; 14896 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 14897 14898 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14899 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14900 */ 14901 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14902 dst_reg->s32_min_value = dst_reg->u32_min_value; 14903 dst_reg->s32_max_value = dst_reg->u32_max_value; 14904 } else { 14905 dst_reg->s32_min_value = S32_MIN; 14906 dst_reg->s32_max_value = S32_MAX; 14907 } 14908 } 14909 14910 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14911 struct bpf_reg_state *src_reg) 14912 { 14913 bool src_known = tnum_is_const(src_reg->var_off); 14914 bool dst_known = tnum_is_const(dst_reg->var_off); 14915 u64 umax_val = src_reg->umax_value; 14916 14917 if (src_known && dst_known) { 14918 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14919 return; 14920 } 14921 14922 /* We get our minimum from the var_off, since that's inherently 14923 * bitwise. Our maximum is the minimum of the operands' maxima. 14924 */ 14925 dst_reg->umin_value = dst_reg->var_off.value; 14926 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 14927 14928 /* Safe to set s64 bounds by casting u64 result into s64 when u64 14929 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 14930 */ 14931 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 14932 dst_reg->smin_value = dst_reg->umin_value; 14933 dst_reg->smax_value = dst_reg->umax_value; 14934 } else { 14935 dst_reg->smin_value = S64_MIN; 14936 dst_reg->smax_value = S64_MAX; 14937 } 14938 /* We may learn something more from the var_off */ 14939 __update_reg_bounds(dst_reg); 14940 } 14941 14942 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14943 struct bpf_reg_state *src_reg) 14944 { 14945 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14946 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14947 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14948 u32 umin_val = src_reg->u32_min_value; 14949 14950 if (src_known && dst_known) { 14951 __mark_reg32_known(dst_reg, var32_off.value); 14952 return; 14953 } 14954 14955 /* We get our maximum from the var_off, and our minimum is the 14956 * maximum of the operands' minima 14957 */ 14958 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 14959 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 14960 14961 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14962 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14963 */ 14964 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14965 dst_reg->s32_min_value = dst_reg->u32_min_value; 14966 dst_reg->s32_max_value = dst_reg->u32_max_value; 14967 } else { 14968 dst_reg->s32_min_value = S32_MIN; 14969 dst_reg->s32_max_value = S32_MAX; 14970 } 14971 } 14972 14973 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14974 struct bpf_reg_state *src_reg) 14975 { 14976 bool src_known = tnum_is_const(src_reg->var_off); 14977 bool dst_known = tnum_is_const(dst_reg->var_off); 14978 u64 umin_val = src_reg->umin_value; 14979 14980 if (src_known && dst_known) { 14981 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14982 return; 14983 } 14984 14985 /* We get our maximum from the var_off, and our minimum is the 14986 * maximum of the operands' minima 14987 */ 14988 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 14989 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 14990 14991 /* Safe to set s64 bounds by casting u64 result into s64 when u64 14992 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 14993 */ 14994 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 14995 dst_reg->smin_value = dst_reg->umin_value; 14996 dst_reg->smax_value = dst_reg->umax_value; 14997 } else { 14998 dst_reg->smin_value = S64_MIN; 14999 dst_reg->smax_value = S64_MAX; 15000 } 15001 /* We may learn something more from the var_off */ 15002 __update_reg_bounds(dst_reg); 15003 } 15004 15005 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 15006 struct bpf_reg_state *src_reg) 15007 { 15008 bool src_known = tnum_subreg_is_const(src_reg->var_off); 15009 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 15010 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 15011 15012 if (src_known && dst_known) { 15013 __mark_reg32_known(dst_reg, var32_off.value); 15014 return; 15015 } 15016 15017 /* We get both minimum and maximum from the var32_off. */ 15018 dst_reg->u32_min_value = var32_off.value; 15019 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 15020 15021 /* Safe to set s32 bounds by casting u32 result into s32 when u32 15022 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 15023 */ 15024 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 15025 dst_reg->s32_min_value = dst_reg->u32_min_value; 15026 dst_reg->s32_max_value = dst_reg->u32_max_value; 15027 } else { 15028 dst_reg->s32_min_value = S32_MIN; 15029 dst_reg->s32_max_value = S32_MAX; 15030 } 15031 } 15032 15033 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 15034 struct bpf_reg_state *src_reg) 15035 { 15036 bool src_known = tnum_is_const(src_reg->var_off); 15037 bool dst_known = tnum_is_const(dst_reg->var_off); 15038 15039 if (src_known && dst_known) { 15040 /* dst_reg->var_off.value has been updated earlier */ 15041 __mark_reg_known(dst_reg, dst_reg->var_off.value); 15042 return; 15043 } 15044 15045 /* We get both minimum and maximum from the var_off. */ 15046 dst_reg->umin_value = dst_reg->var_off.value; 15047 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 15048 15049 /* Safe to set s64 bounds by casting u64 result into s64 when u64 15050 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 15051 */ 15052 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 15053 dst_reg->smin_value = dst_reg->umin_value; 15054 dst_reg->smax_value = dst_reg->umax_value; 15055 } else { 15056 dst_reg->smin_value = S64_MIN; 15057 dst_reg->smax_value = S64_MAX; 15058 } 15059 15060 __update_reg_bounds(dst_reg); 15061 } 15062 15063 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 15064 u64 umin_val, u64 umax_val) 15065 { 15066 /* We lose all sign bit information (except what we can pick 15067 * up from var_off) 15068 */ 15069 dst_reg->s32_min_value = S32_MIN; 15070 dst_reg->s32_max_value = S32_MAX; 15071 /* If we might shift our top bit out, then we know nothing */ 15072 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 15073 dst_reg->u32_min_value = 0; 15074 dst_reg->u32_max_value = U32_MAX; 15075 } else { 15076 dst_reg->u32_min_value <<= umin_val; 15077 dst_reg->u32_max_value <<= umax_val; 15078 } 15079 } 15080 15081 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 15082 struct bpf_reg_state *src_reg) 15083 { 15084 u32 umax_val = src_reg->u32_max_value; 15085 u32 umin_val = src_reg->u32_min_value; 15086 /* u32 alu operation will zext upper bits */ 15087 struct tnum subreg = tnum_subreg(dst_reg->var_off); 15088 15089 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 15090 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 15091 /* Not required but being careful mark reg64 bounds as unknown so 15092 * that we are forced to pick them up from tnum and zext later and 15093 * if some path skips this step we are still safe. 15094 */ 15095 __mark_reg64_unbounded(dst_reg); 15096 __update_reg32_bounds(dst_reg); 15097 } 15098 15099 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 15100 u64 umin_val, u64 umax_val) 15101 { 15102 /* Special case <<32 because it is a common compiler pattern to sign 15103 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 15104 * positive we know this shift will also be positive so we can track 15105 * bounds correctly. Otherwise we lose all sign bit information except 15106 * what we can pick up from var_off. Perhaps we can generalize this 15107 * later to shifts of any length. 15108 */ 15109 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 15110 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 15111 else 15112 dst_reg->smax_value = S64_MAX; 15113 15114 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 15115 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 15116 else 15117 dst_reg->smin_value = S64_MIN; 15118 15119 /* If we might shift our top bit out, then we know nothing */ 15120 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 15121 dst_reg->umin_value = 0; 15122 dst_reg->umax_value = U64_MAX; 15123 } else { 15124 dst_reg->umin_value <<= umin_val; 15125 dst_reg->umax_value <<= umax_val; 15126 } 15127 } 15128 15129 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 15130 struct bpf_reg_state *src_reg) 15131 { 15132 u64 umax_val = src_reg->umax_value; 15133 u64 umin_val = src_reg->umin_value; 15134 15135 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 15136 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 15137 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 15138 15139 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 15140 /* We may learn something more from the var_off */ 15141 __update_reg_bounds(dst_reg); 15142 } 15143 15144 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 15145 struct bpf_reg_state *src_reg) 15146 { 15147 struct tnum subreg = tnum_subreg(dst_reg->var_off); 15148 u32 umax_val = src_reg->u32_max_value; 15149 u32 umin_val = src_reg->u32_min_value; 15150 15151 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 15152 * be negative, then either: 15153 * 1) src_reg might be zero, so the sign bit of the result is 15154 * unknown, so we lose our signed bounds 15155 * 2) it's known negative, thus the unsigned bounds capture the 15156 * signed bounds 15157 * 3) the signed bounds cross zero, so they tell us nothing 15158 * about the result 15159 * If the value in dst_reg is known nonnegative, then again the 15160 * unsigned bounds capture the signed bounds. 15161 * Thus, in all cases it suffices to blow away our signed bounds 15162 * and rely on inferring new ones from the unsigned bounds and 15163 * var_off of the result. 15164 */ 15165 dst_reg->s32_min_value = S32_MIN; 15166 dst_reg->s32_max_value = S32_MAX; 15167 15168 dst_reg->var_off = tnum_rshift(subreg, umin_val); 15169 dst_reg->u32_min_value >>= umax_val; 15170 dst_reg->u32_max_value >>= umin_val; 15171 15172 __mark_reg64_unbounded(dst_reg); 15173 __update_reg32_bounds(dst_reg); 15174 } 15175 15176 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 15177 struct bpf_reg_state *src_reg) 15178 { 15179 u64 umax_val = src_reg->umax_value; 15180 u64 umin_val = src_reg->umin_value; 15181 15182 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 15183 * be negative, then either: 15184 * 1) src_reg might be zero, so the sign bit of the result is 15185 * unknown, so we lose our signed bounds 15186 * 2) it's known negative, thus the unsigned bounds capture the 15187 * signed bounds 15188 * 3) the signed bounds cross zero, so they tell us nothing 15189 * about the result 15190 * If the value in dst_reg is known nonnegative, then again the 15191 * unsigned bounds capture the signed bounds. 15192 * Thus, in all cases it suffices to blow away our signed bounds 15193 * and rely on inferring new ones from the unsigned bounds and 15194 * var_off of the result. 15195 */ 15196 dst_reg->smin_value = S64_MIN; 15197 dst_reg->smax_value = S64_MAX; 15198 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 15199 dst_reg->umin_value >>= umax_val; 15200 dst_reg->umax_value >>= umin_val; 15201 15202 /* Its not easy to operate on alu32 bounds here because it depends 15203 * on bits being shifted in. Take easy way out and mark unbounded 15204 * so we can recalculate later from tnum. 15205 */ 15206 __mark_reg32_unbounded(dst_reg); 15207 __update_reg_bounds(dst_reg); 15208 } 15209 15210 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 15211 struct bpf_reg_state *src_reg) 15212 { 15213 u64 umin_val = src_reg->u32_min_value; 15214 15215 /* Upon reaching here, src_known is true and 15216 * umax_val is equal to umin_val. 15217 */ 15218 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 15219 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 15220 15221 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 15222 15223 /* blow away the dst_reg umin_value/umax_value and rely on 15224 * dst_reg var_off to refine the result. 15225 */ 15226 dst_reg->u32_min_value = 0; 15227 dst_reg->u32_max_value = U32_MAX; 15228 15229 __mark_reg64_unbounded(dst_reg); 15230 __update_reg32_bounds(dst_reg); 15231 } 15232 15233 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 15234 struct bpf_reg_state *src_reg) 15235 { 15236 u64 umin_val = src_reg->umin_value; 15237 15238 /* Upon reaching here, src_known is true and umax_val is equal 15239 * to umin_val. 15240 */ 15241 dst_reg->smin_value >>= umin_val; 15242 dst_reg->smax_value >>= umin_val; 15243 15244 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 15245 15246 /* blow away the dst_reg umin_value/umax_value and rely on 15247 * dst_reg var_off to refine the result. 15248 */ 15249 dst_reg->umin_value = 0; 15250 dst_reg->umax_value = U64_MAX; 15251 15252 /* Its not easy to operate on alu32 bounds here because it depends 15253 * on bits being shifted in from upper 32-bits. Take easy way out 15254 * and mark unbounded so we can recalculate later from tnum. 15255 */ 15256 __mark_reg32_unbounded(dst_reg); 15257 __update_reg_bounds(dst_reg); 15258 } 15259 15260 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 15261 const struct bpf_reg_state *src_reg) 15262 { 15263 bool src_is_const = false; 15264 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 15265 15266 if (insn_bitness == 32) { 15267 if (tnum_subreg_is_const(src_reg->var_off) 15268 && src_reg->s32_min_value == src_reg->s32_max_value 15269 && src_reg->u32_min_value == src_reg->u32_max_value) 15270 src_is_const = true; 15271 } else { 15272 if (tnum_is_const(src_reg->var_off) 15273 && src_reg->smin_value == src_reg->smax_value 15274 && src_reg->umin_value == src_reg->umax_value) 15275 src_is_const = true; 15276 } 15277 15278 switch (BPF_OP(insn->code)) { 15279 case BPF_ADD: 15280 case BPF_SUB: 15281 case BPF_NEG: 15282 case BPF_AND: 15283 case BPF_XOR: 15284 case BPF_OR: 15285 case BPF_MUL: 15286 return true; 15287 15288 /* Shift operators range is only computable if shift dimension operand 15289 * is a constant. Shifts greater than 31 or 63 are undefined. This 15290 * includes shifts by a negative number. 15291 */ 15292 case BPF_LSH: 15293 case BPF_RSH: 15294 case BPF_ARSH: 15295 return (src_is_const && src_reg->umax_value < insn_bitness); 15296 default: 15297 return false; 15298 } 15299 } 15300 15301 /* WARNING: This function does calculations on 64-bit values, but the actual 15302 * execution may occur on 32-bit values. Therefore, things like bitshifts 15303 * need extra checks in the 32-bit case. 15304 */ 15305 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 15306 struct bpf_insn *insn, 15307 struct bpf_reg_state *dst_reg, 15308 struct bpf_reg_state src_reg) 15309 { 15310 u8 opcode = BPF_OP(insn->code); 15311 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 15312 int ret; 15313 15314 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 15315 __mark_reg_unknown(env, dst_reg); 15316 return 0; 15317 } 15318 15319 if (sanitize_needed(opcode)) { 15320 ret = sanitize_val_alu(env, insn); 15321 if (ret < 0) 15322 return sanitize_err(env, insn, ret, NULL, NULL); 15323 } 15324 15325 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 15326 * There are two classes of instructions: The first class we track both 15327 * alu32 and alu64 sign/unsigned bounds independently this provides the 15328 * greatest amount of precision when alu operations are mixed with jmp32 15329 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 15330 * and BPF_OR. This is possible because these ops have fairly easy to 15331 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 15332 * See alu32 verifier tests for examples. The second class of 15333 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 15334 * with regards to tracking sign/unsigned bounds because the bits may 15335 * cross subreg boundaries in the alu64 case. When this happens we mark 15336 * the reg unbounded in the subreg bound space and use the resulting 15337 * tnum to calculate an approximation of the sign/unsigned bounds. 15338 */ 15339 switch (opcode) { 15340 case BPF_ADD: 15341 scalar32_min_max_add(dst_reg, &src_reg); 15342 scalar_min_max_add(dst_reg, &src_reg); 15343 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 15344 break; 15345 case BPF_SUB: 15346 scalar32_min_max_sub(dst_reg, &src_reg); 15347 scalar_min_max_sub(dst_reg, &src_reg); 15348 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 15349 break; 15350 case BPF_NEG: 15351 env->fake_reg[0] = *dst_reg; 15352 __mark_reg_known(dst_reg, 0); 15353 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 15354 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 15355 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 15356 break; 15357 case BPF_MUL: 15358 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 15359 scalar32_min_max_mul(dst_reg, &src_reg); 15360 scalar_min_max_mul(dst_reg, &src_reg); 15361 break; 15362 case BPF_AND: 15363 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 15364 scalar32_min_max_and(dst_reg, &src_reg); 15365 scalar_min_max_and(dst_reg, &src_reg); 15366 break; 15367 case BPF_OR: 15368 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 15369 scalar32_min_max_or(dst_reg, &src_reg); 15370 scalar_min_max_or(dst_reg, &src_reg); 15371 break; 15372 case BPF_XOR: 15373 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 15374 scalar32_min_max_xor(dst_reg, &src_reg); 15375 scalar_min_max_xor(dst_reg, &src_reg); 15376 break; 15377 case BPF_LSH: 15378 if (alu32) 15379 scalar32_min_max_lsh(dst_reg, &src_reg); 15380 else 15381 scalar_min_max_lsh(dst_reg, &src_reg); 15382 break; 15383 case BPF_RSH: 15384 if (alu32) 15385 scalar32_min_max_rsh(dst_reg, &src_reg); 15386 else 15387 scalar_min_max_rsh(dst_reg, &src_reg); 15388 break; 15389 case BPF_ARSH: 15390 if (alu32) 15391 scalar32_min_max_arsh(dst_reg, &src_reg); 15392 else 15393 scalar_min_max_arsh(dst_reg, &src_reg); 15394 break; 15395 default: 15396 break; 15397 } 15398 15399 /* ALU32 ops are zero extended into 64bit register */ 15400 if (alu32) 15401 zext_32_to_64(dst_reg); 15402 reg_bounds_sync(dst_reg); 15403 return 0; 15404 } 15405 15406 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 15407 * and var_off. 15408 */ 15409 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 15410 struct bpf_insn *insn) 15411 { 15412 struct bpf_verifier_state *vstate = env->cur_state; 15413 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15414 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 15415 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 15416 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 15417 u8 opcode = BPF_OP(insn->code); 15418 int err; 15419 15420 dst_reg = ®s[insn->dst_reg]; 15421 src_reg = NULL; 15422 15423 if (dst_reg->type == PTR_TO_ARENA) { 15424 struct bpf_insn_aux_data *aux = cur_aux(env); 15425 15426 if (BPF_CLASS(insn->code) == BPF_ALU64) 15427 /* 15428 * 32-bit operations zero upper bits automatically. 15429 * 64-bit operations need to be converted to 32. 15430 */ 15431 aux->needs_zext = true; 15432 15433 /* Any arithmetic operations are allowed on arena pointers */ 15434 return 0; 15435 } 15436 15437 if (dst_reg->type != SCALAR_VALUE) 15438 ptr_reg = dst_reg; 15439 15440 if (BPF_SRC(insn->code) == BPF_X) { 15441 src_reg = ®s[insn->src_reg]; 15442 if (src_reg->type != SCALAR_VALUE) { 15443 if (dst_reg->type != SCALAR_VALUE) { 15444 /* Combining two pointers by any ALU op yields 15445 * an arbitrary scalar. Disallow all math except 15446 * pointer subtraction 15447 */ 15448 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 15449 mark_reg_unknown(env, regs, insn->dst_reg); 15450 return 0; 15451 } 15452 verbose(env, "R%d pointer %s pointer prohibited\n", 15453 insn->dst_reg, 15454 bpf_alu_string[opcode >> 4]); 15455 return -EACCES; 15456 } else { 15457 /* scalar += pointer 15458 * This is legal, but we have to reverse our 15459 * src/dest handling in computing the range 15460 */ 15461 err = mark_chain_precision(env, insn->dst_reg); 15462 if (err) 15463 return err; 15464 return adjust_ptr_min_max_vals(env, insn, 15465 src_reg, dst_reg); 15466 } 15467 } else if (ptr_reg) { 15468 /* pointer += scalar */ 15469 err = mark_chain_precision(env, insn->src_reg); 15470 if (err) 15471 return err; 15472 return adjust_ptr_min_max_vals(env, insn, 15473 dst_reg, src_reg); 15474 } else if (dst_reg->precise) { 15475 /* if dst_reg is precise, src_reg should be precise as well */ 15476 err = mark_chain_precision(env, insn->src_reg); 15477 if (err) 15478 return err; 15479 } 15480 } else { 15481 /* Pretend the src is a reg with a known value, since we only 15482 * need to be able to read from this state. 15483 */ 15484 off_reg.type = SCALAR_VALUE; 15485 __mark_reg_known(&off_reg, insn->imm); 15486 src_reg = &off_reg; 15487 if (ptr_reg) /* pointer += K */ 15488 return adjust_ptr_min_max_vals(env, insn, 15489 ptr_reg, src_reg); 15490 } 15491 15492 /* Got here implies adding two SCALAR_VALUEs */ 15493 if (WARN_ON_ONCE(ptr_reg)) { 15494 print_verifier_state(env, vstate, vstate->curframe, true); 15495 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 15496 return -EFAULT; 15497 } 15498 if (WARN_ON(!src_reg)) { 15499 print_verifier_state(env, vstate, vstate->curframe, true); 15500 verbose(env, "verifier internal error: no src_reg\n"); 15501 return -EFAULT; 15502 } 15503 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 15504 if (err) 15505 return err; 15506 /* 15507 * Compilers can generate the code 15508 * r1 = r2 15509 * r1 += 0x1 15510 * if r2 < 1000 goto ... 15511 * use r1 in memory access 15512 * So for 64-bit alu remember constant delta between r2 and r1 and 15513 * update r1 after 'if' condition. 15514 */ 15515 if (env->bpf_capable && 15516 BPF_OP(insn->code) == BPF_ADD && !alu32 && 15517 dst_reg->id && is_reg_const(src_reg, false)) { 15518 u64 val = reg_const_value(src_reg, false); 15519 15520 if ((dst_reg->id & BPF_ADD_CONST) || 15521 /* prevent overflow in sync_linked_regs() later */ 15522 val > (u32)S32_MAX) { 15523 /* 15524 * If the register already went through rX += val 15525 * we cannot accumulate another val into rx->off. 15526 */ 15527 dst_reg->off = 0; 15528 dst_reg->id = 0; 15529 } else { 15530 dst_reg->id |= BPF_ADD_CONST; 15531 dst_reg->off = val; 15532 } 15533 } else { 15534 /* 15535 * Make sure ID is cleared otherwise dst_reg min/max could be 15536 * incorrectly propagated into other registers by sync_linked_regs() 15537 */ 15538 dst_reg->id = 0; 15539 } 15540 return 0; 15541 } 15542 15543 /* check validity of 32-bit and 64-bit arithmetic operations */ 15544 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 15545 { 15546 struct bpf_reg_state *regs = cur_regs(env); 15547 u8 opcode = BPF_OP(insn->code); 15548 int err; 15549 15550 if (opcode == BPF_END || opcode == BPF_NEG) { 15551 if (opcode == BPF_NEG) { 15552 if (BPF_SRC(insn->code) != BPF_K || 15553 insn->src_reg != BPF_REG_0 || 15554 insn->off != 0 || insn->imm != 0) { 15555 verbose(env, "BPF_NEG uses reserved fields\n"); 15556 return -EINVAL; 15557 } 15558 } else { 15559 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 15560 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 15561 (BPF_CLASS(insn->code) == BPF_ALU64 && 15562 BPF_SRC(insn->code) != BPF_TO_LE)) { 15563 verbose(env, "BPF_END uses reserved fields\n"); 15564 return -EINVAL; 15565 } 15566 } 15567 15568 /* check src operand */ 15569 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15570 if (err) 15571 return err; 15572 15573 if (is_pointer_value(env, insn->dst_reg)) { 15574 verbose(env, "R%d pointer arithmetic prohibited\n", 15575 insn->dst_reg); 15576 return -EACCES; 15577 } 15578 15579 /* check dest operand */ 15580 if (opcode == BPF_NEG) { 15581 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15582 err = err ?: adjust_scalar_min_max_vals(env, insn, 15583 ®s[insn->dst_reg], 15584 regs[insn->dst_reg]); 15585 } else { 15586 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15587 } 15588 if (err) 15589 return err; 15590 15591 } else if (opcode == BPF_MOV) { 15592 15593 if (BPF_SRC(insn->code) == BPF_X) { 15594 if (BPF_CLASS(insn->code) == BPF_ALU) { 15595 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 15596 insn->imm) { 15597 verbose(env, "BPF_MOV uses reserved fields\n"); 15598 return -EINVAL; 15599 } 15600 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 15601 if (insn->imm != 1 && insn->imm != 1u << 16) { 15602 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 15603 return -EINVAL; 15604 } 15605 if (!env->prog->aux->arena) { 15606 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 15607 return -EINVAL; 15608 } 15609 } else { 15610 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 15611 insn->off != 32) || insn->imm) { 15612 verbose(env, "BPF_MOV uses reserved fields\n"); 15613 return -EINVAL; 15614 } 15615 } 15616 15617 /* check src operand */ 15618 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15619 if (err) 15620 return err; 15621 } else { 15622 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 15623 verbose(env, "BPF_MOV uses reserved fields\n"); 15624 return -EINVAL; 15625 } 15626 } 15627 15628 /* check dest operand, mark as required later */ 15629 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15630 if (err) 15631 return err; 15632 15633 if (BPF_SRC(insn->code) == BPF_X) { 15634 struct bpf_reg_state *src_reg = regs + insn->src_reg; 15635 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 15636 15637 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15638 if (insn->imm) { 15639 /* off == BPF_ADDR_SPACE_CAST */ 15640 mark_reg_unknown(env, regs, insn->dst_reg); 15641 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 15642 dst_reg->type = PTR_TO_ARENA; 15643 /* PTR_TO_ARENA is 32-bit */ 15644 dst_reg->subreg_def = env->insn_idx + 1; 15645 } 15646 } else if (insn->off == 0) { 15647 /* case: R1 = R2 15648 * copy register state to dest reg 15649 */ 15650 assign_scalar_id_before_mov(env, src_reg); 15651 copy_register_state(dst_reg, src_reg); 15652 dst_reg->live |= REG_LIVE_WRITTEN; 15653 dst_reg->subreg_def = DEF_NOT_SUBREG; 15654 } else { 15655 /* case: R1 = (s8, s16 s32)R2 */ 15656 if (is_pointer_value(env, insn->src_reg)) { 15657 verbose(env, 15658 "R%d sign-extension part of pointer\n", 15659 insn->src_reg); 15660 return -EACCES; 15661 } else if (src_reg->type == SCALAR_VALUE) { 15662 bool no_sext; 15663 15664 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 15665 if (no_sext) 15666 assign_scalar_id_before_mov(env, src_reg); 15667 copy_register_state(dst_reg, src_reg); 15668 if (!no_sext) 15669 dst_reg->id = 0; 15670 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 15671 dst_reg->live |= REG_LIVE_WRITTEN; 15672 dst_reg->subreg_def = DEF_NOT_SUBREG; 15673 } else { 15674 mark_reg_unknown(env, regs, insn->dst_reg); 15675 } 15676 } 15677 } else { 15678 /* R1 = (u32) R2 */ 15679 if (is_pointer_value(env, insn->src_reg)) { 15680 verbose(env, 15681 "R%d partial copy of pointer\n", 15682 insn->src_reg); 15683 return -EACCES; 15684 } else if (src_reg->type == SCALAR_VALUE) { 15685 if (insn->off == 0) { 15686 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 15687 15688 if (is_src_reg_u32) 15689 assign_scalar_id_before_mov(env, src_reg); 15690 copy_register_state(dst_reg, src_reg); 15691 /* Make sure ID is cleared if src_reg is not in u32 15692 * range otherwise dst_reg min/max could be incorrectly 15693 * propagated into src_reg by sync_linked_regs() 15694 */ 15695 if (!is_src_reg_u32) 15696 dst_reg->id = 0; 15697 dst_reg->live |= REG_LIVE_WRITTEN; 15698 dst_reg->subreg_def = env->insn_idx + 1; 15699 } else { 15700 /* case: W1 = (s8, s16)W2 */ 15701 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 15702 15703 if (no_sext) 15704 assign_scalar_id_before_mov(env, src_reg); 15705 copy_register_state(dst_reg, src_reg); 15706 if (!no_sext) 15707 dst_reg->id = 0; 15708 dst_reg->live |= REG_LIVE_WRITTEN; 15709 dst_reg->subreg_def = env->insn_idx + 1; 15710 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 15711 } 15712 } else { 15713 mark_reg_unknown(env, regs, 15714 insn->dst_reg); 15715 } 15716 zext_32_to_64(dst_reg); 15717 reg_bounds_sync(dst_reg); 15718 } 15719 } else { 15720 /* case: R = imm 15721 * remember the value we stored into this reg 15722 */ 15723 /* clear any state __mark_reg_known doesn't set */ 15724 mark_reg_unknown(env, regs, insn->dst_reg); 15725 regs[insn->dst_reg].type = SCALAR_VALUE; 15726 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15727 __mark_reg_known(regs + insn->dst_reg, 15728 insn->imm); 15729 } else { 15730 __mark_reg_known(regs + insn->dst_reg, 15731 (u32)insn->imm); 15732 } 15733 } 15734 15735 } else if (opcode > BPF_END) { 15736 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 15737 return -EINVAL; 15738 15739 } else { /* all other ALU ops: and, sub, xor, add, ... */ 15740 15741 if (BPF_SRC(insn->code) == BPF_X) { 15742 if (insn->imm != 0 || insn->off > 1 || 15743 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 15744 verbose(env, "BPF_ALU uses reserved fields\n"); 15745 return -EINVAL; 15746 } 15747 /* check src1 operand */ 15748 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15749 if (err) 15750 return err; 15751 } else { 15752 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 15753 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 15754 verbose(env, "BPF_ALU uses reserved fields\n"); 15755 return -EINVAL; 15756 } 15757 } 15758 15759 /* check src2 operand */ 15760 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15761 if (err) 15762 return err; 15763 15764 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 15765 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 15766 verbose(env, "div by zero\n"); 15767 return -EINVAL; 15768 } 15769 15770 if ((opcode == BPF_LSH || opcode == BPF_RSH || 15771 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 15772 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 15773 15774 if (insn->imm < 0 || insn->imm >= size) { 15775 verbose(env, "invalid shift %d\n", insn->imm); 15776 return -EINVAL; 15777 } 15778 } 15779 15780 /* check dest operand */ 15781 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15782 err = err ?: adjust_reg_min_max_vals(env, insn); 15783 if (err) 15784 return err; 15785 } 15786 15787 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 15788 } 15789 15790 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 15791 struct bpf_reg_state *dst_reg, 15792 enum bpf_reg_type type, 15793 bool range_right_open) 15794 { 15795 struct bpf_func_state *state; 15796 struct bpf_reg_state *reg; 15797 int new_range; 15798 15799 if (dst_reg->off < 0 || 15800 (dst_reg->off == 0 && range_right_open)) 15801 /* This doesn't give us any range */ 15802 return; 15803 15804 if (dst_reg->umax_value > MAX_PACKET_OFF || 15805 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 15806 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15807 * than pkt_end, but that's because it's also less than pkt. 15808 */ 15809 return; 15810 15811 new_range = dst_reg->off; 15812 if (range_right_open) 15813 new_range++; 15814 15815 /* Examples for register markings: 15816 * 15817 * pkt_data in dst register: 15818 * 15819 * r2 = r3; 15820 * r2 += 8; 15821 * if (r2 > pkt_end) goto <handle exception> 15822 * <access okay> 15823 * 15824 * r2 = r3; 15825 * r2 += 8; 15826 * if (r2 < pkt_end) goto <access okay> 15827 * <handle exception> 15828 * 15829 * Where: 15830 * r2 == dst_reg, pkt_end == src_reg 15831 * r2=pkt(id=n,off=8,r=0) 15832 * r3=pkt(id=n,off=0,r=0) 15833 * 15834 * pkt_data in src register: 15835 * 15836 * r2 = r3; 15837 * r2 += 8; 15838 * if (pkt_end >= r2) goto <access okay> 15839 * <handle exception> 15840 * 15841 * r2 = r3; 15842 * r2 += 8; 15843 * if (pkt_end <= r2) goto <handle exception> 15844 * <access okay> 15845 * 15846 * Where: 15847 * pkt_end == dst_reg, r2 == src_reg 15848 * r2=pkt(id=n,off=8,r=0) 15849 * r3=pkt(id=n,off=0,r=0) 15850 * 15851 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15852 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15853 * and [r3, r3 + 8-1) respectively is safe to access depending on 15854 * the check. 15855 */ 15856 15857 /* If our ids match, then we must have the same max_value. And we 15858 * don't care about the other reg's fixed offset, since if it's too big 15859 * the range won't allow anything. 15860 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 15861 */ 15862 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15863 if (reg->type == type && reg->id == dst_reg->id) 15864 /* keep the maximum range already checked */ 15865 reg->range = max(reg->range, new_range); 15866 })); 15867 } 15868 15869 /* 15870 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15871 */ 15872 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15873 u8 opcode, bool is_jmp32) 15874 { 15875 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15876 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15877 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 15878 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 15879 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 15880 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 15881 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 15882 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 15883 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 15884 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 15885 15886 switch (opcode) { 15887 case BPF_JEQ: 15888 /* constants, umin/umax and smin/smax checks would be 15889 * redundant in this case because they all should match 15890 */ 15891 if (tnum_is_const(t1) && tnum_is_const(t2)) 15892 return t1.value == t2.value; 15893 /* non-overlapping ranges */ 15894 if (umin1 > umax2 || umax1 < umin2) 15895 return 0; 15896 if (smin1 > smax2 || smax1 < smin2) 15897 return 0; 15898 if (!is_jmp32) { 15899 /* if 64-bit ranges are inconclusive, see if we can 15900 * utilize 32-bit subrange knowledge to eliminate 15901 * branches that can't be taken a priori 15902 */ 15903 if (reg1->u32_min_value > reg2->u32_max_value || 15904 reg1->u32_max_value < reg2->u32_min_value) 15905 return 0; 15906 if (reg1->s32_min_value > reg2->s32_max_value || 15907 reg1->s32_max_value < reg2->s32_min_value) 15908 return 0; 15909 } 15910 break; 15911 case BPF_JNE: 15912 /* constants, umin/umax and smin/smax checks would be 15913 * redundant in this case because they all should match 15914 */ 15915 if (tnum_is_const(t1) && tnum_is_const(t2)) 15916 return t1.value != t2.value; 15917 /* non-overlapping ranges */ 15918 if (umin1 > umax2 || umax1 < umin2) 15919 return 1; 15920 if (smin1 > smax2 || smax1 < smin2) 15921 return 1; 15922 if (!is_jmp32) { 15923 /* if 64-bit ranges are inconclusive, see if we can 15924 * utilize 32-bit subrange knowledge to eliminate 15925 * branches that can't be taken a priori 15926 */ 15927 if (reg1->u32_min_value > reg2->u32_max_value || 15928 reg1->u32_max_value < reg2->u32_min_value) 15929 return 1; 15930 if (reg1->s32_min_value > reg2->s32_max_value || 15931 reg1->s32_max_value < reg2->s32_min_value) 15932 return 1; 15933 } 15934 break; 15935 case BPF_JSET: 15936 if (!is_reg_const(reg2, is_jmp32)) { 15937 swap(reg1, reg2); 15938 swap(t1, t2); 15939 } 15940 if (!is_reg_const(reg2, is_jmp32)) 15941 return -1; 15942 if ((~t1.mask & t1.value) & t2.value) 15943 return 1; 15944 if (!((t1.mask | t1.value) & t2.value)) 15945 return 0; 15946 break; 15947 case BPF_JGT: 15948 if (umin1 > umax2) 15949 return 1; 15950 else if (umax1 <= umin2) 15951 return 0; 15952 break; 15953 case BPF_JSGT: 15954 if (smin1 > smax2) 15955 return 1; 15956 else if (smax1 <= smin2) 15957 return 0; 15958 break; 15959 case BPF_JLT: 15960 if (umax1 < umin2) 15961 return 1; 15962 else if (umin1 >= umax2) 15963 return 0; 15964 break; 15965 case BPF_JSLT: 15966 if (smax1 < smin2) 15967 return 1; 15968 else if (smin1 >= smax2) 15969 return 0; 15970 break; 15971 case BPF_JGE: 15972 if (umin1 >= umax2) 15973 return 1; 15974 else if (umax1 < umin2) 15975 return 0; 15976 break; 15977 case BPF_JSGE: 15978 if (smin1 >= smax2) 15979 return 1; 15980 else if (smax1 < smin2) 15981 return 0; 15982 break; 15983 case BPF_JLE: 15984 if (umax1 <= umin2) 15985 return 1; 15986 else if (umin1 > umax2) 15987 return 0; 15988 break; 15989 case BPF_JSLE: 15990 if (smax1 <= smin2) 15991 return 1; 15992 else if (smin1 > smax2) 15993 return 0; 15994 break; 15995 } 15996 15997 return -1; 15998 } 15999 16000 static int flip_opcode(u32 opcode) 16001 { 16002 /* How can we transform "a <op> b" into "b <op> a"? */ 16003 static const u8 opcode_flip[16] = { 16004 /* these stay the same */ 16005 [BPF_JEQ >> 4] = BPF_JEQ, 16006 [BPF_JNE >> 4] = BPF_JNE, 16007 [BPF_JSET >> 4] = BPF_JSET, 16008 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 16009 [BPF_JGE >> 4] = BPF_JLE, 16010 [BPF_JGT >> 4] = BPF_JLT, 16011 [BPF_JLE >> 4] = BPF_JGE, 16012 [BPF_JLT >> 4] = BPF_JGT, 16013 [BPF_JSGE >> 4] = BPF_JSLE, 16014 [BPF_JSGT >> 4] = BPF_JSLT, 16015 [BPF_JSLE >> 4] = BPF_JSGE, 16016 [BPF_JSLT >> 4] = BPF_JSGT 16017 }; 16018 return opcode_flip[opcode >> 4]; 16019 } 16020 16021 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 16022 struct bpf_reg_state *src_reg, 16023 u8 opcode) 16024 { 16025 struct bpf_reg_state *pkt; 16026 16027 if (src_reg->type == PTR_TO_PACKET_END) { 16028 pkt = dst_reg; 16029 } else if (dst_reg->type == PTR_TO_PACKET_END) { 16030 pkt = src_reg; 16031 opcode = flip_opcode(opcode); 16032 } else { 16033 return -1; 16034 } 16035 16036 if (pkt->range >= 0) 16037 return -1; 16038 16039 switch (opcode) { 16040 case BPF_JLE: 16041 /* pkt <= pkt_end */ 16042 fallthrough; 16043 case BPF_JGT: 16044 /* pkt > pkt_end */ 16045 if (pkt->range == BEYOND_PKT_END) 16046 /* pkt has at last one extra byte beyond pkt_end */ 16047 return opcode == BPF_JGT; 16048 break; 16049 case BPF_JLT: 16050 /* pkt < pkt_end */ 16051 fallthrough; 16052 case BPF_JGE: 16053 /* pkt >= pkt_end */ 16054 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 16055 return opcode == BPF_JGE; 16056 break; 16057 } 16058 return -1; 16059 } 16060 16061 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 16062 * and return: 16063 * 1 - branch will be taken and "goto target" will be executed 16064 * 0 - branch will not be taken and fall-through to next insn 16065 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 16066 * range [0,10] 16067 */ 16068 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 16069 u8 opcode, bool is_jmp32) 16070 { 16071 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 16072 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 16073 16074 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 16075 u64 val; 16076 16077 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 16078 if (!is_reg_const(reg2, is_jmp32)) { 16079 opcode = flip_opcode(opcode); 16080 swap(reg1, reg2); 16081 } 16082 /* and ensure that reg2 is a constant */ 16083 if (!is_reg_const(reg2, is_jmp32)) 16084 return -1; 16085 16086 if (!reg_not_null(reg1)) 16087 return -1; 16088 16089 /* If pointer is valid tests against zero will fail so we can 16090 * use this to direct branch taken. 16091 */ 16092 val = reg_const_value(reg2, is_jmp32); 16093 if (val != 0) 16094 return -1; 16095 16096 switch (opcode) { 16097 case BPF_JEQ: 16098 return 0; 16099 case BPF_JNE: 16100 return 1; 16101 default: 16102 return -1; 16103 } 16104 } 16105 16106 /* now deal with two scalars, but not necessarily constants */ 16107 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 16108 } 16109 16110 /* Opcode that corresponds to a *false* branch condition. 16111 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 16112 */ 16113 static u8 rev_opcode(u8 opcode) 16114 { 16115 switch (opcode) { 16116 case BPF_JEQ: return BPF_JNE; 16117 case BPF_JNE: return BPF_JEQ; 16118 /* JSET doesn't have it's reverse opcode in BPF, so add 16119 * BPF_X flag to denote the reverse of that operation 16120 */ 16121 case BPF_JSET: return BPF_JSET | BPF_X; 16122 case BPF_JSET | BPF_X: return BPF_JSET; 16123 case BPF_JGE: return BPF_JLT; 16124 case BPF_JGT: return BPF_JLE; 16125 case BPF_JLE: return BPF_JGT; 16126 case BPF_JLT: return BPF_JGE; 16127 case BPF_JSGE: return BPF_JSLT; 16128 case BPF_JSGT: return BPF_JSLE; 16129 case BPF_JSLE: return BPF_JSGT; 16130 case BPF_JSLT: return BPF_JSGE; 16131 default: return 0; 16132 } 16133 } 16134 16135 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 16136 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 16137 u8 opcode, bool is_jmp32) 16138 { 16139 struct tnum t; 16140 u64 val; 16141 16142 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 16143 switch (opcode) { 16144 case BPF_JGE: 16145 case BPF_JGT: 16146 case BPF_JSGE: 16147 case BPF_JSGT: 16148 opcode = flip_opcode(opcode); 16149 swap(reg1, reg2); 16150 break; 16151 default: 16152 break; 16153 } 16154 16155 switch (opcode) { 16156 case BPF_JEQ: 16157 if (is_jmp32) { 16158 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 16159 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 16160 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 16161 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 16162 reg2->u32_min_value = reg1->u32_min_value; 16163 reg2->u32_max_value = reg1->u32_max_value; 16164 reg2->s32_min_value = reg1->s32_min_value; 16165 reg2->s32_max_value = reg1->s32_max_value; 16166 16167 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 16168 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 16169 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 16170 } else { 16171 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 16172 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 16173 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 16174 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 16175 reg2->umin_value = reg1->umin_value; 16176 reg2->umax_value = reg1->umax_value; 16177 reg2->smin_value = reg1->smin_value; 16178 reg2->smax_value = reg1->smax_value; 16179 16180 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 16181 reg2->var_off = reg1->var_off; 16182 } 16183 break; 16184 case BPF_JNE: 16185 if (!is_reg_const(reg2, is_jmp32)) 16186 swap(reg1, reg2); 16187 if (!is_reg_const(reg2, is_jmp32)) 16188 break; 16189 16190 /* try to recompute the bound of reg1 if reg2 is a const and 16191 * is exactly the edge of reg1. 16192 */ 16193 val = reg_const_value(reg2, is_jmp32); 16194 if (is_jmp32) { 16195 /* u32_min_value is not equal to 0xffffffff at this point, 16196 * because otherwise u32_max_value is 0xffffffff as well, 16197 * in such a case both reg1 and reg2 would be constants, 16198 * jump would be predicted and reg_set_min_max() won't 16199 * be called. 16200 * 16201 * Same reasoning works for all {u,s}{min,max}{32,64} cases 16202 * below. 16203 */ 16204 if (reg1->u32_min_value == (u32)val) 16205 reg1->u32_min_value++; 16206 if (reg1->u32_max_value == (u32)val) 16207 reg1->u32_max_value--; 16208 if (reg1->s32_min_value == (s32)val) 16209 reg1->s32_min_value++; 16210 if (reg1->s32_max_value == (s32)val) 16211 reg1->s32_max_value--; 16212 } else { 16213 if (reg1->umin_value == (u64)val) 16214 reg1->umin_value++; 16215 if (reg1->umax_value == (u64)val) 16216 reg1->umax_value--; 16217 if (reg1->smin_value == (s64)val) 16218 reg1->smin_value++; 16219 if (reg1->smax_value == (s64)val) 16220 reg1->smax_value--; 16221 } 16222 break; 16223 case BPF_JSET: 16224 if (!is_reg_const(reg2, is_jmp32)) 16225 swap(reg1, reg2); 16226 if (!is_reg_const(reg2, is_jmp32)) 16227 break; 16228 val = reg_const_value(reg2, is_jmp32); 16229 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 16230 * requires single bit to learn something useful. E.g., if we 16231 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 16232 * are actually set? We can learn something definite only if 16233 * it's a single-bit value to begin with. 16234 * 16235 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 16236 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 16237 * bit 1 is set, which we can readily use in adjustments. 16238 */ 16239 if (!is_power_of_2(val)) 16240 break; 16241 if (is_jmp32) { 16242 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 16243 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 16244 } else { 16245 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 16246 } 16247 break; 16248 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 16249 if (!is_reg_const(reg2, is_jmp32)) 16250 swap(reg1, reg2); 16251 if (!is_reg_const(reg2, is_jmp32)) 16252 break; 16253 val = reg_const_value(reg2, is_jmp32); 16254 /* Forget the ranges before narrowing tnums, to avoid invariant 16255 * violations if we're on a dead branch. 16256 */ 16257 __mark_reg_unbounded(reg1); 16258 if (is_jmp32) { 16259 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 16260 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 16261 } else { 16262 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 16263 } 16264 break; 16265 case BPF_JLE: 16266 if (is_jmp32) { 16267 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 16268 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 16269 } else { 16270 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 16271 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 16272 } 16273 break; 16274 case BPF_JLT: 16275 if (is_jmp32) { 16276 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 16277 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 16278 } else { 16279 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 16280 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 16281 } 16282 break; 16283 case BPF_JSLE: 16284 if (is_jmp32) { 16285 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 16286 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 16287 } else { 16288 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 16289 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 16290 } 16291 break; 16292 case BPF_JSLT: 16293 if (is_jmp32) { 16294 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 16295 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 16296 } else { 16297 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 16298 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 16299 } 16300 break; 16301 default: 16302 return; 16303 } 16304 } 16305 16306 /* Adjusts the register min/max values in the case that the dst_reg and 16307 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 16308 * check, in which case we have a fake SCALAR_VALUE representing insn->imm). 16309 * Technically we can do similar adjustments for pointers to the same object, 16310 * but we don't support that right now. 16311 */ 16312 static int reg_set_min_max(struct bpf_verifier_env *env, 16313 struct bpf_reg_state *true_reg1, 16314 struct bpf_reg_state *true_reg2, 16315 struct bpf_reg_state *false_reg1, 16316 struct bpf_reg_state *false_reg2, 16317 u8 opcode, bool is_jmp32) 16318 { 16319 int err; 16320 16321 /* If either register is a pointer, we can't learn anything about its 16322 * variable offset from the compare (unless they were a pointer into 16323 * the same object, but we don't bother with that). 16324 */ 16325 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 16326 return 0; 16327 16328 /* fallthrough (FALSE) branch */ 16329 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 16330 reg_bounds_sync(false_reg1); 16331 reg_bounds_sync(false_reg2); 16332 16333 /* jump (TRUE) branch */ 16334 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 16335 reg_bounds_sync(true_reg1); 16336 reg_bounds_sync(true_reg2); 16337 16338 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 16339 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 16340 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 16341 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 16342 return err; 16343 } 16344 16345 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 16346 struct bpf_reg_state *reg, u32 id, 16347 bool is_null) 16348 { 16349 if (type_may_be_null(reg->type) && reg->id == id && 16350 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 16351 /* Old offset (both fixed and variable parts) should have been 16352 * known-zero, because we don't allow pointer arithmetic on 16353 * pointers that might be NULL. If we see this happening, don't 16354 * convert the register. 16355 * 16356 * But in some cases, some helpers that return local kptrs 16357 * advance offset for the returned pointer. In those cases, it 16358 * is fine to expect to see reg->off. 16359 */ 16360 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 16361 return; 16362 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 16363 WARN_ON_ONCE(reg->off)) 16364 return; 16365 16366 if (is_null) { 16367 reg->type = SCALAR_VALUE; 16368 /* We don't need id and ref_obj_id from this point 16369 * onwards anymore, thus we should better reset it, 16370 * so that state pruning has chances to take effect. 16371 */ 16372 reg->id = 0; 16373 reg->ref_obj_id = 0; 16374 16375 return; 16376 } 16377 16378 mark_ptr_not_null_reg(reg); 16379 16380 if (!reg_may_point_to_spin_lock(reg)) { 16381 /* For not-NULL ptr, reg->ref_obj_id will be reset 16382 * in release_reference(). 16383 * 16384 * reg->id is still used by spin_lock ptr. Other 16385 * than spin_lock ptr type, reg->id can be reset. 16386 */ 16387 reg->id = 0; 16388 } 16389 } 16390 } 16391 16392 /* The logic is similar to find_good_pkt_pointers(), both could eventually 16393 * be folded together at some point. 16394 */ 16395 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 16396 bool is_null) 16397 { 16398 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 16399 struct bpf_reg_state *regs = state->regs, *reg; 16400 u32 ref_obj_id = regs[regno].ref_obj_id; 16401 u32 id = regs[regno].id; 16402 16403 if (ref_obj_id && ref_obj_id == id && is_null) 16404 /* regs[regno] is in the " == NULL" branch. 16405 * No one could have freed the reference state before 16406 * doing the NULL check. 16407 */ 16408 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 16409 16410 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 16411 mark_ptr_or_null_reg(state, reg, id, is_null); 16412 })); 16413 } 16414 16415 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 16416 struct bpf_reg_state *dst_reg, 16417 struct bpf_reg_state *src_reg, 16418 struct bpf_verifier_state *this_branch, 16419 struct bpf_verifier_state *other_branch) 16420 { 16421 if (BPF_SRC(insn->code) != BPF_X) 16422 return false; 16423 16424 /* Pointers are always 64-bit. */ 16425 if (BPF_CLASS(insn->code) == BPF_JMP32) 16426 return false; 16427 16428 switch (BPF_OP(insn->code)) { 16429 case BPF_JGT: 16430 if ((dst_reg->type == PTR_TO_PACKET && 16431 src_reg->type == PTR_TO_PACKET_END) || 16432 (dst_reg->type == PTR_TO_PACKET_META && 16433 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16434 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 16435 find_good_pkt_pointers(this_branch, dst_reg, 16436 dst_reg->type, false); 16437 mark_pkt_end(other_branch, insn->dst_reg, true); 16438 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16439 src_reg->type == PTR_TO_PACKET) || 16440 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16441 src_reg->type == PTR_TO_PACKET_META)) { 16442 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 16443 find_good_pkt_pointers(other_branch, src_reg, 16444 src_reg->type, true); 16445 mark_pkt_end(this_branch, insn->src_reg, false); 16446 } else { 16447 return false; 16448 } 16449 break; 16450 case BPF_JLT: 16451 if ((dst_reg->type == PTR_TO_PACKET && 16452 src_reg->type == PTR_TO_PACKET_END) || 16453 (dst_reg->type == PTR_TO_PACKET_META && 16454 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16455 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 16456 find_good_pkt_pointers(other_branch, dst_reg, 16457 dst_reg->type, true); 16458 mark_pkt_end(this_branch, insn->dst_reg, false); 16459 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16460 src_reg->type == PTR_TO_PACKET) || 16461 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16462 src_reg->type == PTR_TO_PACKET_META)) { 16463 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 16464 find_good_pkt_pointers(this_branch, src_reg, 16465 src_reg->type, false); 16466 mark_pkt_end(other_branch, insn->src_reg, true); 16467 } else { 16468 return false; 16469 } 16470 break; 16471 case BPF_JGE: 16472 if ((dst_reg->type == PTR_TO_PACKET && 16473 src_reg->type == PTR_TO_PACKET_END) || 16474 (dst_reg->type == PTR_TO_PACKET_META && 16475 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16476 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 16477 find_good_pkt_pointers(this_branch, dst_reg, 16478 dst_reg->type, true); 16479 mark_pkt_end(other_branch, insn->dst_reg, false); 16480 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16481 src_reg->type == PTR_TO_PACKET) || 16482 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16483 src_reg->type == PTR_TO_PACKET_META)) { 16484 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 16485 find_good_pkt_pointers(other_branch, src_reg, 16486 src_reg->type, false); 16487 mark_pkt_end(this_branch, insn->src_reg, true); 16488 } else { 16489 return false; 16490 } 16491 break; 16492 case BPF_JLE: 16493 if ((dst_reg->type == PTR_TO_PACKET && 16494 src_reg->type == PTR_TO_PACKET_END) || 16495 (dst_reg->type == PTR_TO_PACKET_META && 16496 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16497 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 16498 find_good_pkt_pointers(other_branch, dst_reg, 16499 dst_reg->type, false); 16500 mark_pkt_end(this_branch, insn->dst_reg, true); 16501 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16502 src_reg->type == PTR_TO_PACKET) || 16503 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16504 src_reg->type == PTR_TO_PACKET_META)) { 16505 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 16506 find_good_pkt_pointers(this_branch, src_reg, 16507 src_reg->type, true); 16508 mark_pkt_end(other_branch, insn->src_reg, false); 16509 } else { 16510 return false; 16511 } 16512 break; 16513 default: 16514 return false; 16515 } 16516 16517 return true; 16518 } 16519 16520 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 16521 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 16522 { 16523 struct linked_reg *e; 16524 16525 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 16526 return; 16527 16528 e = linked_regs_push(reg_set); 16529 if (e) { 16530 e->frameno = frameno; 16531 e->is_reg = is_reg; 16532 e->regno = spi_or_reg; 16533 } else { 16534 reg->id = 0; 16535 } 16536 } 16537 16538 /* For all R being scalar registers or spilled scalar registers 16539 * in verifier state, save R in linked_regs if R->id == id. 16540 * If there are too many Rs sharing same id, reset id for leftover Rs. 16541 */ 16542 static void collect_linked_regs(struct bpf_verifier_state *vstate, u32 id, 16543 struct linked_regs *linked_regs) 16544 { 16545 struct bpf_func_state *func; 16546 struct bpf_reg_state *reg; 16547 int i, j; 16548 16549 id = id & ~BPF_ADD_CONST; 16550 for (i = vstate->curframe; i >= 0; i--) { 16551 func = vstate->frame[i]; 16552 for (j = 0; j < BPF_REG_FP; j++) { 16553 reg = &func->regs[j]; 16554 __collect_linked_regs(linked_regs, reg, id, i, j, true); 16555 } 16556 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 16557 if (!is_spilled_reg(&func->stack[j])) 16558 continue; 16559 reg = &func->stack[j].spilled_ptr; 16560 __collect_linked_regs(linked_regs, reg, id, i, j, false); 16561 } 16562 } 16563 } 16564 16565 /* For all R in linked_regs, copy known_reg range into R 16566 * if R->id == known_reg->id. 16567 */ 16568 static void sync_linked_regs(struct bpf_verifier_state *vstate, struct bpf_reg_state *known_reg, 16569 struct linked_regs *linked_regs) 16570 { 16571 struct bpf_reg_state fake_reg; 16572 struct bpf_reg_state *reg; 16573 struct linked_reg *e; 16574 int i; 16575 16576 for (i = 0; i < linked_regs->cnt; ++i) { 16577 e = &linked_regs->entries[i]; 16578 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 16579 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 16580 if (reg->type != SCALAR_VALUE || reg == known_reg) 16581 continue; 16582 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 16583 continue; 16584 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 16585 reg->off == known_reg->off) { 16586 s32 saved_subreg_def = reg->subreg_def; 16587 16588 copy_register_state(reg, known_reg); 16589 reg->subreg_def = saved_subreg_def; 16590 } else { 16591 s32 saved_subreg_def = reg->subreg_def; 16592 s32 saved_off = reg->off; 16593 16594 fake_reg.type = SCALAR_VALUE; 16595 __mark_reg_known(&fake_reg, (s32)reg->off - (s32)known_reg->off); 16596 16597 /* reg = known_reg; reg += delta */ 16598 copy_register_state(reg, known_reg); 16599 /* 16600 * Must preserve off, id and add_const flag, 16601 * otherwise another sync_linked_regs() will be incorrect. 16602 */ 16603 reg->off = saved_off; 16604 reg->subreg_def = saved_subreg_def; 16605 16606 scalar32_min_max_add(reg, &fake_reg); 16607 scalar_min_max_add(reg, &fake_reg); 16608 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 16609 } 16610 } 16611 } 16612 16613 static int check_cond_jmp_op(struct bpf_verifier_env *env, 16614 struct bpf_insn *insn, int *insn_idx) 16615 { 16616 struct bpf_verifier_state *this_branch = env->cur_state; 16617 struct bpf_verifier_state *other_branch; 16618 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 16619 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 16620 struct bpf_reg_state *eq_branch_regs; 16621 struct linked_regs linked_regs = {}; 16622 u8 opcode = BPF_OP(insn->code); 16623 int insn_flags = 0; 16624 bool is_jmp32; 16625 int pred = -1; 16626 int err; 16627 16628 /* Only conditional jumps are expected to reach here. */ 16629 if (opcode == BPF_JA || opcode > BPF_JCOND) { 16630 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 16631 return -EINVAL; 16632 } 16633 16634 if (opcode == BPF_JCOND) { 16635 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 16636 int idx = *insn_idx; 16637 16638 if (insn->code != (BPF_JMP | BPF_JCOND) || 16639 insn->src_reg != BPF_MAY_GOTO || 16640 insn->dst_reg || insn->imm) { 16641 verbose(env, "invalid may_goto imm %d\n", insn->imm); 16642 return -EINVAL; 16643 } 16644 prev_st = find_prev_entry(env, cur_st->parent, idx); 16645 16646 /* branch out 'fallthrough' insn as a new state to explore */ 16647 queued_st = push_stack(env, idx + 1, idx, false); 16648 if (!queued_st) 16649 return -ENOMEM; 16650 16651 queued_st->may_goto_depth++; 16652 if (prev_st) 16653 widen_imprecise_scalars(env, prev_st, queued_st); 16654 *insn_idx += insn->off; 16655 return 0; 16656 } 16657 16658 /* check src2 operand */ 16659 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16660 if (err) 16661 return err; 16662 16663 dst_reg = ®s[insn->dst_reg]; 16664 if (BPF_SRC(insn->code) == BPF_X) { 16665 if (insn->imm != 0) { 16666 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 16667 return -EINVAL; 16668 } 16669 16670 /* check src1 operand */ 16671 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16672 if (err) 16673 return err; 16674 16675 src_reg = ®s[insn->src_reg]; 16676 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 16677 is_pointer_value(env, insn->src_reg)) { 16678 verbose(env, "R%d pointer comparison prohibited\n", 16679 insn->src_reg); 16680 return -EACCES; 16681 } 16682 16683 if (src_reg->type == PTR_TO_STACK) 16684 insn_flags |= INSN_F_SRC_REG_STACK; 16685 if (dst_reg->type == PTR_TO_STACK) 16686 insn_flags |= INSN_F_DST_REG_STACK; 16687 } else { 16688 if (insn->src_reg != BPF_REG_0) { 16689 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 16690 return -EINVAL; 16691 } 16692 src_reg = &env->fake_reg[0]; 16693 memset(src_reg, 0, sizeof(*src_reg)); 16694 src_reg->type = SCALAR_VALUE; 16695 __mark_reg_known(src_reg, insn->imm); 16696 16697 if (dst_reg->type == PTR_TO_STACK) 16698 insn_flags |= INSN_F_DST_REG_STACK; 16699 } 16700 16701 if (insn_flags) { 16702 err = push_jmp_history(env, this_branch, insn_flags, 0); 16703 if (err) 16704 return err; 16705 } 16706 16707 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 16708 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 16709 if (pred >= 0) { 16710 /* If we get here with a dst_reg pointer type it is because 16711 * above is_branch_taken() special cased the 0 comparison. 16712 */ 16713 if (!__is_pointer_value(false, dst_reg)) 16714 err = mark_chain_precision(env, insn->dst_reg); 16715 if (BPF_SRC(insn->code) == BPF_X && !err && 16716 !__is_pointer_value(false, src_reg)) 16717 err = mark_chain_precision(env, insn->src_reg); 16718 if (err) 16719 return err; 16720 } 16721 16722 if (pred == 1) { 16723 /* Only follow the goto, ignore fall-through. If needed, push 16724 * the fall-through branch for simulation under speculative 16725 * execution. 16726 */ 16727 if (!env->bypass_spec_v1 && 16728 !sanitize_speculative_path(env, insn, *insn_idx + 1, 16729 *insn_idx)) 16730 return -EFAULT; 16731 if (env->log.level & BPF_LOG_LEVEL) 16732 print_insn_state(env, this_branch, this_branch->curframe); 16733 *insn_idx += insn->off; 16734 return 0; 16735 } else if (pred == 0) { 16736 /* Only follow the fall-through branch, since that's where the 16737 * program will go. If needed, push the goto branch for 16738 * simulation under speculative execution. 16739 */ 16740 if (!env->bypass_spec_v1 && 16741 !sanitize_speculative_path(env, insn, 16742 *insn_idx + insn->off + 1, 16743 *insn_idx)) 16744 return -EFAULT; 16745 if (env->log.level & BPF_LOG_LEVEL) 16746 print_insn_state(env, this_branch, this_branch->curframe); 16747 return 0; 16748 } 16749 16750 /* Push scalar registers sharing same ID to jump history, 16751 * do this before creating 'other_branch', so that both 16752 * 'this_branch' and 'other_branch' share this history 16753 * if parent state is created. 16754 */ 16755 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 16756 collect_linked_regs(this_branch, src_reg->id, &linked_regs); 16757 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 16758 collect_linked_regs(this_branch, dst_reg->id, &linked_regs); 16759 if (linked_regs.cnt > 1) { 16760 err = push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs)); 16761 if (err) 16762 return err; 16763 } 16764 16765 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 16766 false); 16767 if (!other_branch) 16768 return -EFAULT; 16769 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 16770 16771 if (BPF_SRC(insn->code) == BPF_X) { 16772 err = reg_set_min_max(env, 16773 &other_branch_regs[insn->dst_reg], 16774 &other_branch_regs[insn->src_reg], 16775 dst_reg, src_reg, opcode, is_jmp32); 16776 } else /* BPF_SRC(insn->code) == BPF_K */ { 16777 /* reg_set_min_max() can mangle the fake_reg. Make a copy 16778 * so that these are two different memory locations. The 16779 * src_reg is not used beyond here in context of K. 16780 */ 16781 memcpy(&env->fake_reg[1], &env->fake_reg[0], 16782 sizeof(env->fake_reg[0])); 16783 err = reg_set_min_max(env, 16784 &other_branch_regs[insn->dst_reg], 16785 &env->fake_reg[0], 16786 dst_reg, &env->fake_reg[1], 16787 opcode, is_jmp32); 16788 } 16789 if (err) 16790 return err; 16791 16792 if (BPF_SRC(insn->code) == BPF_X && 16793 src_reg->type == SCALAR_VALUE && src_reg->id && 16794 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 16795 sync_linked_regs(this_branch, src_reg, &linked_regs); 16796 sync_linked_regs(other_branch, &other_branch_regs[insn->src_reg], &linked_regs); 16797 } 16798 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 16799 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 16800 sync_linked_regs(this_branch, dst_reg, &linked_regs); 16801 sync_linked_regs(other_branch, &other_branch_regs[insn->dst_reg], &linked_regs); 16802 } 16803 16804 /* if one pointer register is compared to another pointer 16805 * register check if PTR_MAYBE_NULL could be lifted. 16806 * E.g. register A - maybe null 16807 * register B - not null 16808 * for JNE A, B, ... - A is not null in the false branch; 16809 * for JEQ A, B, ... - A is not null in the true branch. 16810 * 16811 * Since PTR_TO_BTF_ID points to a kernel struct that does 16812 * not need to be null checked by the BPF program, i.e., 16813 * could be null even without PTR_MAYBE_NULL marking, so 16814 * only propagate nullness when neither reg is that type. 16815 */ 16816 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16817 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16818 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16819 base_type(src_reg->type) != PTR_TO_BTF_ID && 16820 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16821 eq_branch_regs = NULL; 16822 switch (opcode) { 16823 case BPF_JEQ: 16824 eq_branch_regs = other_branch_regs; 16825 break; 16826 case BPF_JNE: 16827 eq_branch_regs = regs; 16828 break; 16829 default: 16830 /* do nothing */ 16831 break; 16832 } 16833 if (eq_branch_regs) { 16834 if (type_may_be_null(src_reg->type)) 16835 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16836 else 16837 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16838 } 16839 } 16840 16841 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16842 * NOTE: these optimizations below are related with pointer comparison 16843 * which will never be JMP32. 16844 */ 16845 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 16846 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16847 type_may_be_null(dst_reg->type)) { 16848 /* Mark all identical registers in each branch as either 16849 * safe or unknown depending R == 0 or R != 0 conditional. 16850 */ 16851 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16852 opcode == BPF_JNE); 16853 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16854 opcode == BPF_JEQ); 16855 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16856 this_branch, other_branch) && 16857 is_pointer_value(env, insn->dst_reg)) { 16858 verbose(env, "R%d pointer comparison prohibited\n", 16859 insn->dst_reg); 16860 return -EACCES; 16861 } 16862 if (env->log.level & BPF_LOG_LEVEL) 16863 print_insn_state(env, this_branch, this_branch->curframe); 16864 return 0; 16865 } 16866 16867 /* verify BPF_LD_IMM64 instruction */ 16868 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16869 { 16870 struct bpf_insn_aux_data *aux = cur_aux(env); 16871 struct bpf_reg_state *regs = cur_regs(env); 16872 struct bpf_reg_state *dst_reg; 16873 struct bpf_map *map; 16874 int err; 16875 16876 if (BPF_SIZE(insn->code) != BPF_DW) { 16877 verbose(env, "invalid BPF_LD_IMM insn\n"); 16878 return -EINVAL; 16879 } 16880 if (insn->off != 0) { 16881 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 16882 return -EINVAL; 16883 } 16884 16885 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16886 if (err) 16887 return err; 16888 16889 dst_reg = ®s[insn->dst_reg]; 16890 if (insn->src_reg == 0) { 16891 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16892 16893 dst_reg->type = SCALAR_VALUE; 16894 __mark_reg_known(®s[insn->dst_reg], imm); 16895 return 0; 16896 } 16897 16898 /* All special src_reg cases are listed below. From this point onwards 16899 * we either succeed and assign a corresponding dst_reg->type after 16900 * zeroing the offset, or fail and reject the program. 16901 */ 16902 mark_reg_known_zero(env, regs, insn->dst_reg); 16903 16904 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16905 dst_reg->type = aux->btf_var.reg_type; 16906 switch (base_type(dst_reg->type)) { 16907 case PTR_TO_MEM: 16908 dst_reg->mem_size = aux->btf_var.mem_size; 16909 break; 16910 case PTR_TO_BTF_ID: 16911 dst_reg->btf = aux->btf_var.btf; 16912 dst_reg->btf_id = aux->btf_var.btf_id; 16913 break; 16914 default: 16915 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 16916 return -EFAULT; 16917 } 16918 return 0; 16919 } 16920 16921 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16922 struct bpf_prog_aux *aux = env->prog->aux; 16923 u32 subprogno = find_subprog(env, 16924 env->insn_idx + insn->imm + 1); 16925 16926 if (!aux->func_info) { 16927 verbose(env, "missing btf func_info\n"); 16928 return -EINVAL; 16929 } 16930 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16931 verbose(env, "callback function not static\n"); 16932 return -EINVAL; 16933 } 16934 16935 dst_reg->type = PTR_TO_FUNC; 16936 dst_reg->subprogno = subprogno; 16937 return 0; 16938 } 16939 16940 map = env->used_maps[aux->map_index]; 16941 dst_reg->map_ptr = map; 16942 16943 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16944 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16945 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16946 __mark_reg_unknown(env, dst_reg); 16947 return 0; 16948 } 16949 dst_reg->type = PTR_TO_MAP_VALUE; 16950 dst_reg->off = aux->map_off; 16951 WARN_ON_ONCE(map->max_entries != 1); 16952 /* We want reg->id to be same (0) as map_value is not distinct */ 16953 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16954 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16955 dst_reg->type = CONST_PTR_TO_MAP; 16956 } else { 16957 verifier_bug(env, "unexpected src reg value for ldimm64"); 16958 return -EFAULT; 16959 } 16960 16961 return 0; 16962 } 16963 16964 static bool may_access_skb(enum bpf_prog_type type) 16965 { 16966 switch (type) { 16967 case BPF_PROG_TYPE_SOCKET_FILTER: 16968 case BPF_PROG_TYPE_SCHED_CLS: 16969 case BPF_PROG_TYPE_SCHED_ACT: 16970 return true; 16971 default: 16972 return false; 16973 } 16974 } 16975 16976 /* verify safety of LD_ABS|LD_IND instructions: 16977 * - they can only appear in the programs where ctx == skb 16978 * - since they are wrappers of function calls, they scratch R1-R5 registers, 16979 * preserve R6-R9, and store return value into R0 16980 * 16981 * Implicit input: 16982 * ctx == skb == R6 == CTX 16983 * 16984 * Explicit input: 16985 * SRC == any register 16986 * IMM == 32-bit immediate 16987 * 16988 * Output: 16989 * R0 - 8/16/32-bit skb data converted to cpu endianness 16990 */ 16991 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 16992 { 16993 struct bpf_reg_state *regs = cur_regs(env); 16994 static const int ctx_reg = BPF_REG_6; 16995 u8 mode = BPF_MODE(insn->code); 16996 int i, err; 16997 16998 if (!may_access_skb(resolve_prog_type(env->prog))) { 16999 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 17000 return -EINVAL; 17001 } 17002 17003 if (!env->ops->gen_ld_abs) { 17004 verifier_bug(env, "gen_ld_abs is null"); 17005 return -EFAULT; 17006 } 17007 17008 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 17009 BPF_SIZE(insn->code) == BPF_DW || 17010 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 17011 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 17012 return -EINVAL; 17013 } 17014 17015 /* check whether implicit source operand (register R6) is readable */ 17016 err = check_reg_arg(env, ctx_reg, SRC_OP); 17017 if (err) 17018 return err; 17019 17020 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 17021 * gen_ld_abs() may terminate the program at runtime, leading to 17022 * reference leak. 17023 */ 17024 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 17025 if (err) 17026 return err; 17027 17028 if (regs[ctx_reg].type != PTR_TO_CTX) { 17029 verbose(env, 17030 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 17031 return -EINVAL; 17032 } 17033 17034 if (mode == BPF_IND) { 17035 /* check explicit source operand */ 17036 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17037 if (err) 17038 return err; 17039 } 17040 17041 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 17042 if (err < 0) 17043 return err; 17044 17045 /* reset caller saved regs to unreadable */ 17046 for (i = 0; i < CALLER_SAVED_REGS; i++) { 17047 mark_reg_not_init(env, regs, caller_saved[i]); 17048 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 17049 } 17050 17051 /* mark destination R0 register as readable, since it contains 17052 * the value fetched from the packet. 17053 * Already marked as written above. 17054 */ 17055 mark_reg_unknown(env, regs, BPF_REG_0); 17056 /* ld_abs load up to 32-bit skb data. */ 17057 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 17058 return 0; 17059 } 17060 17061 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 17062 { 17063 const char *exit_ctx = "At program exit"; 17064 struct tnum enforce_attach_type_range = tnum_unknown; 17065 const struct bpf_prog *prog = env->prog; 17066 struct bpf_reg_state *reg = reg_state(env, regno); 17067 struct bpf_retval_range range = retval_range(0, 1); 17068 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 17069 int err; 17070 struct bpf_func_state *frame = env->cur_state->frame[0]; 17071 const bool is_subprog = frame->subprogno; 17072 bool return_32bit = false; 17073 const struct btf_type *reg_type, *ret_type = NULL; 17074 17075 /* LSM and struct_ops func-ptr's return type could be "void" */ 17076 if (!is_subprog || frame->in_exception_callback_fn) { 17077 switch (prog_type) { 17078 case BPF_PROG_TYPE_LSM: 17079 if (prog->expected_attach_type == BPF_LSM_CGROUP) 17080 /* See below, can be 0 or 0-1 depending on hook. */ 17081 break; 17082 if (!prog->aux->attach_func_proto->type) 17083 return 0; 17084 break; 17085 case BPF_PROG_TYPE_STRUCT_OPS: 17086 if (!prog->aux->attach_func_proto->type) 17087 return 0; 17088 17089 if (frame->in_exception_callback_fn) 17090 break; 17091 17092 /* Allow a struct_ops program to return a referenced kptr if it 17093 * matches the operator's return type and is in its unmodified 17094 * form. A scalar zero (i.e., a null pointer) is also allowed. 17095 */ 17096 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 17097 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 17098 prog->aux->attach_func_proto->type, 17099 NULL); 17100 if (ret_type && ret_type == reg_type && reg->ref_obj_id) 17101 return __check_ptr_off_reg(env, reg, regno, false); 17102 break; 17103 default: 17104 break; 17105 } 17106 } 17107 17108 /* eBPF calling convention is such that R0 is used 17109 * to return the value from eBPF program. 17110 * Make sure that it's readable at this time 17111 * of bpf_exit, which means that program wrote 17112 * something into it earlier 17113 */ 17114 err = check_reg_arg(env, regno, SRC_OP); 17115 if (err) 17116 return err; 17117 17118 if (is_pointer_value(env, regno)) { 17119 verbose(env, "R%d leaks addr as return value\n", regno); 17120 return -EACCES; 17121 } 17122 17123 if (frame->in_async_callback_fn) { 17124 /* enforce return zero from async callbacks like timer */ 17125 exit_ctx = "At async callback return"; 17126 range = retval_range(0, 0); 17127 goto enforce_retval; 17128 } 17129 17130 if (is_subprog && !frame->in_exception_callback_fn) { 17131 if (reg->type != SCALAR_VALUE) { 17132 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 17133 regno, reg_type_str(env, reg->type)); 17134 return -EINVAL; 17135 } 17136 return 0; 17137 } 17138 17139 switch (prog_type) { 17140 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 17141 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 17142 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 17143 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 17144 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 17145 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 17146 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 17147 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 17148 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 17149 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 17150 range = retval_range(1, 1); 17151 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 17152 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 17153 range = retval_range(0, 3); 17154 break; 17155 case BPF_PROG_TYPE_CGROUP_SKB: 17156 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 17157 range = retval_range(0, 3); 17158 enforce_attach_type_range = tnum_range(2, 3); 17159 } 17160 break; 17161 case BPF_PROG_TYPE_CGROUP_SOCK: 17162 case BPF_PROG_TYPE_SOCK_OPS: 17163 case BPF_PROG_TYPE_CGROUP_DEVICE: 17164 case BPF_PROG_TYPE_CGROUP_SYSCTL: 17165 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 17166 break; 17167 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17168 if (!env->prog->aux->attach_btf_id) 17169 return 0; 17170 range = retval_range(0, 0); 17171 break; 17172 case BPF_PROG_TYPE_TRACING: 17173 switch (env->prog->expected_attach_type) { 17174 case BPF_TRACE_FENTRY: 17175 case BPF_TRACE_FEXIT: 17176 range = retval_range(0, 0); 17177 break; 17178 case BPF_TRACE_RAW_TP: 17179 case BPF_MODIFY_RETURN: 17180 return 0; 17181 case BPF_TRACE_ITER: 17182 break; 17183 default: 17184 return -ENOTSUPP; 17185 } 17186 break; 17187 case BPF_PROG_TYPE_KPROBE: 17188 switch (env->prog->expected_attach_type) { 17189 case BPF_TRACE_KPROBE_SESSION: 17190 case BPF_TRACE_UPROBE_SESSION: 17191 range = retval_range(0, 1); 17192 break; 17193 default: 17194 return 0; 17195 } 17196 break; 17197 case BPF_PROG_TYPE_SK_LOOKUP: 17198 range = retval_range(SK_DROP, SK_PASS); 17199 break; 17200 17201 case BPF_PROG_TYPE_LSM: 17202 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 17203 /* no range found, any return value is allowed */ 17204 if (!get_func_retval_range(env->prog, &range)) 17205 return 0; 17206 /* no restricted range, any return value is allowed */ 17207 if (range.minval == S32_MIN && range.maxval == S32_MAX) 17208 return 0; 17209 return_32bit = true; 17210 } else if (!env->prog->aux->attach_func_proto->type) { 17211 /* Make sure programs that attach to void 17212 * hooks don't try to modify return value. 17213 */ 17214 range = retval_range(1, 1); 17215 } 17216 break; 17217 17218 case BPF_PROG_TYPE_NETFILTER: 17219 range = retval_range(NF_DROP, NF_ACCEPT); 17220 break; 17221 case BPF_PROG_TYPE_STRUCT_OPS: 17222 if (!ret_type) 17223 return 0; 17224 range = retval_range(0, 0); 17225 break; 17226 case BPF_PROG_TYPE_EXT: 17227 /* freplace program can return anything as its return value 17228 * depends on the to-be-replaced kernel func or bpf program. 17229 */ 17230 default: 17231 return 0; 17232 } 17233 17234 enforce_retval: 17235 if (reg->type != SCALAR_VALUE) { 17236 verbose(env, "%s the register R%d is not a known value (%s)\n", 17237 exit_ctx, regno, reg_type_str(env, reg->type)); 17238 return -EINVAL; 17239 } 17240 17241 err = mark_chain_precision(env, regno); 17242 if (err) 17243 return err; 17244 17245 if (!retval_range_within(range, reg, return_32bit)) { 17246 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 17247 if (!is_subprog && 17248 prog->expected_attach_type == BPF_LSM_CGROUP && 17249 prog_type == BPF_PROG_TYPE_LSM && 17250 !prog->aux->attach_func_proto->type) 17251 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 17252 return -EINVAL; 17253 } 17254 17255 if (!tnum_is_unknown(enforce_attach_type_range) && 17256 tnum_in(enforce_attach_type_range, reg->var_off)) 17257 env->prog->enforce_expected_attach_type = 1; 17258 return 0; 17259 } 17260 17261 static void mark_subprog_changes_pkt_data(struct bpf_verifier_env *env, int off) 17262 { 17263 struct bpf_subprog_info *subprog; 17264 17265 subprog = find_containing_subprog(env, off); 17266 subprog->changes_pkt_data = true; 17267 } 17268 17269 static void mark_subprog_might_sleep(struct bpf_verifier_env *env, int off) 17270 { 17271 struct bpf_subprog_info *subprog; 17272 17273 subprog = find_containing_subprog(env, off); 17274 subprog->might_sleep = true; 17275 } 17276 17277 /* 't' is an index of a call-site. 17278 * 'w' is a callee entry point. 17279 * Eventually this function would be called when env->cfg.insn_state[w] == EXPLORED. 17280 * Rely on DFS traversal order and absence of recursive calls to guarantee that 17281 * callee's change_pkt_data marks would be correct at that moment. 17282 */ 17283 static void merge_callee_effects(struct bpf_verifier_env *env, int t, int w) 17284 { 17285 struct bpf_subprog_info *caller, *callee; 17286 17287 caller = find_containing_subprog(env, t); 17288 callee = find_containing_subprog(env, w); 17289 caller->changes_pkt_data |= callee->changes_pkt_data; 17290 caller->might_sleep |= callee->might_sleep; 17291 } 17292 17293 /* non-recursive DFS pseudo code 17294 * 1 procedure DFS-iterative(G,v): 17295 * 2 label v as discovered 17296 * 3 let S be a stack 17297 * 4 S.push(v) 17298 * 5 while S is not empty 17299 * 6 t <- S.peek() 17300 * 7 if t is what we're looking for: 17301 * 8 return t 17302 * 9 for all edges e in G.adjacentEdges(t) do 17303 * 10 if edge e is already labelled 17304 * 11 continue with the next edge 17305 * 12 w <- G.adjacentVertex(t,e) 17306 * 13 if vertex w is not discovered and not explored 17307 * 14 label e as tree-edge 17308 * 15 label w as discovered 17309 * 16 S.push(w) 17310 * 17 continue at 5 17311 * 18 else if vertex w is discovered 17312 * 19 label e as back-edge 17313 * 20 else 17314 * 21 // vertex w is explored 17315 * 22 label e as forward- or cross-edge 17316 * 23 label t as explored 17317 * 24 S.pop() 17318 * 17319 * convention: 17320 * 0x10 - discovered 17321 * 0x11 - discovered and fall-through edge labelled 17322 * 0x12 - discovered and fall-through and branch edges labelled 17323 * 0x20 - explored 17324 */ 17325 17326 enum { 17327 DISCOVERED = 0x10, 17328 EXPLORED = 0x20, 17329 FALLTHROUGH = 1, 17330 BRANCH = 2, 17331 }; 17332 17333 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 17334 { 17335 env->insn_aux_data[idx].prune_point = true; 17336 } 17337 17338 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 17339 { 17340 return env->insn_aux_data[insn_idx].prune_point; 17341 } 17342 17343 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 17344 { 17345 env->insn_aux_data[idx].force_checkpoint = true; 17346 } 17347 17348 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 17349 { 17350 return env->insn_aux_data[insn_idx].force_checkpoint; 17351 } 17352 17353 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 17354 { 17355 env->insn_aux_data[idx].calls_callback = true; 17356 } 17357 17358 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 17359 { 17360 return env->insn_aux_data[insn_idx].calls_callback; 17361 } 17362 17363 enum { 17364 DONE_EXPLORING = 0, 17365 KEEP_EXPLORING = 1, 17366 }; 17367 17368 /* t, w, e - match pseudo-code above: 17369 * t - index of current instruction 17370 * w - next instruction 17371 * e - edge 17372 */ 17373 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 17374 { 17375 int *insn_stack = env->cfg.insn_stack; 17376 int *insn_state = env->cfg.insn_state; 17377 17378 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 17379 return DONE_EXPLORING; 17380 17381 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 17382 return DONE_EXPLORING; 17383 17384 if (w < 0 || w >= env->prog->len) { 17385 verbose_linfo(env, t, "%d: ", t); 17386 verbose(env, "jump out of range from insn %d to %d\n", t, w); 17387 return -EINVAL; 17388 } 17389 17390 if (e == BRANCH) { 17391 /* mark branch target for state pruning */ 17392 mark_prune_point(env, w); 17393 mark_jmp_point(env, w); 17394 } 17395 17396 if (insn_state[w] == 0) { 17397 /* tree-edge */ 17398 insn_state[t] = DISCOVERED | e; 17399 insn_state[w] = DISCOVERED; 17400 if (env->cfg.cur_stack >= env->prog->len) 17401 return -E2BIG; 17402 insn_stack[env->cfg.cur_stack++] = w; 17403 return KEEP_EXPLORING; 17404 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 17405 if (env->bpf_capable) 17406 return DONE_EXPLORING; 17407 verbose_linfo(env, t, "%d: ", t); 17408 verbose_linfo(env, w, "%d: ", w); 17409 verbose(env, "back-edge from insn %d to %d\n", t, w); 17410 return -EINVAL; 17411 } else if (insn_state[w] == EXPLORED) { 17412 /* forward- or cross-edge */ 17413 insn_state[t] = DISCOVERED | e; 17414 } else { 17415 verifier_bug(env, "insn state internal bug"); 17416 return -EFAULT; 17417 } 17418 return DONE_EXPLORING; 17419 } 17420 17421 static int visit_func_call_insn(int t, struct bpf_insn *insns, 17422 struct bpf_verifier_env *env, 17423 bool visit_callee) 17424 { 17425 int ret, insn_sz; 17426 int w; 17427 17428 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 17429 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 17430 if (ret) 17431 return ret; 17432 17433 mark_prune_point(env, t + insn_sz); 17434 /* when we exit from subprog, we need to record non-linear history */ 17435 mark_jmp_point(env, t + insn_sz); 17436 17437 if (visit_callee) { 17438 w = t + insns[t].imm + 1; 17439 mark_prune_point(env, t); 17440 merge_callee_effects(env, t, w); 17441 ret = push_insn(t, w, BRANCH, env); 17442 } 17443 return ret; 17444 } 17445 17446 /* Bitmask with 1s for all caller saved registers */ 17447 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 17448 17449 /* True if do_misc_fixups() replaces calls to helper number 'imm', 17450 * replacement patch is presumed to follow bpf_fastcall contract 17451 * (see mark_fastcall_pattern_for_call() below). 17452 */ 17453 static bool verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 17454 { 17455 switch (imm) { 17456 #ifdef CONFIG_X86_64 17457 case BPF_FUNC_get_smp_processor_id: 17458 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 17459 #endif 17460 default: 17461 return false; 17462 } 17463 } 17464 17465 struct call_summary { 17466 u8 num_params; 17467 bool is_void; 17468 bool fastcall; 17469 }; 17470 17471 /* If @call is a kfunc or helper call, fills @cs and returns true, 17472 * otherwise returns false. 17473 */ 17474 static bool get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 17475 struct call_summary *cs) 17476 { 17477 struct bpf_kfunc_call_arg_meta meta; 17478 const struct bpf_func_proto *fn; 17479 int i; 17480 17481 if (bpf_helper_call(call)) { 17482 17483 if (get_helper_proto(env, call->imm, &fn) < 0) 17484 /* error would be reported later */ 17485 return false; 17486 cs->fastcall = fn->allow_fastcall && 17487 (verifier_inlines_helper_call(env, call->imm) || 17488 bpf_jit_inlines_helper_call(call->imm)); 17489 cs->is_void = fn->ret_type == RET_VOID; 17490 cs->num_params = 0; 17491 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 17492 if (fn->arg_type[i] == ARG_DONTCARE) 17493 break; 17494 cs->num_params++; 17495 } 17496 return true; 17497 } 17498 17499 if (bpf_pseudo_kfunc_call(call)) { 17500 int err; 17501 17502 err = fetch_kfunc_meta(env, call, &meta, NULL); 17503 if (err < 0) 17504 /* error would be reported later */ 17505 return false; 17506 cs->num_params = btf_type_vlen(meta.func_proto); 17507 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 17508 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 17509 return true; 17510 } 17511 17512 return false; 17513 } 17514 17515 /* LLVM define a bpf_fastcall function attribute. 17516 * This attribute means that function scratches only some of 17517 * the caller saved registers defined by ABI. 17518 * For BPF the set of such registers could be defined as follows: 17519 * - R0 is scratched only if function is non-void; 17520 * - R1-R5 are scratched only if corresponding parameter type is defined 17521 * in the function prototype. 17522 * 17523 * The contract between kernel and clang allows to simultaneously use 17524 * such functions and maintain backwards compatibility with old 17525 * kernels that don't understand bpf_fastcall calls: 17526 * 17527 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 17528 * registers are not scratched by the call; 17529 * 17530 * - as a post-processing step, clang visits each bpf_fastcall call and adds 17531 * spill/fill for every live r0-r5; 17532 * 17533 * - stack offsets used for the spill/fill are allocated as lowest 17534 * stack offsets in whole function and are not used for any other 17535 * purposes; 17536 * 17537 * - when kernel loads a program, it looks for such patterns 17538 * (bpf_fastcall function surrounded by spills/fills) and checks if 17539 * spill/fill stack offsets are used exclusively in fastcall patterns; 17540 * 17541 * - if so, and if verifier or current JIT inlines the call to the 17542 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 17543 * spill/fill pairs; 17544 * 17545 * - when old kernel loads a program, presence of spill/fill pairs 17546 * keeps BPF program valid, albeit slightly less efficient. 17547 * 17548 * For example: 17549 * 17550 * r1 = 1; 17551 * r2 = 2; 17552 * *(u64 *)(r10 - 8) = r1; r1 = 1; 17553 * *(u64 *)(r10 - 16) = r2; r2 = 2; 17554 * call %[to_be_inlined] --> call %[to_be_inlined] 17555 * r2 = *(u64 *)(r10 - 16); r0 = r1; 17556 * r1 = *(u64 *)(r10 - 8); r0 += r2; 17557 * r0 = r1; exit; 17558 * r0 += r2; 17559 * exit; 17560 * 17561 * The purpose of mark_fastcall_pattern_for_call is to: 17562 * - look for such patterns; 17563 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 17564 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 17565 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 17566 * at which bpf_fastcall spill/fill stack slots start; 17567 * - update env->subprog_info[*]->keep_fastcall_stack. 17568 * 17569 * The .fastcall_pattern and .fastcall_stack_off are used by 17570 * check_fastcall_stack_contract() to check if every stack access to 17571 * fastcall spill/fill stack slot originates from spill/fill 17572 * instructions, members of fastcall patterns. 17573 * 17574 * If such condition holds true for a subprogram, fastcall patterns could 17575 * be rewritten by remove_fastcall_spills_fills(). 17576 * Otherwise bpf_fastcall patterns are not changed in the subprogram 17577 * (code, presumably, generated by an older clang version). 17578 * 17579 * For example, it is *not* safe to remove spill/fill below: 17580 * 17581 * r1 = 1; 17582 * *(u64 *)(r10 - 8) = r1; r1 = 1; 17583 * call %[to_be_inlined] --> call %[to_be_inlined] 17584 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 17585 * r0 = *(u64 *)(r10 - 8); r0 += r1; 17586 * r0 += r1; exit; 17587 * exit; 17588 */ 17589 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 17590 struct bpf_subprog_info *subprog, 17591 int insn_idx, s16 lowest_off) 17592 { 17593 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 17594 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 17595 u32 clobbered_regs_mask; 17596 struct call_summary cs; 17597 u32 expected_regs_mask; 17598 s16 off; 17599 int i; 17600 17601 if (!get_call_summary(env, call, &cs)) 17602 return; 17603 17604 /* A bitmask specifying which caller saved registers are clobbered 17605 * by a call to a helper/kfunc *as if* this helper/kfunc follows 17606 * bpf_fastcall contract: 17607 * - includes R0 if function is non-void; 17608 * - includes R1-R5 if corresponding parameter has is described 17609 * in the function prototype. 17610 */ 17611 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 17612 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 17613 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 17614 17615 /* match pairs of form: 17616 * 17617 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 17618 * ... 17619 * call %[to_be_inlined] 17620 * ... 17621 * rX = *(u64 *)(r10 - Y) 17622 */ 17623 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 17624 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 17625 break; 17626 stx = &insns[insn_idx - i]; 17627 ldx = &insns[insn_idx + i]; 17628 /* must be a stack spill/fill pair */ 17629 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 17630 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 17631 stx->dst_reg != BPF_REG_10 || 17632 ldx->src_reg != BPF_REG_10) 17633 break; 17634 /* must be a spill/fill for the same reg */ 17635 if (stx->src_reg != ldx->dst_reg) 17636 break; 17637 /* must be one of the previously unseen registers */ 17638 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 17639 break; 17640 /* must be a spill/fill for the same expected offset, 17641 * no need to check offset alignment, BPF_DW stack access 17642 * is always 8-byte aligned. 17643 */ 17644 if (stx->off != off || ldx->off != off) 17645 break; 17646 expected_regs_mask &= ~BIT(stx->src_reg); 17647 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 17648 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 17649 } 17650 if (i == 1) 17651 return; 17652 17653 /* Conditionally set 'fastcall_spills_num' to allow forward 17654 * compatibility when more helper functions are marked as 17655 * bpf_fastcall at compile time than current kernel supports, e.g: 17656 * 17657 * 1: *(u64 *)(r10 - 8) = r1 17658 * 2: call A ;; assume A is bpf_fastcall for current kernel 17659 * 3: r1 = *(u64 *)(r10 - 8) 17660 * 4: *(u64 *)(r10 - 8) = r1 17661 * 5: call B ;; assume B is not bpf_fastcall for current kernel 17662 * 6: r1 = *(u64 *)(r10 - 8) 17663 * 17664 * There is no need to block bpf_fastcall rewrite for such program. 17665 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 17666 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 17667 * does not remove spill/fill pair {4,6}. 17668 */ 17669 if (cs.fastcall) 17670 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 17671 else 17672 subprog->keep_fastcall_stack = 1; 17673 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 17674 } 17675 17676 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 17677 { 17678 struct bpf_subprog_info *subprog = env->subprog_info; 17679 struct bpf_insn *insn; 17680 s16 lowest_off; 17681 int s, i; 17682 17683 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 17684 /* find lowest stack spill offset used in this subprog */ 17685 lowest_off = 0; 17686 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 17687 insn = env->prog->insnsi + i; 17688 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 17689 insn->dst_reg != BPF_REG_10) 17690 continue; 17691 lowest_off = min(lowest_off, insn->off); 17692 } 17693 /* use this offset to find fastcall patterns */ 17694 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 17695 insn = env->prog->insnsi + i; 17696 if (insn->code != (BPF_JMP | BPF_CALL)) 17697 continue; 17698 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 17699 } 17700 } 17701 return 0; 17702 } 17703 17704 /* Visits the instruction at index t and returns one of the following: 17705 * < 0 - an error occurred 17706 * DONE_EXPLORING - the instruction was fully explored 17707 * KEEP_EXPLORING - there is still work to be done before it is fully explored 17708 */ 17709 static int visit_insn(int t, struct bpf_verifier_env *env) 17710 { 17711 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 17712 int ret, off, insn_sz; 17713 17714 if (bpf_pseudo_func(insn)) 17715 return visit_func_call_insn(t, insns, env, true); 17716 17717 /* All non-branch instructions have a single fall-through edge. */ 17718 if (BPF_CLASS(insn->code) != BPF_JMP && 17719 BPF_CLASS(insn->code) != BPF_JMP32) { 17720 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 17721 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 17722 } 17723 17724 switch (BPF_OP(insn->code)) { 17725 case BPF_EXIT: 17726 return DONE_EXPLORING; 17727 17728 case BPF_CALL: 17729 if (is_async_callback_calling_insn(insn)) 17730 /* Mark this call insn as a prune point to trigger 17731 * is_state_visited() check before call itself is 17732 * processed by __check_func_call(). Otherwise new 17733 * async state will be pushed for further exploration. 17734 */ 17735 mark_prune_point(env, t); 17736 /* For functions that invoke callbacks it is not known how many times 17737 * callback would be called. Verifier models callback calling functions 17738 * by repeatedly visiting callback bodies and returning to origin call 17739 * instruction. 17740 * In order to stop such iteration verifier needs to identify when a 17741 * state identical some state from a previous iteration is reached. 17742 * Check below forces creation of checkpoint before callback calling 17743 * instruction to allow search for such identical states. 17744 */ 17745 if (is_sync_callback_calling_insn(insn)) { 17746 mark_calls_callback(env, t); 17747 mark_force_checkpoint(env, t); 17748 mark_prune_point(env, t); 17749 mark_jmp_point(env, t); 17750 } 17751 if (bpf_helper_call(insn)) { 17752 const struct bpf_func_proto *fp; 17753 17754 ret = get_helper_proto(env, insn->imm, &fp); 17755 /* If called in a non-sleepable context program will be 17756 * rejected anyway, so we should end up with precise 17757 * sleepable marks on subprogs, except for dead code 17758 * elimination. 17759 */ 17760 if (ret == 0 && fp->might_sleep) 17761 mark_subprog_might_sleep(env, t); 17762 if (bpf_helper_changes_pkt_data(insn->imm)) 17763 mark_subprog_changes_pkt_data(env, t); 17764 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17765 struct bpf_kfunc_call_arg_meta meta; 17766 17767 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 17768 if (ret == 0 && is_iter_next_kfunc(&meta)) { 17769 mark_prune_point(env, t); 17770 /* Checking and saving state checkpoints at iter_next() call 17771 * is crucial for fast convergence of open-coded iterator loop 17772 * logic, so we need to force it. If we don't do that, 17773 * is_state_visited() might skip saving a checkpoint, causing 17774 * unnecessarily long sequence of not checkpointed 17775 * instructions and jumps, leading to exhaustion of jump 17776 * history buffer, and potentially other undesired outcomes. 17777 * It is expected that with correct open-coded iterators 17778 * convergence will happen quickly, so we don't run a risk of 17779 * exhausting memory. 17780 */ 17781 mark_force_checkpoint(env, t); 17782 } 17783 /* Same as helpers, if called in a non-sleepable context 17784 * program will be rejected anyway, so we should end up 17785 * with precise sleepable marks on subprogs, except for 17786 * dead code elimination. 17787 */ 17788 if (ret == 0 && is_kfunc_sleepable(&meta)) 17789 mark_subprog_might_sleep(env, t); 17790 } 17791 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 17792 17793 case BPF_JA: 17794 if (BPF_SRC(insn->code) != BPF_K) 17795 return -EINVAL; 17796 17797 if (BPF_CLASS(insn->code) == BPF_JMP) 17798 off = insn->off; 17799 else 17800 off = insn->imm; 17801 17802 /* unconditional jump with single edge */ 17803 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 17804 if (ret) 17805 return ret; 17806 17807 mark_prune_point(env, t + off + 1); 17808 mark_jmp_point(env, t + off + 1); 17809 17810 return ret; 17811 17812 default: 17813 /* conditional jump with two edges */ 17814 mark_prune_point(env, t); 17815 if (is_may_goto_insn(insn)) 17816 mark_force_checkpoint(env, t); 17817 17818 ret = push_insn(t, t + 1, FALLTHROUGH, env); 17819 if (ret) 17820 return ret; 17821 17822 return push_insn(t, t + insn->off + 1, BRANCH, env); 17823 } 17824 } 17825 17826 /* non-recursive depth-first-search to detect loops in BPF program 17827 * loop == back-edge in directed graph 17828 */ 17829 static int check_cfg(struct bpf_verifier_env *env) 17830 { 17831 int insn_cnt = env->prog->len; 17832 int *insn_stack, *insn_state, *insn_postorder; 17833 int ex_insn_beg, i, ret = 0; 17834 17835 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 17836 if (!insn_state) 17837 return -ENOMEM; 17838 17839 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 17840 if (!insn_stack) { 17841 kvfree(insn_state); 17842 return -ENOMEM; 17843 } 17844 17845 insn_postorder = env->cfg.insn_postorder = 17846 kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 17847 if (!insn_postorder) { 17848 kvfree(insn_state); 17849 kvfree(insn_stack); 17850 return -ENOMEM; 17851 } 17852 17853 ex_insn_beg = env->exception_callback_subprog 17854 ? env->subprog_info[env->exception_callback_subprog].start 17855 : 0; 17856 17857 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 17858 insn_stack[0] = 0; /* 0 is the first instruction */ 17859 env->cfg.cur_stack = 1; 17860 17861 walk_cfg: 17862 while (env->cfg.cur_stack > 0) { 17863 int t = insn_stack[env->cfg.cur_stack - 1]; 17864 17865 ret = visit_insn(t, env); 17866 switch (ret) { 17867 case DONE_EXPLORING: 17868 insn_state[t] = EXPLORED; 17869 env->cfg.cur_stack--; 17870 insn_postorder[env->cfg.cur_postorder++] = t; 17871 break; 17872 case KEEP_EXPLORING: 17873 break; 17874 default: 17875 if (ret > 0) { 17876 verifier_bug(env, "visit_insn internal bug"); 17877 ret = -EFAULT; 17878 } 17879 goto err_free; 17880 } 17881 } 17882 17883 if (env->cfg.cur_stack < 0) { 17884 verifier_bug(env, "pop stack internal bug"); 17885 ret = -EFAULT; 17886 goto err_free; 17887 } 17888 17889 if (ex_insn_beg && insn_state[ex_insn_beg] != EXPLORED) { 17890 insn_state[ex_insn_beg] = DISCOVERED; 17891 insn_stack[0] = ex_insn_beg; 17892 env->cfg.cur_stack = 1; 17893 goto walk_cfg; 17894 } 17895 17896 for (i = 0; i < insn_cnt; i++) { 17897 struct bpf_insn *insn = &env->prog->insnsi[i]; 17898 17899 if (insn_state[i] != EXPLORED) { 17900 verbose(env, "unreachable insn %d\n", i); 17901 ret = -EINVAL; 17902 goto err_free; 17903 } 17904 if (bpf_is_ldimm64(insn)) { 17905 if (insn_state[i + 1] != 0) { 17906 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 17907 ret = -EINVAL; 17908 goto err_free; 17909 } 17910 i++; /* skip second half of ldimm64 */ 17911 } 17912 } 17913 ret = 0; /* cfg looks good */ 17914 env->prog->aux->changes_pkt_data = env->subprog_info[0].changes_pkt_data; 17915 env->prog->aux->might_sleep = env->subprog_info[0].might_sleep; 17916 17917 err_free: 17918 kvfree(insn_state); 17919 kvfree(insn_stack); 17920 env->cfg.insn_state = env->cfg.insn_stack = NULL; 17921 return ret; 17922 } 17923 17924 static int check_abnormal_return(struct bpf_verifier_env *env) 17925 { 17926 int i; 17927 17928 for (i = 1; i < env->subprog_cnt; i++) { 17929 if (env->subprog_info[i].has_ld_abs) { 17930 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 17931 return -EINVAL; 17932 } 17933 if (env->subprog_info[i].has_tail_call) { 17934 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 17935 return -EINVAL; 17936 } 17937 } 17938 return 0; 17939 } 17940 17941 /* The minimum supported BTF func info size */ 17942 #define MIN_BPF_FUNCINFO_SIZE 8 17943 #define MAX_FUNCINFO_REC_SIZE 252 17944 17945 static int check_btf_func_early(struct bpf_verifier_env *env, 17946 const union bpf_attr *attr, 17947 bpfptr_t uattr) 17948 { 17949 u32 krec_size = sizeof(struct bpf_func_info); 17950 const struct btf_type *type, *func_proto; 17951 u32 i, nfuncs, urec_size, min_size; 17952 struct bpf_func_info *krecord; 17953 struct bpf_prog *prog; 17954 const struct btf *btf; 17955 u32 prev_offset = 0; 17956 bpfptr_t urecord; 17957 int ret = -ENOMEM; 17958 17959 nfuncs = attr->func_info_cnt; 17960 if (!nfuncs) { 17961 if (check_abnormal_return(env)) 17962 return -EINVAL; 17963 return 0; 17964 } 17965 17966 urec_size = attr->func_info_rec_size; 17967 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 17968 urec_size > MAX_FUNCINFO_REC_SIZE || 17969 urec_size % sizeof(u32)) { 17970 verbose(env, "invalid func info rec size %u\n", urec_size); 17971 return -EINVAL; 17972 } 17973 17974 prog = env->prog; 17975 btf = prog->aux->btf; 17976 17977 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 17978 min_size = min_t(u32, krec_size, urec_size); 17979 17980 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL_ACCOUNT | __GFP_NOWARN); 17981 if (!krecord) 17982 return -ENOMEM; 17983 17984 for (i = 0; i < nfuncs; i++) { 17985 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 17986 if (ret) { 17987 if (ret == -E2BIG) { 17988 verbose(env, "nonzero tailing record in func info"); 17989 /* set the size kernel expects so loader can zero 17990 * out the rest of the record. 17991 */ 17992 if (copy_to_bpfptr_offset(uattr, 17993 offsetof(union bpf_attr, func_info_rec_size), 17994 &min_size, sizeof(min_size))) 17995 ret = -EFAULT; 17996 } 17997 goto err_free; 17998 } 17999 18000 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 18001 ret = -EFAULT; 18002 goto err_free; 18003 } 18004 18005 /* check insn_off */ 18006 ret = -EINVAL; 18007 if (i == 0) { 18008 if (krecord[i].insn_off) { 18009 verbose(env, 18010 "nonzero insn_off %u for the first func info record", 18011 krecord[i].insn_off); 18012 goto err_free; 18013 } 18014 } else if (krecord[i].insn_off <= prev_offset) { 18015 verbose(env, 18016 "same or smaller insn offset (%u) than previous func info record (%u)", 18017 krecord[i].insn_off, prev_offset); 18018 goto err_free; 18019 } 18020 18021 /* check type_id */ 18022 type = btf_type_by_id(btf, krecord[i].type_id); 18023 if (!type || !btf_type_is_func(type)) { 18024 verbose(env, "invalid type id %d in func info", 18025 krecord[i].type_id); 18026 goto err_free; 18027 } 18028 18029 func_proto = btf_type_by_id(btf, type->type); 18030 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 18031 /* btf_func_check() already verified it during BTF load */ 18032 goto err_free; 18033 18034 prev_offset = krecord[i].insn_off; 18035 bpfptr_add(&urecord, urec_size); 18036 } 18037 18038 prog->aux->func_info = krecord; 18039 prog->aux->func_info_cnt = nfuncs; 18040 return 0; 18041 18042 err_free: 18043 kvfree(krecord); 18044 return ret; 18045 } 18046 18047 static int check_btf_func(struct bpf_verifier_env *env, 18048 const union bpf_attr *attr, 18049 bpfptr_t uattr) 18050 { 18051 const struct btf_type *type, *func_proto, *ret_type; 18052 u32 i, nfuncs, urec_size; 18053 struct bpf_func_info *krecord; 18054 struct bpf_func_info_aux *info_aux = NULL; 18055 struct bpf_prog *prog; 18056 const struct btf *btf; 18057 bpfptr_t urecord; 18058 bool scalar_return; 18059 int ret = -ENOMEM; 18060 18061 nfuncs = attr->func_info_cnt; 18062 if (!nfuncs) { 18063 if (check_abnormal_return(env)) 18064 return -EINVAL; 18065 return 0; 18066 } 18067 if (nfuncs != env->subprog_cnt) { 18068 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 18069 return -EINVAL; 18070 } 18071 18072 urec_size = attr->func_info_rec_size; 18073 18074 prog = env->prog; 18075 btf = prog->aux->btf; 18076 18077 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 18078 18079 krecord = prog->aux->func_info; 18080 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL_ACCOUNT | __GFP_NOWARN); 18081 if (!info_aux) 18082 return -ENOMEM; 18083 18084 for (i = 0; i < nfuncs; i++) { 18085 /* check insn_off */ 18086 ret = -EINVAL; 18087 18088 if (env->subprog_info[i].start != krecord[i].insn_off) { 18089 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 18090 goto err_free; 18091 } 18092 18093 /* Already checked type_id */ 18094 type = btf_type_by_id(btf, krecord[i].type_id); 18095 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 18096 /* Already checked func_proto */ 18097 func_proto = btf_type_by_id(btf, type->type); 18098 18099 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 18100 scalar_return = 18101 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 18102 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 18103 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 18104 goto err_free; 18105 } 18106 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 18107 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 18108 goto err_free; 18109 } 18110 18111 bpfptr_add(&urecord, urec_size); 18112 } 18113 18114 prog->aux->func_info_aux = info_aux; 18115 return 0; 18116 18117 err_free: 18118 kfree(info_aux); 18119 return ret; 18120 } 18121 18122 static void adjust_btf_func(struct bpf_verifier_env *env) 18123 { 18124 struct bpf_prog_aux *aux = env->prog->aux; 18125 int i; 18126 18127 if (!aux->func_info) 18128 return; 18129 18130 /* func_info is not available for hidden subprogs */ 18131 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 18132 aux->func_info[i].insn_off = env->subprog_info[i].start; 18133 } 18134 18135 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 18136 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 18137 18138 static int check_btf_line(struct bpf_verifier_env *env, 18139 const union bpf_attr *attr, 18140 bpfptr_t uattr) 18141 { 18142 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 18143 struct bpf_subprog_info *sub; 18144 struct bpf_line_info *linfo; 18145 struct bpf_prog *prog; 18146 const struct btf *btf; 18147 bpfptr_t ulinfo; 18148 int err; 18149 18150 nr_linfo = attr->line_info_cnt; 18151 if (!nr_linfo) 18152 return 0; 18153 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 18154 return -EINVAL; 18155 18156 rec_size = attr->line_info_rec_size; 18157 if (rec_size < MIN_BPF_LINEINFO_SIZE || 18158 rec_size > MAX_LINEINFO_REC_SIZE || 18159 rec_size & (sizeof(u32) - 1)) 18160 return -EINVAL; 18161 18162 /* Need to zero it in case the userspace may 18163 * pass in a smaller bpf_line_info object. 18164 */ 18165 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 18166 GFP_KERNEL_ACCOUNT | __GFP_NOWARN); 18167 if (!linfo) 18168 return -ENOMEM; 18169 18170 prog = env->prog; 18171 btf = prog->aux->btf; 18172 18173 s = 0; 18174 sub = env->subprog_info; 18175 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 18176 expected_size = sizeof(struct bpf_line_info); 18177 ncopy = min_t(u32, expected_size, rec_size); 18178 for (i = 0; i < nr_linfo; i++) { 18179 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 18180 if (err) { 18181 if (err == -E2BIG) { 18182 verbose(env, "nonzero tailing record in line_info"); 18183 if (copy_to_bpfptr_offset(uattr, 18184 offsetof(union bpf_attr, line_info_rec_size), 18185 &expected_size, sizeof(expected_size))) 18186 err = -EFAULT; 18187 } 18188 goto err_free; 18189 } 18190 18191 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 18192 err = -EFAULT; 18193 goto err_free; 18194 } 18195 18196 /* 18197 * Check insn_off to ensure 18198 * 1) strictly increasing AND 18199 * 2) bounded by prog->len 18200 * 18201 * The linfo[0].insn_off == 0 check logically falls into 18202 * the later "missing bpf_line_info for func..." case 18203 * because the first linfo[0].insn_off must be the 18204 * first sub also and the first sub must have 18205 * subprog_info[0].start == 0. 18206 */ 18207 if ((i && linfo[i].insn_off <= prev_offset) || 18208 linfo[i].insn_off >= prog->len) { 18209 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 18210 i, linfo[i].insn_off, prev_offset, 18211 prog->len); 18212 err = -EINVAL; 18213 goto err_free; 18214 } 18215 18216 if (!prog->insnsi[linfo[i].insn_off].code) { 18217 verbose(env, 18218 "Invalid insn code at line_info[%u].insn_off\n", 18219 i); 18220 err = -EINVAL; 18221 goto err_free; 18222 } 18223 18224 if (!btf_name_by_offset(btf, linfo[i].line_off) || 18225 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 18226 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 18227 err = -EINVAL; 18228 goto err_free; 18229 } 18230 18231 if (s != env->subprog_cnt) { 18232 if (linfo[i].insn_off == sub[s].start) { 18233 sub[s].linfo_idx = i; 18234 s++; 18235 } else if (sub[s].start < linfo[i].insn_off) { 18236 verbose(env, "missing bpf_line_info for func#%u\n", s); 18237 err = -EINVAL; 18238 goto err_free; 18239 } 18240 } 18241 18242 prev_offset = linfo[i].insn_off; 18243 bpfptr_add(&ulinfo, rec_size); 18244 } 18245 18246 if (s != env->subprog_cnt) { 18247 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 18248 env->subprog_cnt - s, s); 18249 err = -EINVAL; 18250 goto err_free; 18251 } 18252 18253 prog->aux->linfo = linfo; 18254 prog->aux->nr_linfo = nr_linfo; 18255 18256 return 0; 18257 18258 err_free: 18259 kvfree(linfo); 18260 return err; 18261 } 18262 18263 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 18264 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 18265 18266 static int check_core_relo(struct bpf_verifier_env *env, 18267 const union bpf_attr *attr, 18268 bpfptr_t uattr) 18269 { 18270 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 18271 struct bpf_core_relo core_relo = {}; 18272 struct bpf_prog *prog = env->prog; 18273 const struct btf *btf = prog->aux->btf; 18274 struct bpf_core_ctx ctx = { 18275 .log = &env->log, 18276 .btf = btf, 18277 }; 18278 bpfptr_t u_core_relo; 18279 int err; 18280 18281 nr_core_relo = attr->core_relo_cnt; 18282 if (!nr_core_relo) 18283 return 0; 18284 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 18285 return -EINVAL; 18286 18287 rec_size = attr->core_relo_rec_size; 18288 if (rec_size < MIN_CORE_RELO_SIZE || 18289 rec_size > MAX_CORE_RELO_SIZE || 18290 rec_size % sizeof(u32)) 18291 return -EINVAL; 18292 18293 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 18294 expected_size = sizeof(struct bpf_core_relo); 18295 ncopy = min_t(u32, expected_size, rec_size); 18296 18297 /* Unlike func_info and line_info, copy and apply each CO-RE 18298 * relocation record one at a time. 18299 */ 18300 for (i = 0; i < nr_core_relo; i++) { 18301 /* future proofing when sizeof(bpf_core_relo) changes */ 18302 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 18303 if (err) { 18304 if (err == -E2BIG) { 18305 verbose(env, "nonzero tailing record in core_relo"); 18306 if (copy_to_bpfptr_offset(uattr, 18307 offsetof(union bpf_attr, core_relo_rec_size), 18308 &expected_size, sizeof(expected_size))) 18309 err = -EFAULT; 18310 } 18311 break; 18312 } 18313 18314 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 18315 err = -EFAULT; 18316 break; 18317 } 18318 18319 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 18320 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 18321 i, core_relo.insn_off, prog->len); 18322 err = -EINVAL; 18323 break; 18324 } 18325 18326 err = bpf_core_apply(&ctx, &core_relo, i, 18327 &prog->insnsi[core_relo.insn_off / 8]); 18328 if (err) 18329 break; 18330 bpfptr_add(&u_core_relo, rec_size); 18331 } 18332 return err; 18333 } 18334 18335 static int check_btf_info_early(struct bpf_verifier_env *env, 18336 const union bpf_attr *attr, 18337 bpfptr_t uattr) 18338 { 18339 struct btf *btf; 18340 int err; 18341 18342 if (!attr->func_info_cnt && !attr->line_info_cnt) { 18343 if (check_abnormal_return(env)) 18344 return -EINVAL; 18345 return 0; 18346 } 18347 18348 btf = btf_get_by_fd(attr->prog_btf_fd); 18349 if (IS_ERR(btf)) 18350 return PTR_ERR(btf); 18351 if (btf_is_kernel(btf)) { 18352 btf_put(btf); 18353 return -EACCES; 18354 } 18355 env->prog->aux->btf = btf; 18356 18357 err = check_btf_func_early(env, attr, uattr); 18358 if (err) 18359 return err; 18360 return 0; 18361 } 18362 18363 static int check_btf_info(struct bpf_verifier_env *env, 18364 const union bpf_attr *attr, 18365 bpfptr_t uattr) 18366 { 18367 int err; 18368 18369 if (!attr->func_info_cnt && !attr->line_info_cnt) { 18370 if (check_abnormal_return(env)) 18371 return -EINVAL; 18372 return 0; 18373 } 18374 18375 err = check_btf_func(env, attr, uattr); 18376 if (err) 18377 return err; 18378 18379 err = check_btf_line(env, attr, uattr); 18380 if (err) 18381 return err; 18382 18383 err = check_core_relo(env, attr, uattr); 18384 if (err) 18385 return err; 18386 18387 return 0; 18388 } 18389 18390 /* check %cur's range satisfies %old's */ 18391 static bool range_within(const struct bpf_reg_state *old, 18392 const struct bpf_reg_state *cur) 18393 { 18394 return old->umin_value <= cur->umin_value && 18395 old->umax_value >= cur->umax_value && 18396 old->smin_value <= cur->smin_value && 18397 old->smax_value >= cur->smax_value && 18398 old->u32_min_value <= cur->u32_min_value && 18399 old->u32_max_value >= cur->u32_max_value && 18400 old->s32_min_value <= cur->s32_min_value && 18401 old->s32_max_value >= cur->s32_max_value; 18402 } 18403 18404 /* If in the old state two registers had the same id, then they need to have 18405 * the same id in the new state as well. But that id could be different from 18406 * the old state, so we need to track the mapping from old to new ids. 18407 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 18408 * regs with old id 5 must also have new id 9 for the new state to be safe. But 18409 * regs with a different old id could still have new id 9, we don't care about 18410 * that. 18411 * So we look through our idmap to see if this old id has been seen before. If 18412 * so, we require the new id to match; otherwise, we add the id pair to the map. 18413 */ 18414 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 18415 { 18416 struct bpf_id_pair *map = idmap->map; 18417 unsigned int i; 18418 18419 /* either both IDs should be set or both should be zero */ 18420 if (!!old_id != !!cur_id) 18421 return false; 18422 18423 if (old_id == 0) /* cur_id == 0 as well */ 18424 return true; 18425 18426 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 18427 if (!map[i].old) { 18428 /* Reached an empty slot; haven't seen this id before */ 18429 map[i].old = old_id; 18430 map[i].cur = cur_id; 18431 return true; 18432 } 18433 if (map[i].old == old_id) 18434 return map[i].cur == cur_id; 18435 if (map[i].cur == cur_id) 18436 return false; 18437 } 18438 /* We ran out of idmap slots, which should be impossible */ 18439 WARN_ON_ONCE(1); 18440 return false; 18441 } 18442 18443 /* Similar to check_ids(), but allocate a unique temporary ID 18444 * for 'old_id' or 'cur_id' of zero. 18445 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 18446 */ 18447 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 18448 { 18449 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 18450 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 18451 18452 return check_ids(old_id, cur_id, idmap); 18453 } 18454 18455 static void clean_func_state(struct bpf_verifier_env *env, 18456 struct bpf_func_state *st) 18457 { 18458 enum bpf_reg_liveness live; 18459 int i, j; 18460 18461 for (i = 0; i < BPF_REG_FP; i++) { 18462 live = st->regs[i].live; 18463 /* liveness must not touch this register anymore */ 18464 st->regs[i].live |= REG_LIVE_DONE; 18465 if (!(live & REG_LIVE_READ)) 18466 /* since the register is unused, clear its state 18467 * to make further comparison simpler 18468 */ 18469 __mark_reg_not_init(env, &st->regs[i]); 18470 } 18471 18472 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 18473 live = st->stack[i].spilled_ptr.live; 18474 /* liveness must not touch this stack slot anymore */ 18475 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 18476 if (!(live & REG_LIVE_READ)) { 18477 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 18478 for (j = 0; j < BPF_REG_SIZE; j++) 18479 st->stack[i].slot_type[j] = STACK_INVALID; 18480 } 18481 } 18482 } 18483 18484 static void clean_verifier_state(struct bpf_verifier_env *env, 18485 struct bpf_verifier_state *st) 18486 { 18487 int i; 18488 18489 for (i = 0; i <= st->curframe; i++) 18490 clean_func_state(env, st->frame[i]); 18491 } 18492 18493 /* the parentage chains form a tree. 18494 * the verifier states are added to state lists at given insn and 18495 * pushed into state stack for future exploration. 18496 * when the verifier reaches bpf_exit insn some of the verifier states 18497 * stored in the state lists have their final liveness state already, 18498 * but a lot of states will get revised from liveness point of view when 18499 * the verifier explores other branches. 18500 * Example: 18501 * 1: r0 = 1 18502 * 2: if r1 == 100 goto pc+1 18503 * 3: r0 = 2 18504 * 4: exit 18505 * when the verifier reaches exit insn the register r0 in the state list of 18506 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 18507 * of insn 2 and goes exploring further. At the insn 4 it will walk the 18508 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 18509 * 18510 * Since the verifier pushes the branch states as it sees them while exploring 18511 * the program the condition of walking the branch instruction for the second 18512 * time means that all states below this branch were already explored and 18513 * their final liveness marks are already propagated. 18514 * Hence when the verifier completes the search of state list in is_state_visited() 18515 * we can call this clean_live_states() function to mark all liveness states 18516 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 18517 * will not be used. 18518 * This function also clears the registers and stack for states that !READ 18519 * to simplify state merging. 18520 * 18521 * Important note here that walking the same branch instruction in the callee 18522 * doesn't meant that the states are DONE. The verifier has to compare 18523 * the callsites 18524 */ 18525 static void clean_live_states(struct bpf_verifier_env *env, int insn, 18526 struct bpf_verifier_state *cur) 18527 { 18528 struct bpf_verifier_state_list *sl; 18529 struct list_head *pos, *head; 18530 18531 head = explored_state(env, insn); 18532 list_for_each(pos, head) { 18533 sl = container_of(pos, struct bpf_verifier_state_list, node); 18534 if (sl->state.branches) 18535 continue; 18536 if (sl->state.insn_idx != insn || 18537 !same_callsites(&sl->state, cur)) 18538 continue; 18539 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) 18540 /* all regs in this state in all frames were already marked */ 18541 continue; 18542 if (incomplete_read_marks(env, &sl->state)) 18543 continue; 18544 clean_verifier_state(env, &sl->state); 18545 } 18546 } 18547 18548 static bool regs_exact(const struct bpf_reg_state *rold, 18549 const struct bpf_reg_state *rcur, 18550 struct bpf_idmap *idmap) 18551 { 18552 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 18553 check_ids(rold->id, rcur->id, idmap) && 18554 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 18555 } 18556 18557 enum exact_level { 18558 NOT_EXACT, 18559 EXACT, 18560 RANGE_WITHIN 18561 }; 18562 18563 /* Returns true if (rold safe implies rcur safe) */ 18564 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 18565 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 18566 enum exact_level exact) 18567 { 18568 if (exact == EXACT) 18569 return regs_exact(rold, rcur, idmap); 18570 18571 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 18572 /* explored state didn't use this */ 18573 return true; 18574 if (rold->type == NOT_INIT) { 18575 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 18576 /* explored state can't have used this */ 18577 return true; 18578 } 18579 18580 /* Enforce that register types have to match exactly, including their 18581 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 18582 * rule. 18583 * 18584 * One can make a point that using a pointer register as unbounded 18585 * SCALAR would be technically acceptable, but this could lead to 18586 * pointer leaks because scalars are allowed to leak while pointers 18587 * are not. We could make this safe in special cases if root is 18588 * calling us, but it's probably not worth the hassle. 18589 * 18590 * Also, register types that are *not* MAYBE_NULL could technically be 18591 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 18592 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 18593 * to the same map). 18594 * However, if the old MAYBE_NULL register then got NULL checked, 18595 * doing so could have affected others with the same id, and we can't 18596 * check for that because we lost the id when we converted to 18597 * a non-MAYBE_NULL variant. 18598 * So, as a general rule we don't allow mixing MAYBE_NULL and 18599 * non-MAYBE_NULL registers as well. 18600 */ 18601 if (rold->type != rcur->type) 18602 return false; 18603 18604 switch (base_type(rold->type)) { 18605 case SCALAR_VALUE: 18606 if (env->explore_alu_limits) { 18607 /* explore_alu_limits disables tnum_in() and range_within() 18608 * logic and requires everything to be strict 18609 */ 18610 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 18611 check_scalar_ids(rold->id, rcur->id, idmap); 18612 } 18613 if (!rold->precise && exact == NOT_EXACT) 18614 return true; 18615 if ((rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST)) 18616 return false; 18617 if ((rold->id & BPF_ADD_CONST) && (rold->off != rcur->off)) 18618 return false; 18619 /* Why check_ids() for scalar registers? 18620 * 18621 * Consider the following BPF code: 18622 * 1: r6 = ... unbound scalar, ID=a ... 18623 * 2: r7 = ... unbound scalar, ID=b ... 18624 * 3: if (r6 > r7) goto +1 18625 * 4: r6 = r7 18626 * 5: if (r6 > X) goto ... 18627 * 6: ... memory operation using r7 ... 18628 * 18629 * First verification path is [1-6]: 18630 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 18631 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark 18632 * r7 <= X, because r6 and r7 share same id. 18633 * Next verification path is [1-4, 6]. 18634 * 18635 * Instruction (6) would be reached in two states: 18636 * I. r6{.id=b}, r7{.id=b} via path 1-6; 18637 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 18638 * 18639 * Use check_ids() to distinguish these states. 18640 * --- 18641 * Also verify that new value satisfies old value range knowledge. 18642 */ 18643 return range_within(rold, rcur) && 18644 tnum_in(rold->var_off, rcur->var_off) && 18645 check_scalar_ids(rold->id, rcur->id, idmap); 18646 case PTR_TO_MAP_KEY: 18647 case PTR_TO_MAP_VALUE: 18648 case PTR_TO_MEM: 18649 case PTR_TO_BUF: 18650 case PTR_TO_TP_BUFFER: 18651 /* If the new min/max/var_off satisfy the old ones and 18652 * everything else matches, we are OK. 18653 */ 18654 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 18655 range_within(rold, rcur) && 18656 tnum_in(rold->var_off, rcur->var_off) && 18657 check_ids(rold->id, rcur->id, idmap) && 18658 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 18659 case PTR_TO_PACKET_META: 18660 case PTR_TO_PACKET: 18661 /* We must have at least as much range as the old ptr 18662 * did, so that any accesses which were safe before are 18663 * still safe. This is true even if old range < old off, 18664 * since someone could have accessed through (ptr - k), or 18665 * even done ptr -= k in a register, to get a safe access. 18666 */ 18667 if (rold->range > rcur->range) 18668 return false; 18669 /* If the offsets don't match, we can't trust our alignment; 18670 * nor can we be sure that we won't fall out of range. 18671 */ 18672 if (rold->off != rcur->off) 18673 return false; 18674 /* id relations must be preserved */ 18675 if (!check_ids(rold->id, rcur->id, idmap)) 18676 return false; 18677 /* new val must satisfy old val knowledge */ 18678 return range_within(rold, rcur) && 18679 tnum_in(rold->var_off, rcur->var_off); 18680 case PTR_TO_STACK: 18681 /* two stack pointers are equal only if they're pointing to 18682 * the same stack frame, since fp-8 in foo != fp-8 in bar 18683 */ 18684 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 18685 case PTR_TO_ARENA: 18686 return true; 18687 default: 18688 return regs_exact(rold, rcur, idmap); 18689 } 18690 } 18691 18692 static struct bpf_reg_state unbound_reg; 18693 18694 static __init int unbound_reg_init(void) 18695 { 18696 __mark_reg_unknown_imprecise(&unbound_reg); 18697 unbound_reg.live |= REG_LIVE_READ; 18698 return 0; 18699 } 18700 late_initcall(unbound_reg_init); 18701 18702 static bool is_stack_all_misc(struct bpf_verifier_env *env, 18703 struct bpf_stack_state *stack) 18704 { 18705 u32 i; 18706 18707 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 18708 if ((stack->slot_type[i] == STACK_MISC) || 18709 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 18710 continue; 18711 return false; 18712 } 18713 18714 return true; 18715 } 18716 18717 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 18718 struct bpf_stack_state *stack) 18719 { 18720 if (is_spilled_scalar_reg64(stack)) 18721 return &stack->spilled_ptr; 18722 18723 if (is_stack_all_misc(env, stack)) 18724 return &unbound_reg; 18725 18726 return NULL; 18727 } 18728 18729 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 18730 struct bpf_func_state *cur, struct bpf_idmap *idmap, 18731 enum exact_level exact) 18732 { 18733 int i, spi; 18734 18735 /* walk slots of the explored stack and ignore any additional 18736 * slots in the current stack, since explored(safe) state 18737 * didn't use them 18738 */ 18739 for (i = 0; i < old->allocated_stack; i++) { 18740 struct bpf_reg_state *old_reg, *cur_reg; 18741 18742 spi = i / BPF_REG_SIZE; 18743 18744 if (exact != NOT_EXACT && 18745 (i >= cur->allocated_stack || 18746 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 18747 cur->stack[spi].slot_type[i % BPF_REG_SIZE])) 18748 return false; 18749 18750 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 18751 && exact == NOT_EXACT) { 18752 i += BPF_REG_SIZE - 1; 18753 /* explored state didn't use this */ 18754 continue; 18755 } 18756 18757 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 18758 continue; 18759 18760 if (env->allow_uninit_stack && 18761 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 18762 continue; 18763 18764 /* explored stack has more populated slots than current stack 18765 * and these slots were used 18766 */ 18767 if (i >= cur->allocated_stack) 18768 return false; 18769 18770 /* 64-bit scalar spill vs all slots MISC and vice versa. 18771 * Load from all slots MISC produces unbound scalar. 18772 * Construct a fake register for such stack and call 18773 * regsafe() to ensure scalar ids are compared. 18774 */ 18775 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 18776 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 18777 if (old_reg && cur_reg) { 18778 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 18779 return false; 18780 i += BPF_REG_SIZE - 1; 18781 continue; 18782 } 18783 18784 /* if old state was safe with misc data in the stack 18785 * it will be safe with zero-initialized stack. 18786 * The opposite is not true 18787 */ 18788 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 18789 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 18790 continue; 18791 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 18792 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 18793 /* Ex: old explored (safe) state has STACK_SPILL in 18794 * this stack slot, but current has STACK_MISC -> 18795 * this verifier states are not equivalent, 18796 * return false to continue verification of this path 18797 */ 18798 return false; 18799 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 18800 continue; 18801 /* Both old and cur are having same slot_type */ 18802 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 18803 case STACK_SPILL: 18804 /* when explored and current stack slot are both storing 18805 * spilled registers, check that stored pointers types 18806 * are the same as well. 18807 * Ex: explored safe path could have stored 18808 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 18809 * but current path has stored: 18810 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 18811 * such verifier states are not equivalent. 18812 * return false to continue verification of this path 18813 */ 18814 if (!regsafe(env, &old->stack[spi].spilled_ptr, 18815 &cur->stack[spi].spilled_ptr, idmap, exact)) 18816 return false; 18817 break; 18818 case STACK_DYNPTR: 18819 old_reg = &old->stack[spi].spilled_ptr; 18820 cur_reg = &cur->stack[spi].spilled_ptr; 18821 if (old_reg->dynptr.type != cur_reg->dynptr.type || 18822 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 18823 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 18824 return false; 18825 break; 18826 case STACK_ITER: 18827 old_reg = &old->stack[spi].spilled_ptr; 18828 cur_reg = &cur->stack[spi].spilled_ptr; 18829 /* iter.depth is not compared between states as it 18830 * doesn't matter for correctness and would otherwise 18831 * prevent convergence; we maintain it only to prevent 18832 * infinite loop check triggering, see 18833 * iter_active_depths_differ() 18834 */ 18835 if (old_reg->iter.btf != cur_reg->iter.btf || 18836 old_reg->iter.btf_id != cur_reg->iter.btf_id || 18837 old_reg->iter.state != cur_reg->iter.state || 18838 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 18839 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 18840 return false; 18841 break; 18842 case STACK_IRQ_FLAG: 18843 old_reg = &old->stack[spi].spilled_ptr; 18844 cur_reg = &cur->stack[spi].spilled_ptr; 18845 if (!check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap) || 18846 old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class) 18847 return false; 18848 break; 18849 case STACK_MISC: 18850 case STACK_ZERO: 18851 case STACK_INVALID: 18852 continue; 18853 /* Ensure that new unhandled slot types return false by default */ 18854 default: 18855 return false; 18856 } 18857 } 18858 return true; 18859 } 18860 18861 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur, 18862 struct bpf_idmap *idmap) 18863 { 18864 int i; 18865 18866 if (old->acquired_refs != cur->acquired_refs) 18867 return false; 18868 18869 if (old->active_locks != cur->active_locks) 18870 return false; 18871 18872 if (old->active_preempt_locks != cur->active_preempt_locks) 18873 return false; 18874 18875 if (old->active_rcu_lock != cur->active_rcu_lock) 18876 return false; 18877 18878 if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap)) 18879 return false; 18880 18881 if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) || 18882 old->active_lock_ptr != cur->active_lock_ptr) 18883 return false; 18884 18885 for (i = 0; i < old->acquired_refs; i++) { 18886 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) || 18887 old->refs[i].type != cur->refs[i].type) 18888 return false; 18889 switch (old->refs[i].type) { 18890 case REF_TYPE_PTR: 18891 case REF_TYPE_IRQ: 18892 break; 18893 case REF_TYPE_LOCK: 18894 case REF_TYPE_RES_LOCK: 18895 case REF_TYPE_RES_LOCK_IRQ: 18896 if (old->refs[i].ptr != cur->refs[i].ptr) 18897 return false; 18898 break; 18899 default: 18900 WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type); 18901 return false; 18902 } 18903 } 18904 18905 return true; 18906 } 18907 18908 /* compare two verifier states 18909 * 18910 * all states stored in state_list are known to be valid, since 18911 * verifier reached 'bpf_exit' instruction through them 18912 * 18913 * this function is called when verifier exploring different branches of 18914 * execution popped from the state stack. If it sees an old state that has 18915 * more strict register state and more strict stack state then this execution 18916 * branch doesn't need to be explored further, since verifier already 18917 * concluded that more strict state leads to valid finish. 18918 * 18919 * Therefore two states are equivalent if register state is more conservative 18920 * and explored stack state is more conservative than the current one. 18921 * Example: 18922 * explored current 18923 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 18924 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 18925 * 18926 * In other words if current stack state (one being explored) has more 18927 * valid slots than old one that already passed validation, it means 18928 * the verifier can stop exploring and conclude that current state is valid too 18929 * 18930 * Similarly with registers. If explored state has register type as invalid 18931 * whereas register type in current state is meaningful, it means that 18932 * the current state will reach 'bpf_exit' instruction safely 18933 */ 18934 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 18935 struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact) 18936 { 18937 u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before; 18938 u16 i; 18939 18940 if (old->callback_depth > cur->callback_depth) 18941 return false; 18942 18943 for (i = 0; i < MAX_BPF_REG; i++) 18944 if (((1 << i) & live_regs) && 18945 !regsafe(env, &old->regs[i], &cur->regs[i], 18946 &env->idmap_scratch, exact)) 18947 return false; 18948 18949 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 18950 return false; 18951 18952 return true; 18953 } 18954 18955 static void reset_idmap_scratch(struct bpf_verifier_env *env) 18956 { 18957 env->idmap_scratch.tmp_id_gen = env->id_gen; 18958 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 18959 } 18960 18961 static bool states_equal(struct bpf_verifier_env *env, 18962 struct bpf_verifier_state *old, 18963 struct bpf_verifier_state *cur, 18964 enum exact_level exact) 18965 { 18966 u32 insn_idx; 18967 int i; 18968 18969 if (old->curframe != cur->curframe) 18970 return false; 18971 18972 reset_idmap_scratch(env); 18973 18974 /* Verification state from speculative execution simulation 18975 * must never prune a non-speculative execution one. 18976 */ 18977 if (old->speculative && !cur->speculative) 18978 return false; 18979 18980 if (old->in_sleepable != cur->in_sleepable) 18981 return false; 18982 18983 if (!refsafe(old, cur, &env->idmap_scratch)) 18984 return false; 18985 18986 /* for states to be equal callsites have to be the same 18987 * and all frame states need to be equivalent 18988 */ 18989 for (i = 0; i <= old->curframe; i++) { 18990 insn_idx = frame_insn_idx(old, i); 18991 if (old->frame[i]->callsite != cur->frame[i]->callsite) 18992 return false; 18993 if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact)) 18994 return false; 18995 } 18996 return true; 18997 } 18998 18999 /* Return 0 if no propagation happened. Return negative error code if error 19000 * happened. Otherwise, return the propagated bit. 19001 */ 19002 static int propagate_liveness_reg(struct bpf_verifier_env *env, 19003 struct bpf_reg_state *reg, 19004 struct bpf_reg_state *parent_reg) 19005 { 19006 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 19007 u8 flag = reg->live & REG_LIVE_READ; 19008 int err; 19009 19010 /* When comes here, read flags of PARENT_REG or REG could be any of 19011 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 19012 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 19013 */ 19014 if (parent_flag == REG_LIVE_READ64 || 19015 /* Or if there is no read flag from REG. */ 19016 !flag || 19017 /* Or if the read flag from REG is the same as PARENT_REG. */ 19018 parent_flag == flag) 19019 return 0; 19020 19021 err = mark_reg_read(env, reg, parent_reg, flag); 19022 if (err) 19023 return err; 19024 19025 return flag; 19026 } 19027 19028 /* A write screens off any subsequent reads; but write marks come from the 19029 * straight-line code between a state and its parent. When we arrive at an 19030 * equivalent state (jump target or such) we didn't arrive by the straight-line 19031 * code, so read marks in the state must propagate to the parent regardless 19032 * of the state's write marks. That's what 'parent == state->parent' comparison 19033 * in mark_reg_read() is for. 19034 */ 19035 static int propagate_liveness(struct bpf_verifier_env *env, 19036 const struct bpf_verifier_state *vstate, 19037 struct bpf_verifier_state *vparent, 19038 bool *changed) 19039 { 19040 struct bpf_reg_state *state_reg, *parent_reg; 19041 struct bpf_func_state *state, *parent; 19042 int i, frame, err = 0; 19043 bool tmp = false; 19044 19045 changed = changed ?: &tmp; 19046 if (vparent->curframe != vstate->curframe) { 19047 WARN(1, "propagate_live: parent frame %d current frame %d\n", 19048 vparent->curframe, vstate->curframe); 19049 return -EFAULT; 19050 } 19051 /* Propagate read liveness of registers... */ 19052 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 19053 for (frame = 0; frame <= vstate->curframe; frame++) { 19054 parent = vparent->frame[frame]; 19055 state = vstate->frame[frame]; 19056 parent_reg = parent->regs; 19057 state_reg = state->regs; 19058 /* We don't need to worry about FP liveness, it's read-only */ 19059 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 19060 err = propagate_liveness_reg(env, &state_reg[i], 19061 &parent_reg[i]); 19062 if (err < 0) 19063 return err; 19064 *changed |= err > 0; 19065 if (err == REG_LIVE_READ64) 19066 mark_insn_zext(env, &parent_reg[i]); 19067 } 19068 19069 /* Propagate stack slots. */ 19070 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 19071 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 19072 parent_reg = &parent->stack[i].spilled_ptr; 19073 state_reg = &state->stack[i].spilled_ptr; 19074 err = propagate_liveness_reg(env, state_reg, 19075 parent_reg); 19076 *changed |= err > 0; 19077 if (err < 0) 19078 return err; 19079 } 19080 } 19081 return 0; 19082 } 19083 19084 /* find precise scalars in the previous equivalent state and 19085 * propagate them into the current state 19086 */ 19087 static int propagate_precision(struct bpf_verifier_env *env, 19088 const struct bpf_verifier_state *old, 19089 struct bpf_verifier_state *cur, 19090 bool *changed) 19091 { 19092 struct bpf_reg_state *state_reg; 19093 struct bpf_func_state *state; 19094 int i, err = 0, fr; 19095 bool first; 19096 19097 for (fr = old->curframe; fr >= 0; fr--) { 19098 state = old->frame[fr]; 19099 state_reg = state->regs; 19100 first = true; 19101 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 19102 if (state_reg->type != SCALAR_VALUE || 19103 !state_reg->precise || 19104 !(state_reg->live & REG_LIVE_READ)) 19105 continue; 19106 if (env->log.level & BPF_LOG_LEVEL2) { 19107 if (first) 19108 verbose(env, "frame %d: propagating r%d", fr, i); 19109 else 19110 verbose(env, ",r%d", i); 19111 } 19112 bt_set_frame_reg(&env->bt, fr, i); 19113 first = false; 19114 } 19115 19116 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 19117 if (!is_spilled_reg(&state->stack[i])) 19118 continue; 19119 state_reg = &state->stack[i].spilled_ptr; 19120 if (state_reg->type != SCALAR_VALUE || 19121 !state_reg->precise || 19122 !(state_reg->live & REG_LIVE_READ)) 19123 continue; 19124 if (env->log.level & BPF_LOG_LEVEL2) { 19125 if (first) 19126 verbose(env, "frame %d: propagating fp%d", 19127 fr, (-i - 1) * BPF_REG_SIZE); 19128 else 19129 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 19130 } 19131 bt_set_frame_slot(&env->bt, fr, i); 19132 first = false; 19133 } 19134 if (!first) 19135 verbose(env, "\n"); 19136 } 19137 19138 err = __mark_chain_precision(env, cur, -1, changed); 19139 if (err < 0) 19140 return err; 19141 19142 return 0; 19143 } 19144 19145 #define MAX_BACKEDGE_ITERS 64 19146 19147 /* Propagate read and precision marks from visit->backedges[*].state->equal_state 19148 * to corresponding parent states of visit->backedges[*].state until fixed point is reached, 19149 * then free visit->backedges. 19150 * After execution of this function incomplete_read_marks() will return false 19151 * for all states corresponding to @visit->callchain. 19152 */ 19153 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit) 19154 { 19155 struct bpf_scc_backedge *backedge; 19156 struct bpf_verifier_state *st; 19157 bool changed; 19158 int i, err; 19159 19160 i = 0; 19161 do { 19162 if (i++ > MAX_BACKEDGE_ITERS) { 19163 if (env->log.level & BPF_LOG_LEVEL2) 19164 verbose(env, "%s: too many iterations\n", __func__); 19165 for (backedge = visit->backedges; backedge; backedge = backedge->next) 19166 mark_all_scalars_precise(env, &backedge->state); 19167 break; 19168 } 19169 changed = false; 19170 for (backedge = visit->backedges; backedge; backedge = backedge->next) { 19171 st = &backedge->state; 19172 err = propagate_liveness(env, st->equal_state, st, &changed); 19173 if (err) 19174 return err; 19175 err = propagate_precision(env, st->equal_state, st, &changed); 19176 if (err) 19177 return err; 19178 } 19179 } while (changed); 19180 19181 free_backedges(visit); 19182 return 0; 19183 } 19184 19185 static bool states_maybe_looping(struct bpf_verifier_state *old, 19186 struct bpf_verifier_state *cur) 19187 { 19188 struct bpf_func_state *fold, *fcur; 19189 int i, fr = cur->curframe; 19190 19191 if (old->curframe != fr) 19192 return false; 19193 19194 fold = old->frame[fr]; 19195 fcur = cur->frame[fr]; 19196 for (i = 0; i < MAX_BPF_REG; i++) 19197 if (memcmp(&fold->regs[i], &fcur->regs[i], 19198 offsetof(struct bpf_reg_state, parent))) 19199 return false; 19200 return true; 19201 } 19202 19203 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 19204 { 19205 return env->insn_aux_data[insn_idx].is_iter_next; 19206 } 19207 19208 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 19209 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 19210 * states to match, which otherwise would look like an infinite loop. So while 19211 * iter_next() calls are taken care of, we still need to be careful and 19212 * prevent erroneous and too eager declaration of "infinite loop", when 19213 * iterators are involved. 19214 * 19215 * Here's a situation in pseudo-BPF assembly form: 19216 * 19217 * 0: again: ; set up iter_next() call args 19218 * 1: r1 = &it ; <CHECKPOINT HERE> 19219 * 2: call bpf_iter_num_next ; this is iter_next() call 19220 * 3: if r0 == 0 goto done 19221 * 4: ... something useful here ... 19222 * 5: goto again ; another iteration 19223 * 6: done: 19224 * 7: r1 = &it 19225 * 8: call bpf_iter_num_destroy ; clean up iter state 19226 * 9: exit 19227 * 19228 * This is a typical loop. Let's assume that we have a prune point at 1:, 19229 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 19230 * again`, assuming other heuristics don't get in a way). 19231 * 19232 * When we first time come to 1:, let's say we have some state X. We proceed 19233 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 19234 * Now we come back to validate that forked ACTIVE state. We proceed through 19235 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 19236 * are converging. But the problem is that we don't know that yet, as this 19237 * convergence has to happen at iter_next() call site only. So if nothing is 19238 * done, at 1: verifier will use bounded loop logic and declare infinite 19239 * looping (and would be *technically* correct, if not for iterator's 19240 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 19241 * don't want that. So what we do in process_iter_next_call() when we go on 19242 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 19243 * a different iteration. So when we suspect an infinite loop, we additionally 19244 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 19245 * pretend we are not looping and wait for next iter_next() call. 19246 * 19247 * This only applies to ACTIVE state. In DRAINED state we don't expect to 19248 * loop, because that would actually mean infinite loop, as DRAINED state is 19249 * "sticky", and so we'll keep returning into the same instruction with the 19250 * same state (at least in one of possible code paths). 19251 * 19252 * This approach allows to keep infinite loop heuristic even in the face of 19253 * active iterator. E.g., C snippet below is and will be detected as 19254 * infinitely looping: 19255 * 19256 * struct bpf_iter_num it; 19257 * int *p, x; 19258 * 19259 * bpf_iter_num_new(&it, 0, 10); 19260 * while ((p = bpf_iter_num_next(&t))) { 19261 * x = p; 19262 * while (x--) {} // <<-- infinite loop here 19263 * } 19264 * 19265 */ 19266 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 19267 { 19268 struct bpf_reg_state *slot, *cur_slot; 19269 struct bpf_func_state *state; 19270 int i, fr; 19271 19272 for (fr = old->curframe; fr >= 0; fr--) { 19273 state = old->frame[fr]; 19274 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 19275 if (state->stack[i].slot_type[0] != STACK_ITER) 19276 continue; 19277 19278 slot = &state->stack[i].spilled_ptr; 19279 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 19280 continue; 19281 19282 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 19283 if (cur_slot->iter.depth != slot->iter.depth) 19284 return true; 19285 } 19286 } 19287 return false; 19288 } 19289 19290 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 19291 { 19292 struct bpf_verifier_state_list *new_sl; 19293 struct bpf_verifier_state_list *sl; 19294 struct bpf_verifier_state *cur = env->cur_state, *new; 19295 bool force_new_state, add_new_state, loop; 19296 int i, j, n, err, states_cnt = 0; 19297 struct list_head *pos, *tmp, *head; 19298 19299 force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx) || 19300 /* Avoid accumulating infinitely long jmp history */ 19301 cur->jmp_history_cnt > 40; 19302 19303 /* bpf progs typically have pruning point every 4 instructions 19304 * http://vger.kernel.org/bpfconf2019.html#session-1 19305 * Do not add new state for future pruning if the verifier hasn't seen 19306 * at least 2 jumps and at least 8 instructions. 19307 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 19308 * In tests that amounts to up to 50% reduction into total verifier 19309 * memory consumption and 20% verifier time speedup. 19310 */ 19311 add_new_state = force_new_state; 19312 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 19313 env->insn_processed - env->prev_insn_processed >= 8) 19314 add_new_state = true; 19315 19316 clean_live_states(env, insn_idx, cur); 19317 19318 loop = false; 19319 head = explored_state(env, insn_idx); 19320 list_for_each_safe(pos, tmp, head) { 19321 sl = container_of(pos, struct bpf_verifier_state_list, node); 19322 states_cnt++; 19323 if (sl->state.insn_idx != insn_idx) 19324 continue; 19325 19326 if (sl->state.branches) { 19327 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 19328 19329 if (frame->in_async_callback_fn && 19330 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 19331 /* Different async_entry_cnt means that the verifier is 19332 * processing another entry into async callback. 19333 * Seeing the same state is not an indication of infinite 19334 * loop or infinite recursion. 19335 * But finding the same state doesn't mean that it's safe 19336 * to stop processing the current state. The previous state 19337 * hasn't yet reached bpf_exit, since state.branches > 0. 19338 * Checking in_async_callback_fn alone is not enough either. 19339 * Since the verifier still needs to catch infinite loops 19340 * inside async callbacks. 19341 */ 19342 goto skip_inf_loop_check; 19343 } 19344 /* BPF open-coded iterators loop detection is special. 19345 * states_maybe_looping() logic is too simplistic in detecting 19346 * states that *might* be equivalent, because it doesn't know 19347 * about ID remapping, so don't even perform it. 19348 * See process_iter_next_call() and iter_active_depths_differ() 19349 * for overview of the logic. When current and one of parent 19350 * states are detected as equivalent, it's a good thing: we prove 19351 * convergence and can stop simulating further iterations. 19352 * It's safe to assume that iterator loop will finish, taking into 19353 * account iter_next() contract of eventually returning 19354 * sticky NULL result. 19355 * 19356 * Note, that states have to be compared exactly in this case because 19357 * read and precision marks might not be finalized inside the loop. 19358 * E.g. as in the program below: 19359 * 19360 * 1. r7 = -16 19361 * 2. r6 = bpf_get_prandom_u32() 19362 * 3. while (bpf_iter_num_next(&fp[-8])) { 19363 * 4. if (r6 != 42) { 19364 * 5. r7 = -32 19365 * 6. r6 = bpf_get_prandom_u32() 19366 * 7. continue 19367 * 8. } 19368 * 9. r0 = r10 19369 * 10. r0 += r7 19370 * 11. r8 = *(u64 *)(r0 + 0) 19371 * 12. r6 = bpf_get_prandom_u32() 19372 * 13. } 19373 * 19374 * Here verifier would first visit path 1-3, create a checkpoint at 3 19375 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 19376 * not have read or precision mark for r7 yet, thus inexact states 19377 * comparison would discard current state with r7=-32 19378 * => unsafe memory access at 11 would not be caught. 19379 */ 19380 if (is_iter_next_insn(env, insn_idx)) { 19381 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 19382 struct bpf_func_state *cur_frame; 19383 struct bpf_reg_state *iter_state, *iter_reg; 19384 int spi; 19385 19386 cur_frame = cur->frame[cur->curframe]; 19387 /* btf_check_iter_kfuncs() enforces that 19388 * iter state pointer is always the first arg 19389 */ 19390 iter_reg = &cur_frame->regs[BPF_REG_1]; 19391 /* current state is valid due to states_equal(), 19392 * so we can assume valid iter and reg state, 19393 * no need for extra (re-)validations 19394 */ 19395 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 19396 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 19397 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 19398 loop = true; 19399 goto hit; 19400 } 19401 } 19402 goto skip_inf_loop_check; 19403 } 19404 if (is_may_goto_insn_at(env, insn_idx)) { 19405 if (sl->state.may_goto_depth != cur->may_goto_depth && 19406 states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 19407 loop = true; 19408 goto hit; 19409 } 19410 } 19411 if (calls_callback(env, insn_idx)) { 19412 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 19413 goto hit; 19414 goto skip_inf_loop_check; 19415 } 19416 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 19417 if (states_maybe_looping(&sl->state, cur) && 19418 states_equal(env, &sl->state, cur, EXACT) && 19419 !iter_active_depths_differ(&sl->state, cur) && 19420 sl->state.may_goto_depth == cur->may_goto_depth && 19421 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 19422 verbose_linfo(env, insn_idx, "; "); 19423 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 19424 verbose(env, "cur state:"); 19425 print_verifier_state(env, cur, cur->curframe, true); 19426 verbose(env, "old state:"); 19427 print_verifier_state(env, &sl->state, cur->curframe, true); 19428 return -EINVAL; 19429 } 19430 /* if the verifier is processing a loop, avoid adding new state 19431 * too often, since different loop iterations have distinct 19432 * states and may not help future pruning. 19433 * This threshold shouldn't be too low to make sure that 19434 * a loop with large bound will be rejected quickly. 19435 * The most abusive loop will be: 19436 * r1 += 1 19437 * if r1 < 1000000 goto pc-2 19438 * 1M insn_procssed limit / 100 == 10k peak states. 19439 * This threshold shouldn't be too high either, since states 19440 * at the end of the loop are likely to be useful in pruning. 19441 */ 19442 skip_inf_loop_check: 19443 if (!force_new_state && 19444 env->jmps_processed - env->prev_jmps_processed < 20 && 19445 env->insn_processed - env->prev_insn_processed < 100) 19446 add_new_state = false; 19447 goto miss; 19448 } 19449 /* See comments for mark_all_regs_read_and_precise() */ 19450 loop = incomplete_read_marks(env, &sl->state); 19451 if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) { 19452 hit: 19453 sl->hit_cnt++; 19454 /* reached equivalent register/stack state, 19455 * prune the search. 19456 * Registers read by the continuation are read by us. 19457 * If we have any write marks in env->cur_state, they 19458 * will prevent corresponding reads in the continuation 19459 * from reaching our parent (an explored_state). Our 19460 * own state will get the read marks recorded, but 19461 * they'll be immediately forgotten as we're pruning 19462 * this state and will pop a new one. 19463 */ 19464 err = propagate_liveness(env, &sl->state, cur, NULL); 19465 19466 /* if previous state reached the exit with precision and 19467 * current state is equivalent to it (except precision marks) 19468 * the precision needs to be propagated back in 19469 * the current state. 19470 */ 19471 if (is_jmp_point(env, env->insn_idx)) 19472 err = err ? : push_jmp_history(env, cur, 0, 0); 19473 err = err ? : propagate_precision(env, &sl->state, cur, NULL); 19474 if (err) 19475 return err; 19476 /* When processing iterator based loops above propagate_liveness and 19477 * propagate_precision calls are not sufficient to transfer all relevant 19478 * read and precision marks. E.g. consider the following case: 19479 * 19480 * .-> A --. Assume the states are visited in the order A, B, C. 19481 * | | | Assume that state B reaches a state equivalent to state A. 19482 * | v v At this point, state C is not processed yet, so state A 19483 * '-- B C has not received any read or precision marks from C. 19484 * Thus, marks propagated from A to B are incomplete. 19485 * 19486 * The verifier mitigates this by performing the following steps: 19487 * 19488 * - Prior to the main verification pass, strongly connected components 19489 * (SCCs) are computed over the program's control flow graph, 19490 * intraprocedurally. 19491 * 19492 * - During the main verification pass, `maybe_enter_scc()` checks 19493 * whether the current verifier state is entering an SCC. If so, an 19494 * instance of a `bpf_scc_visit` object is created, and the state 19495 * entering the SCC is recorded as the entry state. 19496 * 19497 * - This instance is associated not with the SCC itself, but with a 19498 * `bpf_scc_callchain`: a tuple consisting of the call sites leading to 19499 * the SCC and the SCC id. See `compute_scc_callchain()`. 19500 * 19501 * - When a verification path encounters a `states_equal(..., 19502 * RANGE_WITHIN)` condition, there exists a call chain describing the 19503 * current state and a corresponding `bpf_scc_visit` instance. A copy 19504 * of the current state is created and added to 19505 * `bpf_scc_visit->backedges`. 19506 * 19507 * - When a verification path terminates, `maybe_exit_scc()` is called 19508 * from `update_branch_counts()`. For states with `branches == 0`, it 19509 * checks whether the state is the entry state of any `bpf_scc_visit` 19510 * instance. If it is, this indicates that all paths originating from 19511 * this SCC visit have been explored. `propagate_backedges()` is then 19512 * called, which propagates read and precision marks through the 19513 * backedges until a fixed point is reached. 19514 * (In the earlier example, this would propagate marks from A to B, 19515 * from C to A, and then again from A to B.) 19516 * 19517 * A note on callchains 19518 * -------------------- 19519 * 19520 * Consider the following example: 19521 * 19522 * void foo() { loop { ... SCC#1 ... } } 19523 * void main() { 19524 * A: foo(); 19525 * B: ... 19526 * C: foo(); 19527 * } 19528 * 19529 * Here, there are two distinct callchains leading to SCC#1: 19530 * - (A, SCC#1) 19531 * - (C, SCC#1) 19532 * 19533 * Each callchain identifies a separate `bpf_scc_visit` instance that 19534 * accumulates backedge states. The `propagate_{liveness,precision}()` 19535 * functions traverse the parent state of each backedge state, which 19536 * means these parent states must remain valid (i.e., not freed) while 19537 * the corresponding `bpf_scc_visit` instance exists. 19538 * 19539 * Associating `bpf_scc_visit` instances directly with SCCs instead of 19540 * callchains would break this invariant: 19541 * - States explored during `C: foo()` would contribute backedges to 19542 * SCC#1, but SCC#1 would only be exited once the exploration of 19543 * `A: foo()` completes. 19544 * - By that time, the states explored between `A: foo()` and `C: foo()` 19545 * (i.e., `B: ...`) may have already been freed, causing the parent 19546 * links for states from `C: foo()` to become invalid. 19547 */ 19548 if (loop) { 19549 struct bpf_scc_backedge *backedge; 19550 19551 backedge = kzalloc(sizeof(*backedge), GFP_KERNEL_ACCOUNT); 19552 if (!backedge) 19553 return -ENOMEM; 19554 err = copy_verifier_state(&backedge->state, cur); 19555 backedge->state.equal_state = &sl->state; 19556 backedge->state.insn_idx = insn_idx; 19557 err = err ?: add_scc_backedge(env, &sl->state, backedge); 19558 if (err) { 19559 free_verifier_state(&backedge->state, false); 19560 kvfree(backedge); 19561 return err; 19562 } 19563 } 19564 return 1; 19565 } 19566 miss: 19567 /* when new state is not going to be added do not increase miss count. 19568 * Otherwise several loop iterations will remove the state 19569 * recorded earlier. The goal of these heuristics is to have 19570 * states from some iterations of the loop (some in the beginning 19571 * and some at the end) to help pruning. 19572 */ 19573 if (add_new_state) 19574 sl->miss_cnt++; 19575 /* heuristic to determine whether this state is beneficial 19576 * to keep checking from state equivalence point of view. 19577 * Higher numbers increase max_states_per_insn and verification time, 19578 * but do not meaningfully decrease insn_processed. 19579 * 'n' controls how many times state could miss before eviction. 19580 * Use bigger 'n' for checkpoints because evicting checkpoint states 19581 * too early would hinder iterator convergence. 19582 */ 19583 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 19584 if (sl->miss_cnt > sl->hit_cnt * n + n) { 19585 /* the state is unlikely to be useful. Remove it to 19586 * speed up verification 19587 */ 19588 sl->in_free_list = true; 19589 list_del(&sl->node); 19590 list_add(&sl->node, &env->free_list); 19591 env->free_list_size++; 19592 env->explored_states_size--; 19593 maybe_free_verifier_state(env, sl); 19594 } 19595 } 19596 19597 if (env->max_states_per_insn < states_cnt) 19598 env->max_states_per_insn = states_cnt; 19599 19600 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 19601 return 0; 19602 19603 if (!add_new_state) 19604 return 0; 19605 19606 /* There were no equivalent states, remember the current one. 19607 * Technically the current state is not proven to be safe yet, 19608 * but it will either reach outer most bpf_exit (which means it's safe) 19609 * or it will be rejected. When there are no loops the verifier won't be 19610 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 19611 * again on the way to bpf_exit. 19612 * When looping the sl->state.branches will be > 0 and this state 19613 * will not be considered for equivalence until branches == 0. 19614 */ 19615 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL_ACCOUNT); 19616 if (!new_sl) 19617 return -ENOMEM; 19618 env->total_states++; 19619 env->explored_states_size++; 19620 update_peak_states(env); 19621 env->prev_jmps_processed = env->jmps_processed; 19622 env->prev_insn_processed = env->insn_processed; 19623 19624 /* forget precise markings we inherited, see __mark_chain_precision */ 19625 if (env->bpf_capable) 19626 mark_all_scalars_imprecise(env, cur); 19627 19628 /* add new state to the head of linked list */ 19629 new = &new_sl->state; 19630 err = copy_verifier_state(new, cur); 19631 if (err) { 19632 free_verifier_state(new, false); 19633 kfree(new_sl); 19634 return err; 19635 } 19636 new->insn_idx = insn_idx; 19637 verifier_bug_if(new->branches != 1, env, 19638 "%s:branches_to_explore=%d insn %d", 19639 __func__, new->branches, insn_idx); 19640 err = maybe_enter_scc(env, new); 19641 if (err) { 19642 free_verifier_state(new, false); 19643 kvfree(new_sl); 19644 return err; 19645 } 19646 19647 cur->parent = new; 19648 cur->first_insn_idx = insn_idx; 19649 cur->dfs_depth = new->dfs_depth + 1; 19650 clear_jmp_history(cur); 19651 list_add(&new_sl->node, head); 19652 19653 /* connect new state to parentage chain. Current frame needs all 19654 * registers connected. Only r6 - r9 of the callers are alive (pushed 19655 * to the stack implicitly by JITs) so in callers' frames connect just 19656 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 19657 * the state of the call instruction (with WRITTEN set), and r0 comes 19658 * from callee with its full parentage chain, anyway. 19659 */ 19660 /* clear write marks in current state: the writes we did are not writes 19661 * our child did, so they don't screen off its reads from us. 19662 * (There are no read marks in current state, because reads always mark 19663 * their parent and current state never has children yet. Only 19664 * explored_states can get read marks.) 19665 */ 19666 for (j = 0; j <= cur->curframe; j++) { 19667 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 19668 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 19669 for (i = 0; i < BPF_REG_FP; i++) 19670 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 19671 } 19672 19673 /* all stack frames are accessible from callee, clear them all */ 19674 for (j = 0; j <= cur->curframe; j++) { 19675 struct bpf_func_state *frame = cur->frame[j]; 19676 struct bpf_func_state *newframe = new->frame[j]; 19677 19678 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 19679 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 19680 frame->stack[i].spilled_ptr.parent = 19681 &newframe->stack[i].spilled_ptr; 19682 } 19683 } 19684 return 0; 19685 } 19686 19687 /* Return true if it's OK to have the same insn return a different type. */ 19688 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 19689 { 19690 switch (base_type(type)) { 19691 case PTR_TO_CTX: 19692 case PTR_TO_SOCKET: 19693 case PTR_TO_SOCK_COMMON: 19694 case PTR_TO_TCP_SOCK: 19695 case PTR_TO_XDP_SOCK: 19696 case PTR_TO_BTF_ID: 19697 case PTR_TO_ARENA: 19698 return false; 19699 default: 19700 return true; 19701 } 19702 } 19703 19704 /* If an instruction was previously used with particular pointer types, then we 19705 * need to be careful to avoid cases such as the below, where it may be ok 19706 * for one branch accessing the pointer, but not ok for the other branch: 19707 * 19708 * R1 = sock_ptr 19709 * goto X; 19710 * ... 19711 * R1 = some_other_valid_ptr; 19712 * goto X; 19713 * ... 19714 * R2 = *(u32 *)(R1 + 0); 19715 */ 19716 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 19717 { 19718 return src != prev && (!reg_type_mismatch_ok(src) || 19719 !reg_type_mismatch_ok(prev)); 19720 } 19721 19722 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type) 19723 { 19724 switch (base_type(type)) { 19725 case PTR_TO_MEM: 19726 case PTR_TO_BTF_ID: 19727 return true; 19728 default: 19729 return false; 19730 } 19731 } 19732 19733 static bool is_ptr_to_mem(enum bpf_reg_type type) 19734 { 19735 return base_type(type) == PTR_TO_MEM; 19736 } 19737 19738 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 19739 bool allow_trust_mismatch) 19740 { 19741 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 19742 enum bpf_reg_type merged_type; 19743 19744 if (*prev_type == NOT_INIT) { 19745 /* Saw a valid insn 19746 * dst_reg = *(u32 *)(src_reg + off) 19747 * save type to validate intersecting paths 19748 */ 19749 *prev_type = type; 19750 } else if (reg_type_mismatch(type, *prev_type)) { 19751 /* Abuser program is trying to use the same insn 19752 * dst_reg = *(u32*) (src_reg + off) 19753 * with different pointer types: 19754 * src_reg == ctx in one branch and 19755 * src_reg == stack|map in some other branch. 19756 * Reject it. 19757 */ 19758 if (allow_trust_mismatch && 19759 is_ptr_to_mem_or_btf_id(type) && 19760 is_ptr_to_mem_or_btf_id(*prev_type)) { 19761 /* 19762 * Have to support a use case when one path through 19763 * the program yields TRUSTED pointer while another 19764 * is UNTRUSTED. Fallback to UNTRUSTED to generate 19765 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 19766 * Same behavior of MEM_RDONLY flag. 19767 */ 19768 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type)) 19769 merged_type = PTR_TO_MEM; 19770 else 19771 merged_type = PTR_TO_BTF_ID; 19772 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED)) 19773 merged_type |= PTR_UNTRUSTED; 19774 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY)) 19775 merged_type |= MEM_RDONLY; 19776 *prev_type = merged_type; 19777 } else { 19778 verbose(env, "same insn cannot be used with different pointers\n"); 19779 return -EINVAL; 19780 } 19781 } 19782 19783 return 0; 19784 } 19785 19786 enum { 19787 PROCESS_BPF_EXIT = 1 19788 }; 19789 19790 static int process_bpf_exit_full(struct bpf_verifier_env *env, 19791 bool *do_print_state, 19792 bool exception_exit) 19793 { 19794 /* We must do check_reference_leak here before 19795 * prepare_func_exit to handle the case when 19796 * state->curframe > 0, it may be a callback function, 19797 * for which reference_state must match caller reference 19798 * state when it exits. 19799 */ 19800 int err = check_resource_leak(env, exception_exit, 19801 !env->cur_state->curframe, 19802 "BPF_EXIT instruction in main prog"); 19803 if (err) 19804 return err; 19805 19806 /* The side effect of the prepare_func_exit which is 19807 * being skipped is that it frees bpf_func_state. 19808 * Typically, process_bpf_exit will only be hit with 19809 * outermost exit. copy_verifier_state in pop_stack will 19810 * handle freeing of any extra bpf_func_state left over 19811 * from not processing all nested function exits. We 19812 * also skip return code checks as they are not needed 19813 * for exceptional exits. 19814 */ 19815 if (exception_exit) 19816 return PROCESS_BPF_EXIT; 19817 19818 if (env->cur_state->curframe) { 19819 /* exit from nested function */ 19820 err = prepare_func_exit(env, &env->insn_idx); 19821 if (err) 19822 return err; 19823 *do_print_state = true; 19824 return 0; 19825 } 19826 19827 err = check_return_code(env, BPF_REG_0, "R0"); 19828 if (err) 19829 return err; 19830 return PROCESS_BPF_EXIT; 19831 } 19832 19833 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 19834 { 19835 int err; 19836 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 19837 u8 class = BPF_CLASS(insn->code); 19838 19839 if (class == BPF_ALU || class == BPF_ALU64) { 19840 err = check_alu_op(env, insn); 19841 if (err) 19842 return err; 19843 19844 } else if (class == BPF_LDX) { 19845 bool is_ldsx = BPF_MODE(insn->code) == BPF_MEMSX; 19846 19847 /* Check for reserved fields is already done in 19848 * resolve_pseudo_ldimm64(). 19849 */ 19850 err = check_load_mem(env, insn, false, is_ldsx, true, "ldx"); 19851 if (err) 19852 return err; 19853 } else if (class == BPF_STX) { 19854 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 19855 err = check_atomic(env, insn); 19856 if (err) 19857 return err; 19858 env->insn_idx++; 19859 return 0; 19860 } 19861 19862 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 19863 verbose(env, "BPF_STX uses reserved fields\n"); 19864 return -EINVAL; 19865 } 19866 19867 err = check_store_reg(env, insn, false); 19868 if (err) 19869 return err; 19870 } else if (class == BPF_ST) { 19871 enum bpf_reg_type dst_reg_type; 19872 19873 if (BPF_MODE(insn->code) != BPF_MEM || 19874 insn->src_reg != BPF_REG_0) { 19875 verbose(env, "BPF_ST uses reserved fields\n"); 19876 return -EINVAL; 19877 } 19878 /* check src operand */ 19879 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 19880 if (err) 19881 return err; 19882 19883 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 19884 19885 /* check that memory (dst_reg + off) is writeable */ 19886 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 19887 insn->off, BPF_SIZE(insn->code), 19888 BPF_WRITE, -1, false, false); 19889 if (err) 19890 return err; 19891 19892 err = save_aux_ptr_type(env, dst_reg_type, false); 19893 if (err) 19894 return err; 19895 } else if (class == BPF_JMP || class == BPF_JMP32) { 19896 u8 opcode = BPF_OP(insn->code); 19897 19898 env->jmps_processed++; 19899 if (opcode == BPF_CALL) { 19900 if (BPF_SRC(insn->code) != BPF_K || 19901 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && 19902 insn->off != 0) || 19903 (insn->src_reg != BPF_REG_0 && 19904 insn->src_reg != BPF_PSEUDO_CALL && 19905 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 19906 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 19907 verbose(env, "BPF_CALL uses reserved fields\n"); 19908 return -EINVAL; 19909 } 19910 19911 if (env->cur_state->active_locks) { 19912 if ((insn->src_reg == BPF_REG_0 && 19913 insn->imm != BPF_FUNC_spin_unlock) || 19914 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 19915 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) { 19916 verbose(env, 19917 "function calls are not allowed while holding a lock\n"); 19918 return -EINVAL; 19919 } 19920 } 19921 if (insn->src_reg == BPF_PSEUDO_CALL) { 19922 err = check_func_call(env, insn, &env->insn_idx); 19923 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19924 err = check_kfunc_call(env, insn, &env->insn_idx); 19925 if (!err && is_bpf_throw_kfunc(insn)) 19926 return process_bpf_exit_full(env, do_print_state, true); 19927 } else { 19928 err = check_helper_call(env, insn, &env->insn_idx); 19929 } 19930 if (err) 19931 return err; 19932 19933 mark_reg_scratched(env, BPF_REG_0); 19934 } else if (opcode == BPF_JA) { 19935 if (BPF_SRC(insn->code) != BPF_K || 19936 insn->src_reg != BPF_REG_0 || 19937 insn->dst_reg != BPF_REG_0 || 19938 (class == BPF_JMP && insn->imm != 0) || 19939 (class == BPF_JMP32 && insn->off != 0)) { 19940 verbose(env, "BPF_JA uses reserved fields\n"); 19941 return -EINVAL; 19942 } 19943 19944 if (class == BPF_JMP) 19945 env->insn_idx += insn->off + 1; 19946 else 19947 env->insn_idx += insn->imm + 1; 19948 return 0; 19949 } else if (opcode == BPF_EXIT) { 19950 if (BPF_SRC(insn->code) != BPF_K || 19951 insn->imm != 0 || 19952 insn->src_reg != BPF_REG_0 || 19953 insn->dst_reg != BPF_REG_0 || 19954 class == BPF_JMP32) { 19955 verbose(env, "BPF_EXIT uses reserved fields\n"); 19956 return -EINVAL; 19957 } 19958 return process_bpf_exit_full(env, do_print_state, false); 19959 } else { 19960 err = check_cond_jmp_op(env, insn, &env->insn_idx); 19961 if (err) 19962 return err; 19963 } 19964 } else if (class == BPF_LD) { 19965 u8 mode = BPF_MODE(insn->code); 19966 19967 if (mode == BPF_ABS || mode == BPF_IND) { 19968 err = check_ld_abs(env, insn); 19969 if (err) 19970 return err; 19971 19972 } else if (mode == BPF_IMM) { 19973 err = check_ld_imm(env, insn); 19974 if (err) 19975 return err; 19976 19977 env->insn_idx++; 19978 sanitize_mark_insn_seen(env); 19979 } else { 19980 verbose(env, "invalid BPF_LD mode\n"); 19981 return -EINVAL; 19982 } 19983 } else { 19984 verbose(env, "unknown insn class %d\n", class); 19985 return -EINVAL; 19986 } 19987 19988 env->insn_idx++; 19989 return 0; 19990 } 19991 19992 static int do_check(struct bpf_verifier_env *env) 19993 { 19994 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 19995 struct bpf_verifier_state *state = env->cur_state; 19996 struct bpf_insn *insns = env->prog->insnsi; 19997 int insn_cnt = env->prog->len; 19998 bool do_print_state = false; 19999 int prev_insn_idx = -1; 20000 20001 for (;;) { 20002 struct bpf_insn *insn; 20003 struct bpf_insn_aux_data *insn_aux; 20004 int err; 20005 20006 /* reset current history entry on each new instruction */ 20007 env->cur_hist_ent = NULL; 20008 20009 env->prev_insn_idx = prev_insn_idx; 20010 if (env->insn_idx >= insn_cnt) { 20011 verbose(env, "invalid insn idx %d insn_cnt %d\n", 20012 env->insn_idx, insn_cnt); 20013 return -EFAULT; 20014 } 20015 20016 insn = &insns[env->insn_idx]; 20017 insn_aux = &env->insn_aux_data[env->insn_idx]; 20018 20019 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 20020 verbose(env, 20021 "BPF program is too large. Processed %d insn\n", 20022 env->insn_processed); 20023 return -E2BIG; 20024 } 20025 20026 state->last_insn_idx = env->prev_insn_idx; 20027 state->insn_idx = env->insn_idx; 20028 20029 if (is_prune_point(env, env->insn_idx)) { 20030 err = is_state_visited(env, env->insn_idx); 20031 if (err < 0) 20032 return err; 20033 if (err == 1) { 20034 /* found equivalent state, can prune the search */ 20035 if (env->log.level & BPF_LOG_LEVEL) { 20036 if (do_print_state) 20037 verbose(env, "\nfrom %d to %d%s: safe\n", 20038 env->prev_insn_idx, env->insn_idx, 20039 env->cur_state->speculative ? 20040 " (speculative execution)" : ""); 20041 else 20042 verbose(env, "%d: safe\n", env->insn_idx); 20043 } 20044 goto process_bpf_exit; 20045 } 20046 } 20047 20048 if (is_jmp_point(env, env->insn_idx)) { 20049 err = push_jmp_history(env, state, 0, 0); 20050 if (err) 20051 return err; 20052 } 20053 20054 if (signal_pending(current)) 20055 return -EAGAIN; 20056 20057 if (need_resched()) 20058 cond_resched(); 20059 20060 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 20061 verbose(env, "\nfrom %d to %d%s:", 20062 env->prev_insn_idx, env->insn_idx, 20063 env->cur_state->speculative ? 20064 " (speculative execution)" : ""); 20065 print_verifier_state(env, state, state->curframe, true); 20066 do_print_state = false; 20067 } 20068 20069 if (env->log.level & BPF_LOG_LEVEL) { 20070 if (verifier_state_scratched(env)) 20071 print_insn_state(env, state, state->curframe); 20072 20073 verbose_linfo(env, env->insn_idx, "; "); 20074 env->prev_log_pos = env->log.end_pos; 20075 verbose(env, "%d: ", env->insn_idx); 20076 verbose_insn(env, insn); 20077 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 20078 env->prev_log_pos = env->log.end_pos; 20079 } 20080 20081 if (bpf_prog_is_offloaded(env->prog->aux)) { 20082 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 20083 env->prev_insn_idx); 20084 if (err) 20085 return err; 20086 } 20087 20088 sanitize_mark_insn_seen(env); 20089 prev_insn_idx = env->insn_idx; 20090 20091 /* Reduce verification complexity by stopping speculative path 20092 * verification when a nospec is encountered. 20093 */ 20094 if (state->speculative && insn_aux->nospec) 20095 goto process_bpf_exit; 20096 20097 err = do_check_insn(env, &do_print_state); 20098 if (error_recoverable_with_nospec(err) && state->speculative) { 20099 /* Prevent this speculative path from ever reaching the 20100 * insn that would have been unsafe to execute. 20101 */ 20102 insn_aux->nospec = true; 20103 /* If it was an ADD/SUB insn, potentially remove any 20104 * markings for alu sanitization. 20105 */ 20106 insn_aux->alu_state = 0; 20107 goto process_bpf_exit; 20108 } else if (err < 0) { 20109 return err; 20110 } else if (err == PROCESS_BPF_EXIT) { 20111 goto process_bpf_exit; 20112 } 20113 WARN_ON_ONCE(err); 20114 20115 if (state->speculative && insn_aux->nospec_result) { 20116 /* If we are on a path that performed a jump-op, this 20117 * may skip a nospec patched-in after the jump. This can 20118 * currently never happen because nospec_result is only 20119 * used for the write-ops 20120 * `*(size*)(dst_reg+off)=src_reg|imm32` which must 20121 * never skip the following insn. Still, add a warning 20122 * to document this in case nospec_result is used 20123 * elsewhere in the future. 20124 * 20125 * All non-branch instructions have a single 20126 * fall-through edge. For these, nospec_result should 20127 * already work. 20128 */ 20129 if (verifier_bug_if(BPF_CLASS(insn->code) == BPF_JMP || 20130 BPF_CLASS(insn->code) == BPF_JMP32, env, 20131 "speculation barrier after jump instruction may not have the desired effect")) 20132 return -EFAULT; 20133 process_bpf_exit: 20134 mark_verifier_state_scratched(env); 20135 err = update_branch_counts(env, env->cur_state); 20136 if (err) 20137 return err; 20138 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 20139 pop_log); 20140 if (err < 0) { 20141 if (err != -ENOENT) 20142 return err; 20143 break; 20144 } else { 20145 do_print_state = true; 20146 continue; 20147 } 20148 } 20149 } 20150 20151 return 0; 20152 } 20153 20154 static int find_btf_percpu_datasec(struct btf *btf) 20155 { 20156 const struct btf_type *t; 20157 const char *tname; 20158 int i, n; 20159 20160 /* 20161 * Both vmlinux and module each have their own ".data..percpu" 20162 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 20163 * types to look at only module's own BTF types. 20164 */ 20165 n = btf_nr_types(btf); 20166 if (btf_is_module(btf)) 20167 i = btf_nr_types(btf_vmlinux); 20168 else 20169 i = 1; 20170 20171 for(; i < n; i++) { 20172 t = btf_type_by_id(btf, i); 20173 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 20174 continue; 20175 20176 tname = btf_name_by_offset(btf, t->name_off); 20177 if (!strcmp(tname, ".data..percpu")) 20178 return i; 20179 } 20180 20181 return -ENOENT; 20182 } 20183 20184 /* 20185 * Add btf to the used_btfs array and return the index. (If the btf was 20186 * already added, then just return the index.) Upon successful insertion 20187 * increase btf refcnt, and, if present, also refcount the corresponding 20188 * kernel module. 20189 */ 20190 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 20191 { 20192 struct btf_mod_pair *btf_mod; 20193 int i; 20194 20195 /* check whether we recorded this BTF (and maybe module) already */ 20196 for (i = 0; i < env->used_btf_cnt; i++) 20197 if (env->used_btfs[i].btf == btf) 20198 return i; 20199 20200 if (env->used_btf_cnt >= MAX_USED_BTFS) 20201 return -E2BIG; 20202 20203 btf_get(btf); 20204 20205 btf_mod = &env->used_btfs[env->used_btf_cnt]; 20206 btf_mod->btf = btf; 20207 btf_mod->module = NULL; 20208 20209 /* if we reference variables from kernel module, bump its refcount */ 20210 if (btf_is_module(btf)) { 20211 btf_mod->module = btf_try_get_module(btf); 20212 if (!btf_mod->module) { 20213 btf_put(btf); 20214 return -ENXIO; 20215 } 20216 } 20217 20218 return env->used_btf_cnt++; 20219 } 20220 20221 /* replace pseudo btf_id with kernel symbol address */ 20222 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 20223 struct bpf_insn *insn, 20224 struct bpf_insn_aux_data *aux, 20225 struct btf *btf) 20226 { 20227 const struct btf_var_secinfo *vsi; 20228 const struct btf_type *datasec; 20229 const struct btf_type *t; 20230 const char *sym_name; 20231 bool percpu = false; 20232 u32 type, id = insn->imm; 20233 s32 datasec_id; 20234 u64 addr; 20235 int i; 20236 20237 t = btf_type_by_id(btf, id); 20238 if (!t) { 20239 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 20240 return -ENOENT; 20241 } 20242 20243 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 20244 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 20245 return -EINVAL; 20246 } 20247 20248 sym_name = btf_name_by_offset(btf, t->name_off); 20249 addr = kallsyms_lookup_name(sym_name); 20250 if (!addr) { 20251 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 20252 sym_name); 20253 return -ENOENT; 20254 } 20255 insn[0].imm = (u32)addr; 20256 insn[1].imm = addr >> 32; 20257 20258 if (btf_type_is_func(t)) { 20259 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 20260 aux->btf_var.mem_size = 0; 20261 return 0; 20262 } 20263 20264 datasec_id = find_btf_percpu_datasec(btf); 20265 if (datasec_id > 0) { 20266 datasec = btf_type_by_id(btf, datasec_id); 20267 for_each_vsi(i, datasec, vsi) { 20268 if (vsi->type == id) { 20269 percpu = true; 20270 break; 20271 } 20272 } 20273 } 20274 20275 type = t->type; 20276 t = btf_type_skip_modifiers(btf, type, NULL); 20277 if (percpu) { 20278 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 20279 aux->btf_var.btf = btf; 20280 aux->btf_var.btf_id = type; 20281 } else if (!btf_type_is_struct(t)) { 20282 const struct btf_type *ret; 20283 const char *tname; 20284 u32 tsize; 20285 20286 /* resolve the type size of ksym. */ 20287 ret = btf_resolve_size(btf, t, &tsize); 20288 if (IS_ERR(ret)) { 20289 tname = btf_name_by_offset(btf, t->name_off); 20290 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 20291 tname, PTR_ERR(ret)); 20292 return -EINVAL; 20293 } 20294 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 20295 aux->btf_var.mem_size = tsize; 20296 } else { 20297 aux->btf_var.reg_type = PTR_TO_BTF_ID; 20298 aux->btf_var.btf = btf; 20299 aux->btf_var.btf_id = type; 20300 } 20301 20302 return 0; 20303 } 20304 20305 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 20306 struct bpf_insn *insn, 20307 struct bpf_insn_aux_data *aux) 20308 { 20309 struct btf *btf; 20310 int btf_fd; 20311 int err; 20312 20313 btf_fd = insn[1].imm; 20314 if (btf_fd) { 20315 CLASS(fd, f)(btf_fd); 20316 20317 btf = __btf_get_by_fd(f); 20318 if (IS_ERR(btf)) { 20319 verbose(env, "invalid module BTF object FD specified.\n"); 20320 return -EINVAL; 20321 } 20322 } else { 20323 if (!btf_vmlinux) { 20324 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 20325 return -EINVAL; 20326 } 20327 btf = btf_vmlinux; 20328 } 20329 20330 err = __check_pseudo_btf_id(env, insn, aux, btf); 20331 if (err) 20332 return err; 20333 20334 err = __add_used_btf(env, btf); 20335 if (err < 0) 20336 return err; 20337 return 0; 20338 } 20339 20340 static bool is_tracing_prog_type(enum bpf_prog_type type) 20341 { 20342 switch (type) { 20343 case BPF_PROG_TYPE_KPROBE: 20344 case BPF_PROG_TYPE_TRACEPOINT: 20345 case BPF_PROG_TYPE_PERF_EVENT: 20346 case BPF_PROG_TYPE_RAW_TRACEPOINT: 20347 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 20348 return true; 20349 default: 20350 return false; 20351 } 20352 } 20353 20354 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 20355 { 20356 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 20357 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 20358 } 20359 20360 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 20361 struct bpf_map *map, 20362 struct bpf_prog *prog) 20363 20364 { 20365 enum bpf_prog_type prog_type = resolve_prog_type(prog); 20366 20367 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 20368 btf_record_has_field(map->record, BPF_RB_ROOT)) { 20369 if (is_tracing_prog_type(prog_type)) { 20370 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 20371 return -EINVAL; 20372 } 20373 } 20374 20375 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 20376 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 20377 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 20378 return -EINVAL; 20379 } 20380 20381 if (is_tracing_prog_type(prog_type)) { 20382 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 20383 return -EINVAL; 20384 } 20385 } 20386 20387 if (btf_record_has_field(map->record, BPF_TIMER)) { 20388 if (is_tracing_prog_type(prog_type)) { 20389 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 20390 return -EINVAL; 20391 } 20392 } 20393 20394 if (btf_record_has_field(map->record, BPF_WORKQUEUE)) { 20395 if (is_tracing_prog_type(prog_type)) { 20396 verbose(env, "tracing progs cannot use bpf_wq yet\n"); 20397 return -EINVAL; 20398 } 20399 } 20400 20401 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 20402 !bpf_offload_prog_map_match(prog, map)) { 20403 verbose(env, "offload device mismatch between prog and map\n"); 20404 return -EINVAL; 20405 } 20406 20407 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 20408 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 20409 return -EINVAL; 20410 } 20411 20412 if (prog->sleepable) 20413 switch (map->map_type) { 20414 case BPF_MAP_TYPE_HASH: 20415 case BPF_MAP_TYPE_LRU_HASH: 20416 case BPF_MAP_TYPE_ARRAY: 20417 case BPF_MAP_TYPE_PERCPU_HASH: 20418 case BPF_MAP_TYPE_PERCPU_ARRAY: 20419 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 20420 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 20421 case BPF_MAP_TYPE_HASH_OF_MAPS: 20422 case BPF_MAP_TYPE_RINGBUF: 20423 case BPF_MAP_TYPE_USER_RINGBUF: 20424 case BPF_MAP_TYPE_INODE_STORAGE: 20425 case BPF_MAP_TYPE_SK_STORAGE: 20426 case BPF_MAP_TYPE_TASK_STORAGE: 20427 case BPF_MAP_TYPE_CGRP_STORAGE: 20428 case BPF_MAP_TYPE_QUEUE: 20429 case BPF_MAP_TYPE_STACK: 20430 case BPF_MAP_TYPE_ARENA: 20431 break; 20432 default: 20433 verbose(env, 20434 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 20435 return -EINVAL; 20436 } 20437 20438 if (bpf_map_is_cgroup_storage(map) && 20439 bpf_cgroup_storage_assign(env->prog->aux, map)) { 20440 verbose(env, "only one cgroup storage of each type is allowed\n"); 20441 return -EBUSY; 20442 } 20443 20444 if (map->map_type == BPF_MAP_TYPE_ARENA) { 20445 if (env->prog->aux->arena) { 20446 verbose(env, "Only one arena per program\n"); 20447 return -EBUSY; 20448 } 20449 if (!env->allow_ptr_leaks || !env->bpf_capable) { 20450 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 20451 return -EPERM; 20452 } 20453 if (!env->prog->jit_requested) { 20454 verbose(env, "JIT is required to use arena\n"); 20455 return -EOPNOTSUPP; 20456 } 20457 if (!bpf_jit_supports_arena()) { 20458 verbose(env, "JIT doesn't support arena\n"); 20459 return -EOPNOTSUPP; 20460 } 20461 env->prog->aux->arena = (void *)map; 20462 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 20463 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 20464 return -EINVAL; 20465 } 20466 } 20467 20468 return 0; 20469 } 20470 20471 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 20472 { 20473 int i, err; 20474 20475 /* check whether we recorded this map already */ 20476 for (i = 0; i < env->used_map_cnt; i++) 20477 if (env->used_maps[i] == map) 20478 return i; 20479 20480 if (env->used_map_cnt >= MAX_USED_MAPS) { 20481 verbose(env, "The total number of maps per program has reached the limit of %u\n", 20482 MAX_USED_MAPS); 20483 return -E2BIG; 20484 } 20485 20486 err = check_map_prog_compatibility(env, map, env->prog); 20487 if (err) 20488 return err; 20489 20490 if (env->prog->sleepable) 20491 atomic64_inc(&map->sleepable_refcnt); 20492 20493 /* hold the map. If the program is rejected by verifier, 20494 * the map will be released by release_maps() or it 20495 * will be used by the valid program until it's unloaded 20496 * and all maps are released in bpf_free_used_maps() 20497 */ 20498 bpf_map_inc(map); 20499 20500 env->used_maps[env->used_map_cnt++] = map; 20501 20502 return env->used_map_cnt - 1; 20503 } 20504 20505 /* Add map behind fd to used maps list, if it's not already there, and return 20506 * its index. 20507 * Returns <0 on error, or >= 0 index, on success. 20508 */ 20509 static int add_used_map(struct bpf_verifier_env *env, int fd) 20510 { 20511 struct bpf_map *map; 20512 CLASS(fd, f)(fd); 20513 20514 map = __bpf_map_get(f); 20515 if (IS_ERR(map)) { 20516 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 20517 return PTR_ERR(map); 20518 } 20519 20520 return __add_used_map(env, map); 20521 } 20522 20523 /* find and rewrite pseudo imm in ld_imm64 instructions: 20524 * 20525 * 1. if it accesses map FD, replace it with actual map pointer. 20526 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 20527 * 20528 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 20529 */ 20530 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 20531 { 20532 struct bpf_insn *insn = env->prog->insnsi; 20533 int insn_cnt = env->prog->len; 20534 int i, err; 20535 20536 err = bpf_prog_calc_tag(env->prog); 20537 if (err) 20538 return err; 20539 20540 for (i = 0; i < insn_cnt; i++, insn++) { 20541 if (BPF_CLASS(insn->code) == BPF_LDX && 20542 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 20543 insn->imm != 0)) { 20544 verbose(env, "BPF_LDX uses reserved fields\n"); 20545 return -EINVAL; 20546 } 20547 20548 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 20549 struct bpf_insn_aux_data *aux; 20550 struct bpf_map *map; 20551 int map_idx; 20552 u64 addr; 20553 u32 fd; 20554 20555 if (i == insn_cnt - 1 || insn[1].code != 0 || 20556 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 20557 insn[1].off != 0) { 20558 verbose(env, "invalid bpf_ld_imm64 insn\n"); 20559 return -EINVAL; 20560 } 20561 20562 if (insn[0].src_reg == 0) 20563 /* valid generic load 64-bit imm */ 20564 goto next_insn; 20565 20566 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 20567 aux = &env->insn_aux_data[i]; 20568 err = check_pseudo_btf_id(env, insn, aux); 20569 if (err) 20570 return err; 20571 goto next_insn; 20572 } 20573 20574 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 20575 aux = &env->insn_aux_data[i]; 20576 aux->ptr_type = PTR_TO_FUNC; 20577 goto next_insn; 20578 } 20579 20580 /* In final convert_pseudo_ld_imm64() step, this is 20581 * converted into regular 64-bit imm load insn. 20582 */ 20583 switch (insn[0].src_reg) { 20584 case BPF_PSEUDO_MAP_VALUE: 20585 case BPF_PSEUDO_MAP_IDX_VALUE: 20586 break; 20587 case BPF_PSEUDO_MAP_FD: 20588 case BPF_PSEUDO_MAP_IDX: 20589 if (insn[1].imm == 0) 20590 break; 20591 fallthrough; 20592 default: 20593 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 20594 return -EINVAL; 20595 } 20596 20597 switch (insn[0].src_reg) { 20598 case BPF_PSEUDO_MAP_IDX_VALUE: 20599 case BPF_PSEUDO_MAP_IDX: 20600 if (bpfptr_is_null(env->fd_array)) { 20601 verbose(env, "fd_idx without fd_array is invalid\n"); 20602 return -EPROTO; 20603 } 20604 if (copy_from_bpfptr_offset(&fd, env->fd_array, 20605 insn[0].imm * sizeof(fd), 20606 sizeof(fd))) 20607 return -EFAULT; 20608 break; 20609 default: 20610 fd = insn[0].imm; 20611 break; 20612 } 20613 20614 map_idx = add_used_map(env, fd); 20615 if (map_idx < 0) 20616 return map_idx; 20617 map = env->used_maps[map_idx]; 20618 20619 aux = &env->insn_aux_data[i]; 20620 aux->map_index = map_idx; 20621 20622 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 20623 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 20624 addr = (unsigned long)map; 20625 } else { 20626 u32 off = insn[1].imm; 20627 20628 if (off >= BPF_MAX_VAR_OFF) { 20629 verbose(env, "direct value offset of %u is not allowed\n", off); 20630 return -EINVAL; 20631 } 20632 20633 if (!map->ops->map_direct_value_addr) { 20634 verbose(env, "no direct value access support for this map type\n"); 20635 return -EINVAL; 20636 } 20637 20638 err = map->ops->map_direct_value_addr(map, &addr, off); 20639 if (err) { 20640 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 20641 map->value_size, off); 20642 return err; 20643 } 20644 20645 aux->map_off = off; 20646 addr += off; 20647 } 20648 20649 insn[0].imm = (u32)addr; 20650 insn[1].imm = addr >> 32; 20651 20652 next_insn: 20653 insn++; 20654 i++; 20655 continue; 20656 } 20657 20658 /* Basic sanity check before we invest more work here. */ 20659 if (!bpf_opcode_in_insntable(insn->code)) { 20660 verbose(env, "unknown opcode %02x\n", insn->code); 20661 return -EINVAL; 20662 } 20663 } 20664 20665 /* now all pseudo BPF_LD_IMM64 instructions load valid 20666 * 'struct bpf_map *' into a register instead of user map_fd. 20667 * These pointers will be used later by verifier to validate map access. 20668 */ 20669 return 0; 20670 } 20671 20672 /* drop refcnt of maps used by the rejected program */ 20673 static void release_maps(struct bpf_verifier_env *env) 20674 { 20675 __bpf_free_used_maps(env->prog->aux, env->used_maps, 20676 env->used_map_cnt); 20677 } 20678 20679 /* drop refcnt of maps used by the rejected program */ 20680 static void release_btfs(struct bpf_verifier_env *env) 20681 { 20682 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 20683 } 20684 20685 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 20686 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 20687 { 20688 struct bpf_insn *insn = env->prog->insnsi; 20689 int insn_cnt = env->prog->len; 20690 int i; 20691 20692 for (i = 0; i < insn_cnt; i++, insn++) { 20693 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 20694 continue; 20695 if (insn->src_reg == BPF_PSEUDO_FUNC) 20696 continue; 20697 insn->src_reg = 0; 20698 } 20699 } 20700 20701 /* single env->prog->insni[off] instruction was replaced with the range 20702 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 20703 * [0, off) and [off, end) to new locations, so the patched range stays zero 20704 */ 20705 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 20706 struct bpf_insn_aux_data *new_data, 20707 struct bpf_prog *new_prog, u32 off, u32 cnt) 20708 { 20709 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 20710 struct bpf_insn *insn = new_prog->insnsi; 20711 u32 old_seen = old_data[off].seen; 20712 u32 prog_len; 20713 int i; 20714 20715 /* aux info at OFF always needs adjustment, no matter fast path 20716 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 20717 * original insn at old prog. 20718 */ 20719 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 20720 20721 if (cnt == 1) 20722 return; 20723 prog_len = new_prog->len; 20724 20725 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 20726 memcpy(new_data + off + cnt - 1, old_data + off, 20727 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 20728 for (i = off; i < off + cnt - 1; i++) { 20729 /* Expand insni[off]'s seen count to the patched range. */ 20730 new_data[i].seen = old_seen; 20731 new_data[i].zext_dst = insn_has_def32(env, insn + i); 20732 } 20733 env->insn_aux_data = new_data; 20734 vfree(old_data); 20735 } 20736 20737 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 20738 { 20739 int i; 20740 20741 if (len == 1) 20742 return; 20743 /* NOTE: fake 'exit' subprog should be updated as well. */ 20744 for (i = 0; i <= env->subprog_cnt; i++) { 20745 if (env->subprog_info[i].start <= off) 20746 continue; 20747 env->subprog_info[i].start += len - 1; 20748 } 20749 } 20750 20751 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 20752 { 20753 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 20754 int i, sz = prog->aux->size_poke_tab; 20755 struct bpf_jit_poke_descriptor *desc; 20756 20757 for (i = 0; i < sz; i++) { 20758 desc = &tab[i]; 20759 if (desc->insn_idx <= off) 20760 continue; 20761 desc->insn_idx += len - 1; 20762 } 20763 } 20764 20765 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 20766 const struct bpf_insn *patch, u32 len) 20767 { 20768 struct bpf_prog *new_prog; 20769 struct bpf_insn_aux_data *new_data = NULL; 20770 20771 if (len > 1) { 20772 new_data = vzalloc(array_size(env->prog->len + len - 1, 20773 sizeof(struct bpf_insn_aux_data))); 20774 if (!new_data) 20775 return NULL; 20776 } 20777 20778 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 20779 if (IS_ERR(new_prog)) { 20780 if (PTR_ERR(new_prog) == -ERANGE) 20781 verbose(env, 20782 "insn %d cannot be patched due to 16-bit range\n", 20783 env->insn_aux_data[off].orig_idx); 20784 vfree(new_data); 20785 return NULL; 20786 } 20787 adjust_insn_aux_data(env, new_data, new_prog, off, len); 20788 adjust_subprog_starts(env, off, len); 20789 adjust_poke_descs(new_prog, off, len); 20790 return new_prog; 20791 } 20792 20793 /* 20794 * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the 20795 * jump offset by 'delta'. 20796 */ 20797 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta) 20798 { 20799 struct bpf_insn *insn = prog->insnsi; 20800 u32 insn_cnt = prog->len, i; 20801 s32 imm; 20802 s16 off; 20803 20804 for (i = 0; i < insn_cnt; i++, insn++) { 20805 u8 code = insn->code; 20806 20807 if (tgt_idx <= i && i < tgt_idx + delta) 20808 continue; 20809 20810 if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) || 20811 BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT) 20812 continue; 20813 20814 if (insn->code == (BPF_JMP32 | BPF_JA)) { 20815 if (i + 1 + insn->imm != tgt_idx) 20816 continue; 20817 if (check_add_overflow(insn->imm, delta, &imm)) 20818 return -ERANGE; 20819 insn->imm = imm; 20820 } else { 20821 if (i + 1 + insn->off != tgt_idx) 20822 continue; 20823 if (check_add_overflow(insn->off, delta, &off)) 20824 return -ERANGE; 20825 insn->off = off; 20826 } 20827 } 20828 return 0; 20829 } 20830 20831 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 20832 u32 off, u32 cnt) 20833 { 20834 int i, j; 20835 20836 /* find first prog starting at or after off (first to remove) */ 20837 for (i = 0; i < env->subprog_cnt; i++) 20838 if (env->subprog_info[i].start >= off) 20839 break; 20840 /* find first prog starting at or after off + cnt (first to stay) */ 20841 for (j = i; j < env->subprog_cnt; j++) 20842 if (env->subprog_info[j].start >= off + cnt) 20843 break; 20844 /* if j doesn't start exactly at off + cnt, we are just removing 20845 * the front of previous prog 20846 */ 20847 if (env->subprog_info[j].start != off + cnt) 20848 j--; 20849 20850 if (j > i) { 20851 struct bpf_prog_aux *aux = env->prog->aux; 20852 int move; 20853 20854 /* move fake 'exit' subprog as well */ 20855 move = env->subprog_cnt + 1 - j; 20856 20857 memmove(env->subprog_info + i, 20858 env->subprog_info + j, 20859 sizeof(*env->subprog_info) * move); 20860 env->subprog_cnt -= j - i; 20861 20862 /* remove func_info */ 20863 if (aux->func_info) { 20864 move = aux->func_info_cnt - j; 20865 20866 memmove(aux->func_info + i, 20867 aux->func_info + j, 20868 sizeof(*aux->func_info) * move); 20869 aux->func_info_cnt -= j - i; 20870 /* func_info->insn_off is set after all code rewrites, 20871 * in adjust_btf_func() - no need to adjust 20872 */ 20873 } 20874 } else { 20875 /* convert i from "first prog to remove" to "first to adjust" */ 20876 if (env->subprog_info[i].start == off) 20877 i++; 20878 } 20879 20880 /* update fake 'exit' subprog as well */ 20881 for (; i <= env->subprog_cnt; i++) 20882 env->subprog_info[i].start -= cnt; 20883 20884 return 0; 20885 } 20886 20887 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 20888 u32 cnt) 20889 { 20890 struct bpf_prog *prog = env->prog; 20891 u32 i, l_off, l_cnt, nr_linfo; 20892 struct bpf_line_info *linfo; 20893 20894 nr_linfo = prog->aux->nr_linfo; 20895 if (!nr_linfo) 20896 return 0; 20897 20898 linfo = prog->aux->linfo; 20899 20900 /* find first line info to remove, count lines to be removed */ 20901 for (i = 0; i < nr_linfo; i++) 20902 if (linfo[i].insn_off >= off) 20903 break; 20904 20905 l_off = i; 20906 l_cnt = 0; 20907 for (; i < nr_linfo; i++) 20908 if (linfo[i].insn_off < off + cnt) 20909 l_cnt++; 20910 else 20911 break; 20912 20913 /* First live insn doesn't match first live linfo, it needs to "inherit" 20914 * last removed linfo. prog is already modified, so prog->len == off 20915 * means no live instructions after (tail of the program was removed). 20916 */ 20917 if (prog->len != off && l_cnt && 20918 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 20919 l_cnt--; 20920 linfo[--i].insn_off = off + cnt; 20921 } 20922 20923 /* remove the line info which refer to the removed instructions */ 20924 if (l_cnt) { 20925 memmove(linfo + l_off, linfo + i, 20926 sizeof(*linfo) * (nr_linfo - i)); 20927 20928 prog->aux->nr_linfo -= l_cnt; 20929 nr_linfo = prog->aux->nr_linfo; 20930 } 20931 20932 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 20933 for (i = l_off; i < nr_linfo; i++) 20934 linfo[i].insn_off -= cnt; 20935 20936 /* fix up all subprogs (incl. 'exit') which start >= off */ 20937 for (i = 0; i <= env->subprog_cnt; i++) 20938 if (env->subprog_info[i].linfo_idx > l_off) { 20939 /* program may have started in the removed region but 20940 * may not be fully removed 20941 */ 20942 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 20943 env->subprog_info[i].linfo_idx -= l_cnt; 20944 else 20945 env->subprog_info[i].linfo_idx = l_off; 20946 } 20947 20948 return 0; 20949 } 20950 20951 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 20952 { 20953 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 20954 unsigned int orig_prog_len = env->prog->len; 20955 int err; 20956 20957 if (bpf_prog_is_offloaded(env->prog->aux)) 20958 bpf_prog_offload_remove_insns(env, off, cnt); 20959 20960 err = bpf_remove_insns(env->prog, off, cnt); 20961 if (err) 20962 return err; 20963 20964 err = adjust_subprog_starts_after_remove(env, off, cnt); 20965 if (err) 20966 return err; 20967 20968 err = bpf_adj_linfo_after_remove(env, off, cnt); 20969 if (err) 20970 return err; 20971 20972 memmove(aux_data + off, aux_data + off + cnt, 20973 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 20974 20975 return 0; 20976 } 20977 20978 /* The verifier does more data flow analysis than llvm and will not 20979 * explore branches that are dead at run time. Malicious programs can 20980 * have dead code too. Therefore replace all dead at-run-time code 20981 * with 'ja -1'. 20982 * 20983 * Just nops are not optimal, e.g. if they would sit at the end of the 20984 * program and through another bug we would manage to jump there, then 20985 * we'd execute beyond program memory otherwise. Returning exception 20986 * code also wouldn't work since we can have subprogs where the dead 20987 * code could be located. 20988 */ 20989 static void sanitize_dead_code(struct bpf_verifier_env *env) 20990 { 20991 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 20992 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 20993 struct bpf_insn *insn = env->prog->insnsi; 20994 const int insn_cnt = env->prog->len; 20995 int i; 20996 20997 for (i = 0; i < insn_cnt; i++) { 20998 if (aux_data[i].seen) 20999 continue; 21000 memcpy(insn + i, &trap, sizeof(trap)); 21001 aux_data[i].zext_dst = false; 21002 } 21003 } 21004 21005 static bool insn_is_cond_jump(u8 code) 21006 { 21007 u8 op; 21008 21009 op = BPF_OP(code); 21010 if (BPF_CLASS(code) == BPF_JMP32) 21011 return op != BPF_JA; 21012 21013 if (BPF_CLASS(code) != BPF_JMP) 21014 return false; 21015 21016 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 21017 } 21018 21019 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 21020 { 21021 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 21022 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 21023 struct bpf_insn *insn = env->prog->insnsi; 21024 const int insn_cnt = env->prog->len; 21025 int i; 21026 21027 for (i = 0; i < insn_cnt; i++, insn++) { 21028 if (!insn_is_cond_jump(insn->code)) 21029 continue; 21030 21031 if (!aux_data[i + 1].seen) 21032 ja.off = insn->off; 21033 else if (!aux_data[i + 1 + insn->off].seen) 21034 ja.off = 0; 21035 else 21036 continue; 21037 21038 if (bpf_prog_is_offloaded(env->prog->aux)) 21039 bpf_prog_offload_replace_insn(env, i, &ja); 21040 21041 memcpy(insn, &ja, sizeof(ja)); 21042 } 21043 } 21044 21045 static int opt_remove_dead_code(struct bpf_verifier_env *env) 21046 { 21047 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 21048 int insn_cnt = env->prog->len; 21049 int i, err; 21050 21051 for (i = 0; i < insn_cnt; i++) { 21052 int j; 21053 21054 j = 0; 21055 while (i + j < insn_cnt && !aux_data[i + j].seen) 21056 j++; 21057 if (!j) 21058 continue; 21059 21060 err = verifier_remove_insns(env, i, j); 21061 if (err) 21062 return err; 21063 insn_cnt = env->prog->len; 21064 } 21065 21066 return 0; 21067 } 21068 21069 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 21070 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0); 21071 21072 static int opt_remove_nops(struct bpf_verifier_env *env) 21073 { 21074 struct bpf_insn *insn = env->prog->insnsi; 21075 int insn_cnt = env->prog->len; 21076 bool is_may_goto_0, is_ja; 21077 int i, err; 21078 21079 for (i = 0; i < insn_cnt; i++) { 21080 is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0)); 21081 is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP)); 21082 21083 if (!is_may_goto_0 && !is_ja) 21084 continue; 21085 21086 err = verifier_remove_insns(env, i, 1); 21087 if (err) 21088 return err; 21089 insn_cnt--; 21090 /* Go back one insn to catch may_goto +1; may_goto +0 sequence */ 21091 i -= (is_may_goto_0 && i > 0) ? 2 : 1; 21092 } 21093 21094 return 0; 21095 } 21096 21097 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 21098 const union bpf_attr *attr) 21099 { 21100 struct bpf_insn *patch; 21101 /* use env->insn_buf as two independent buffers */ 21102 struct bpf_insn *zext_patch = env->insn_buf; 21103 struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2]; 21104 struct bpf_insn_aux_data *aux = env->insn_aux_data; 21105 int i, patch_len, delta = 0, len = env->prog->len; 21106 struct bpf_insn *insns = env->prog->insnsi; 21107 struct bpf_prog *new_prog; 21108 bool rnd_hi32; 21109 21110 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 21111 zext_patch[1] = BPF_ZEXT_REG(0); 21112 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 21113 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 21114 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 21115 for (i = 0; i < len; i++) { 21116 int adj_idx = i + delta; 21117 struct bpf_insn insn; 21118 int load_reg; 21119 21120 insn = insns[adj_idx]; 21121 load_reg = insn_def_regno(&insn); 21122 if (!aux[adj_idx].zext_dst) { 21123 u8 code, class; 21124 u32 imm_rnd; 21125 21126 if (!rnd_hi32) 21127 continue; 21128 21129 code = insn.code; 21130 class = BPF_CLASS(code); 21131 if (load_reg == -1) 21132 continue; 21133 21134 /* NOTE: arg "reg" (the fourth one) is only used for 21135 * BPF_STX + SRC_OP, so it is safe to pass NULL 21136 * here. 21137 */ 21138 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 21139 if (class == BPF_LD && 21140 BPF_MODE(code) == BPF_IMM) 21141 i++; 21142 continue; 21143 } 21144 21145 /* ctx load could be transformed into wider load. */ 21146 if (class == BPF_LDX && 21147 aux[adj_idx].ptr_type == PTR_TO_CTX) 21148 continue; 21149 21150 imm_rnd = get_random_u32(); 21151 rnd_hi32_patch[0] = insn; 21152 rnd_hi32_patch[1].imm = imm_rnd; 21153 rnd_hi32_patch[3].dst_reg = load_reg; 21154 patch = rnd_hi32_patch; 21155 patch_len = 4; 21156 goto apply_patch_buffer; 21157 } 21158 21159 /* Add in an zero-extend instruction if a) the JIT has requested 21160 * it or b) it's a CMPXCHG. 21161 * 21162 * The latter is because: BPF_CMPXCHG always loads a value into 21163 * R0, therefore always zero-extends. However some archs' 21164 * equivalent instruction only does this load when the 21165 * comparison is successful. This detail of CMPXCHG is 21166 * orthogonal to the general zero-extension behaviour of the 21167 * CPU, so it's treated independently of bpf_jit_needs_zext. 21168 */ 21169 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 21170 continue; 21171 21172 /* Zero-extension is done by the caller. */ 21173 if (bpf_pseudo_kfunc_call(&insn)) 21174 continue; 21175 21176 if (verifier_bug_if(load_reg == -1, env, 21177 "zext_dst is set, but no reg is defined")) 21178 return -EFAULT; 21179 21180 zext_patch[0] = insn; 21181 zext_patch[1].dst_reg = load_reg; 21182 zext_patch[1].src_reg = load_reg; 21183 patch = zext_patch; 21184 patch_len = 2; 21185 apply_patch_buffer: 21186 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 21187 if (!new_prog) 21188 return -ENOMEM; 21189 env->prog = new_prog; 21190 insns = new_prog->insnsi; 21191 aux = env->insn_aux_data; 21192 delta += patch_len - 1; 21193 } 21194 21195 return 0; 21196 } 21197 21198 /* convert load instructions that access fields of a context type into a 21199 * sequence of instructions that access fields of the underlying structure: 21200 * struct __sk_buff -> struct sk_buff 21201 * struct bpf_sock_ops -> struct sock 21202 */ 21203 static int convert_ctx_accesses(struct bpf_verifier_env *env) 21204 { 21205 struct bpf_subprog_info *subprogs = env->subprog_info; 21206 const struct bpf_verifier_ops *ops = env->ops; 21207 int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0; 21208 const int insn_cnt = env->prog->len; 21209 struct bpf_insn *epilogue_buf = env->epilogue_buf; 21210 struct bpf_insn *insn_buf = env->insn_buf; 21211 struct bpf_insn *insn; 21212 u32 target_size, size_default, off; 21213 struct bpf_prog *new_prog; 21214 enum bpf_access_type type; 21215 bool is_narrower_load; 21216 int epilogue_idx = 0; 21217 21218 if (ops->gen_epilogue) { 21219 epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog, 21220 -(subprogs[0].stack_depth + 8)); 21221 if (epilogue_cnt >= INSN_BUF_SIZE) { 21222 verifier_bug(env, "epilogue is too long"); 21223 return -EFAULT; 21224 } else if (epilogue_cnt) { 21225 /* Save the ARG_PTR_TO_CTX for the epilogue to use */ 21226 cnt = 0; 21227 subprogs[0].stack_depth += 8; 21228 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1, 21229 -subprogs[0].stack_depth); 21230 insn_buf[cnt++] = env->prog->insnsi[0]; 21231 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 21232 if (!new_prog) 21233 return -ENOMEM; 21234 env->prog = new_prog; 21235 delta += cnt - 1; 21236 21237 ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1); 21238 if (ret < 0) 21239 return ret; 21240 } 21241 } 21242 21243 if (ops->gen_prologue || env->seen_direct_write) { 21244 if (!ops->gen_prologue) { 21245 verifier_bug(env, "gen_prologue is null"); 21246 return -EFAULT; 21247 } 21248 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 21249 env->prog); 21250 if (cnt >= INSN_BUF_SIZE) { 21251 verifier_bug(env, "prologue is too long"); 21252 return -EFAULT; 21253 } else if (cnt) { 21254 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 21255 if (!new_prog) 21256 return -ENOMEM; 21257 21258 env->prog = new_prog; 21259 delta += cnt - 1; 21260 21261 ret = add_kfunc_in_insns(env, insn_buf, cnt - 1); 21262 if (ret < 0) 21263 return ret; 21264 } 21265 } 21266 21267 if (delta) 21268 WARN_ON(adjust_jmp_off(env->prog, 0, delta)); 21269 21270 if (bpf_prog_is_offloaded(env->prog->aux)) 21271 return 0; 21272 21273 insn = env->prog->insnsi + delta; 21274 21275 for (i = 0; i < insn_cnt; i++, insn++) { 21276 bpf_convert_ctx_access_t convert_ctx_access; 21277 u8 mode; 21278 21279 if (env->insn_aux_data[i + delta].nospec) { 21280 WARN_ON_ONCE(env->insn_aux_data[i + delta].alu_state); 21281 struct bpf_insn *patch = insn_buf; 21282 21283 *patch++ = BPF_ST_NOSPEC(); 21284 *patch++ = *insn; 21285 cnt = patch - insn_buf; 21286 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21287 if (!new_prog) 21288 return -ENOMEM; 21289 21290 delta += cnt - 1; 21291 env->prog = new_prog; 21292 insn = new_prog->insnsi + i + delta; 21293 /* This can not be easily merged with the 21294 * nospec_result-case, because an insn may require a 21295 * nospec before and after itself. Therefore also do not 21296 * 'continue' here but potentially apply further 21297 * patching to insn. *insn should equal patch[1] now. 21298 */ 21299 } 21300 21301 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 21302 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 21303 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 21304 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 21305 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 21306 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 21307 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 21308 type = BPF_READ; 21309 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 21310 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 21311 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 21312 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 21313 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 21314 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 21315 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 21316 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 21317 type = BPF_WRITE; 21318 } else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) || 21319 insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) || 21320 insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) || 21321 insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) && 21322 env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) { 21323 insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code); 21324 env->prog->aux->num_exentries++; 21325 continue; 21326 } else if (insn->code == (BPF_JMP | BPF_EXIT) && 21327 epilogue_cnt && 21328 i + delta < subprogs[1].start) { 21329 /* Generate epilogue for the main prog */ 21330 if (epilogue_idx) { 21331 /* jump back to the earlier generated epilogue */ 21332 insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1); 21333 cnt = 1; 21334 } else { 21335 memcpy(insn_buf, epilogue_buf, 21336 epilogue_cnt * sizeof(*epilogue_buf)); 21337 cnt = epilogue_cnt; 21338 /* epilogue_idx cannot be 0. It must have at 21339 * least one ctx ptr saving insn before the 21340 * epilogue. 21341 */ 21342 epilogue_idx = i + delta; 21343 } 21344 goto patch_insn_buf; 21345 } else { 21346 continue; 21347 } 21348 21349 if (type == BPF_WRITE && 21350 env->insn_aux_data[i + delta].nospec_result) { 21351 /* nospec_result is only used to mitigate Spectre v4 and 21352 * to limit verification-time for Spectre v1. 21353 */ 21354 struct bpf_insn *patch = insn_buf; 21355 21356 *patch++ = *insn; 21357 *patch++ = BPF_ST_NOSPEC(); 21358 cnt = patch - insn_buf; 21359 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21360 if (!new_prog) 21361 return -ENOMEM; 21362 21363 delta += cnt - 1; 21364 env->prog = new_prog; 21365 insn = new_prog->insnsi + i + delta; 21366 continue; 21367 } 21368 21369 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 21370 case PTR_TO_CTX: 21371 if (!ops->convert_ctx_access) 21372 continue; 21373 convert_ctx_access = ops->convert_ctx_access; 21374 break; 21375 case PTR_TO_SOCKET: 21376 case PTR_TO_SOCK_COMMON: 21377 convert_ctx_access = bpf_sock_convert_ctx_access; 21378 break; 21379 case PTR_TO_TCP_SOCK: 21380 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 21381 break; 21382 case PTR_TO_XDP_SOCK: 21383 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 21384 break; 21385 case PTR_TO_BTF_ID: 21386 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 21387 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 21388 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 21389 * be said once it is marked PTR_UNTRUSTED, hence we must handle 21390 * any faults for loads into such types. BPF_WRITE is disallowed 21391 * for this case. 21392 */ 21393 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 21394 case PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED: 21395 if (type == BPF_READ) { 21396 if (BPF_MODE(insn->code) == BPF_MEM) 21397 insn->code = BPF_LDX | BPF_PROBE_MEM | 21398 BPF_SIZE((insn)->code); 21399 else 21400 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 21401 BPF_SIZE((insn)->code); 21402 env->prog->aux->num_exentries++; 21403 } 21404 continue; 21405 case PTR_TO_ARENA: 21406 if (BPF_MODE(insn->code) == BPF_MEMSX) { 21407 verbose(env, "sign extending loads from arena are not supported yet\n"); 21408 return -EOPNOTSUPP; 21409 } 21410 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 21411 env->prog->aux->num_exentries++; 21412 continue; 21413 default: 21414 continue; 21415 } 21416 21417 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 21418 size = BPF_LDST_BYTES(insn); 21419 mode = BPF_MODE(insn->code); 21420 21421 /* If the read access is a narrower load of the field, 21422 * convert to a 4/8-byte load, to minimum program type specific 21423 * convert_ctx_access changes. If conversion is successful, 21424 * we will apply proper mask to the result. 21425 */ 21426 is_narrower_load = size < ctx_field_size; 21427 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 21428 off = insn->off; 21429 if (is_narrower_load) { 21430 u8 size_code; 21431 21432 if (type == BPF_WRITE) { 21433 verifier_bug(env, "narrow ctx access misconfigured"); 21434 return -EFAULT; 21435 } 21436 21437 size_code = BPF_H; 21438 if (ctx_field_size == 4) 21439 size_code = BPF_W; 21440 else if (ctx_field_size == 8) 21441 size_code = BPF_DW; 21442 21443 insn->off = off & ~(size_default - 1); 21444 insn->code = BPF_LDX | BPF_MEM | size_code; 21445 } 21446 21447 target_size = 0; 21448 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 21449 &target_size); 21450 if (cnt == 0 || cnt >= INSN_BUF_SIZE || 21451 (ctx_field_size && !target_size)) { 21452 verifier_bug(env, "error during ctx access conversion (%d)", cnt); 21453 return -EFAULT; 21454 } 21455 21456 if (is_narrower_load && size < target_size) { 21457 u8 shift = bpf_ctx_narrow_access_offset( 21458 off, size, size_default) * 8; 21459 if (shift && cnt + 1 >= INSN_BUF_SIZE) { 21460 verifier_bug(env, "narrow ctx load misconfigured"); 21461 return -EFAULT; 21462 } 21463 if (ctx_field_size <= 4) { 21464 if (shift) 21465 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 21466 insn->dst_reg, 21467 shift); 21468 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 21469 (1 << size * 8) - 1); 21470 } else { 21471 if (shift) 21472 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 21473 insn->dst_reg, 21474 shift); 21475 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 21476 (1ULL << size * 8) - 1); 21477 } 21478 } 21479 if (mode == BPF_MEMSX) 21480 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 21481 insn->dst_reg, insn->dst_reg, 21482 size * 8, 0); 21483 21484 patch_insn_buf: 21485 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 21486 if (!new_prog) 21487 return -ENOMEM; 21488 21489 delta += cnt - 1; 21490 21491 /* keep walking new program and skip insns we just inserted */ 21492 env->prog = new_prog; 21493 insn = new_prog->insnsi + i + delta; 21494 } 21495 21496 return 0; 21497 } 21498 21499 static int jit_subprogs(struct bpf_verifier_env *env) 21500 { 21501 struct bpf_prog *prog = env->prog, **func, *tmp; 21502 int i, j, subprog_start, subprog_end = 0, len, subprog; 21503 struct bpf_map *map_ptr; 21504 struct bpf_insn *insn; 21505 void *old_bpf_func; 21506 int err, num_exentries; 21507 21508 if (env->subprog_cnt <= 1) 21509 return 0; 21510 21511 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21512 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 21513 continue; 21514 21515 /* Upon error here we cannot fall back to interpreter but 21516 * need a hard reject of the program. Thus -EFAULT is 21517 * propagated in any case. 21518 */ 21519 subprog = find_subprog(env, i + insn->imm + 1); 21520 if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d", 21521 i + insn->imm + 1)) 21522 return -EFAULT; 21523 /* temporarily remember subprog id inside insn instead of 21524 * aux_data, since next loop will split up all insns into funcs 21525 */ 21526 insn->off = subprog; 21527 /* remember original imm in case JIT fails and fallback 21528 * to interpreter will be needed 21529 */ 21530 env->insn_aux_data[i].call_imm = insn->imm; 21531 /* point imm to __bpf_call_base+1 from JITs point of view */ 21532 insn->imm = 1; 21533 if (bpf_pseudo_func(insn)) { 21534 #if defined(MODULES_VADDR) 21535 u64 addr = MODULES_VADDR; 21536 #else 21537 u64 addr = VMALLOC_START; 21538 #endif 21539 /* jit (e.g. x86_64) may emit fewer instructions 21540 * if it learns a u32 imm is the same as a u64 imm. 21541 * Set close enough to possible prog address. 21542 */ 21543 insn[0].imm = (u32)addr; 21544 insn[1].imm = addr >> 32; 21545 } 21546 } 21547 21548 err = bpf_prog_alloc_jited_linfo(prog); 21549 if (err) 21550 goto out_undo_insn; 21551 21552 err = -ENOMEM; 21553 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 21554 if (!func) 21555 goto out_undo_insn; 21556 21557 for (i = 0; i < env->subprog_cnt; i++) { 21558 subprog_start = subprog_end; 21559 subprog_end = env->subprog_info[i + 1].start; 21560 21561 len = subprog_end - subprog_start; 21562 /* bpf_prog_run() doesn't call subprogs directly, 21563 * hence main prog stats include the runtime of subprogs. 21564 * subprogs don't have IDs and not reachable via prog_get_next_id 21565 * func[i]->stats will never be accessed and stays NULL 21566 */ 21567 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 21568 if (!func[i]) 21569 goto out_free; 21570 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 21571 len * sizeof(struct bpf_insn)); 21572 func[i]->type = prog->type; 21573 func[i]->len = len; 21574 if (bpf_prog_calc_tag(func[i])) 21575 goto out_free; 21576 func[i]->is_func = 1; 21577 func[i]->sleepable = prog->sleepable; 21578 func[i]->aux->func_idx = i; 21579 /* Below members will be freed only at prog->aux */ 21580 func[i]->aux->btf = prog->aux->btf; 21581 func[i]->aux->func_info = prog->aux->func_info; 21582 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 21583 func[i]->aux->poke_tab = prog->aux->poke_tab; 21584 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 21585 21586 for (j = 0; j < prog->aux->size_poke_tab; j++) { 21587 struct bpf_jit_poke_descriptor *poke; 21588 21589 poke = &prog->aux->poke_tab[j]; 21590 if (poke->insn_idx < subprog_end && 21591 poke->insn_idx >= subprog_start) 21592 poke->aux = func[i]->aux; 21593 } 21594 21595 func[i]->aux->name[0] = 'F'; 21596 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 21597 if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) 21598 func[i]->aux->jits_use_priv_stack = true; 21599 21600 func[i]->jit_requested = 1; 21601 func[i]->blinding_requested = prog->blinding_requested; 21602 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 21603 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 21604 func[i]->aux->linfo = prog->aux->linfo; 21605 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 21606 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 21607 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 21608 func[i]->aux->arena = prog->aux->arena; 21609 num_exentries = 0; 21610 insn = func[i]->insnsi; 21611 for (j = 0; j < func[i]->len; j++, insn++) { 21612 if (BPF_CLASS(insn->code) == BPF_LDX && 21613 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 21614 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 21615 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 21616 num_exentries++; 21617 if ((BPF_CLASS(insn->code) == BPF_STX || 21618 BPF_CLASS(insn->code) == BPF_ST) && 21619 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 21620 num_exentries++; 21621 if (BPF_CLASS(insn->code) == BPF_STX && 21622 BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) 21623 num_exentries++; 21624 } 21625 func[i]->aux->num_exentries = num_exentries; 21626 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 21627 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 21628 func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data; 21629 func[i]->aux->might_sleep = env->subprog_info[i].might_sleep; 21630 if (!i) 21631 func[i]->aux->exception_boundary = env->seen_exception; 21632 func[i] = bpf_int_jit_compile(func[i]); 21633 if (!func[i]->jited) { 21634 err = -ENOTSUPP; 21635 goto out_free; 21636 } 21637 cond_resched(); 21638 } 21639 21640 /* at this point all bpf functions were successfully JITed 21641 * now populate all bpf_calls with correct addresses and 21642 * run last pass of JIT 21643 */ 21644 for (i = 0; i < env->subprog_cnt; i++) { 21645 insn = func[i]->insnsi; 21646 for (j = 0; j < func[i]->len; j++, insn++) { 21647 if (bpf_pseudo_func(insn)) { 21648 subprog = insn->off; 21649 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 21650 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 21651 continue; 21652 } 21653 if (!bpf_pseudo_call(insn)) 21654 continue; 21655 subprog = insn->off; 21656 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 21657 } 21658 21659 /* we use the aux data to keep a list of the start addresses 21660 * of the JITed images for each function in the program 21661 * 21662 * for some architectures, such as powerpc64, the imm field 21663 * might not be large enough to hold the offset of the start 21664 * address of the callee's JITed image from __bpf_call_base 21665 * 21666 * in such cases, we can lookup the start address of a callee 21667 * by using its subprog id, available from the off field of 21668 * the call instruction, as an index for this list 21669 */ 21670 func[i]->aux->func = func; 21671 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 21672 func[i]->aux->real_func_cnt = env->subprog_cnt; 21673 } 21674 for (i = 0; i < env->subprog_cnt; i++) { 21675 old_bpf_func = func[i]->bpf_func; 21676 tmp = bpf_int_jit_compile(func[i]); 21677 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 21678 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 21679 err = -ENOTSUPP; 21680 goto out_free; 21681 } 21682 cond_resched(); 21683 } 21684 21685 /* finally lock prog and jit images for all functions and 21686 * populate kallsysm. Begin at the first subprogram, since 21687 * bpf_prog_load will add the kallsyms for the main program. 21688 */ 21689 for (i = 1; i < env->subprog_cnt; i++) { 21690 err = bpf_prog_lock_ro(func[i]); 21691 if (err) 21692 goto out_free; 21693 } 21694 21695 for (i = 1; i < env->subprog_cnt; i++) 21696 bpf_prog_kallsyms_add(func[i]); 21697 21698 /* Last step: make now unused interpreter insns from main 21699 * prog consistent for later dump requests, so they can 21700 * later look the same as if they were interpreted only. 21701 */ 21702 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21703 if (bpf_pseudo_func(insn)) { 21704 insn[0].imm = env->insn_aux_data[i].call_imm; 21705 insn[1].imm = insn->off; 21706 insn->off = 0; 21707 continue; 21708 } 21709 if (!bpf_pseudo_call(insn)) 21710 continue; 21711 insn->off = env->insn_aux_data[i].call_imm; 21712 subprog = find_subprog(env, i + insn->off + 1); 21713 insn->imm = subprog; 21714 } 21715 21716 prog->jited = 1; 21717 prog->bpf_func = func[0]->bpf_func; 21718 prog->jited_len = func[0]->jited_len; 21719 prog->aux->extable = func[0]->aux->extable; 21720 prog->aux->num_exentries = func[0]->aux->num_exentries; 21721 prog->aux->func = func; 21722 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 21723 prog->aux->real_func_cnt = env->subprog_cnt; 21724 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 21725 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 21726 bpf_prog_jit_attempt_done(prog); 21727 return 0; 21728 out_free: 21729 /* We failed JIT'ing, so at this point we need to unregister poke 21730 * descriptors from subprogs, so that kernel is not attempting to 21731 * patch it anymore as we're freeing the subprog JIT memory. 21732 */ 21733 for (i = 0; i < prog->aux->size_poke_tab; i++) { 21734 map_ptr = prog->aux->poke_tab[i].tail_call.map; 21735 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 21736 } 21737 /* At this point we're guaranteed that poke descriptors are not 21738 * live anymore. We can just unlink its descriptor table as it's 21739 * released with the main prog. 21740 */ 21741 for (i = 0; i < env->subprog_cnt; i++) { 21742 if (!func[i]) 21743 continue; 21744 func[i]->aux->poke_tab = NULL; 21745 bpf_jit_free(func[i]); 21746 } 21747 kfree(func); 21748 out_undo_insn: 21749 /* cleanup main prog to be interpreted */ 21750 prog->jit_requested = 0; 21751 prog->blinding_requested = 0; 21752 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 21753 if (!bpf_pseudo_call(insn)) 21754 continue; 21755 insn->off = 0; 21756 insn->imm = env->insn_aux_data[i].call_imm; 21757 } 21758 bpf_prog_jit_attempt_done(prog); 21759 return err; 21760 } 21761 21762 static int fixup_call_args(struct bpf_verifier_env *env) 21763 { 21764 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 21765 struct bpf_prog *prog = env->prog; 21766 struct bpf_insn *insn = prog->insnsi; 21767 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 21768 int i, depth; 21769 #endif 21770 int err = 0; 21771 21772 if (env->prog->jit_requested && 21773 !bpf_prog_is_offloaded(env->prog->aux)) { 21774 err = jit_subprogs(env); 21775 if (err == 0) 21776 return 0; 21777 if (err == -EFAULT) 21778 return err; 21779 } 21780 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 21781 if (has_kfunc_call) { 21782 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 21783 return -EINVAL; 21784 } 21785 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 21786 /* When JIT fails the progs with bpf2bpf calls and tail_calls 21787 * have to be rejected, since interpreter doesn't support them yet. 21788 */ 21789 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 21790 return -EINVAL; 21791 } 21792 for (i = 0; i < prog->len; i++, insn++) { 21793 if (bpf_pseudo_func(insn)) { 21794 /* When JIT fails the progs with callback calls 21795 * have to be rejected, since interpreter doesn't support them yet. 21796 */ 21797 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 21798 return -EINVAL; 21799 } 21800 21801 if (!bpf_pseudo_call(insn)) 21802 continue; 21803 depth = get_callee_stack_depth(env, insn, i); 21804 if (depth < 0) 21805 return depth; 21806 bpf_patch_call_args(insn, depth); 21807 } 21808 err = 0; 21809 #endif 21810 return err; 21811 } 21812 21813 /* replace a generic kfunc with a specialized version if necessary */ 21814 static void specialize_kfunc(struct bpf_verifier_env *env, 21815 u32 func_id, u16 offset, unsigned long *addr) 21816 { 21817 struct bpf_prog *prog = env->prog; 21818 bool seen_direct_write; 21819 void *xdp_kfunc; 21820 bool is_rdonly; 21821 21822 if (bpf_dev_bound_kfunc_id(func_id)) { 21823 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 21824 if (xdp_kfunc) { 21825 *addr = (unsigned long)xdp_kfunc; 21826 return; 21827 } 21828 /* fallback to default kfunc when not supported by netdev */ 21829 } 21830 21831 if (offset) 21832 return; 21833 21834 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 21835 seen_direct_write = env->seen_direct_write; 21836 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 21837 21838 if (is_rdonly) 21839 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 21840 21841 /* restore env->seen_direct_write to its original value, since 21842 * may_access_direct_pkt_data mutates it 21843 */ 21844 env->seen_direct_write = seen_direct_write; 21845 } 21846 21847 if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] && 21848 bpf_lsm_has_d_inode_locked(prog)) 21849 *addr = (unsigned long)bpf_set_dentry_xattr_locked; 21850 21851 if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] && 21852 bpf_lsm_has_d_inode_locked(prog)) 21853 *addr = (unsigned long)bpf_remove_dentry_xattr_locked; 21854 } 21855 21856 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 21857 u16 struct_meta_reg, 21858 u16 node_offset_reg, 21859 struct bpf_insn *insn, 21860 struct bpf_insn *insn_buf, 21861 int *cnt) 21862 { 21863 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 21864 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 21865 21866 insn_buf[0] = addr[0]; 21867 insn_buf[1] = addr[1]; 21868 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 21869 insn_buf[3] = *insn; 21870 *cnt = 4; 21871 } 21872 21873 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 21874 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 21875 { 21876 const struct bpf_kfunc_desc *desc; 21877 21878 if (!insn->imm) { 21879 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 21880 return -EINVAL; 21881 } 21882 21883 *cnt = 0; 21884 21885 /* insn->imm has the btf func_id. Replace it with an offset relative to 21886 * __bpf_call_base, unless the JIT needs to call functions that are 21887 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 21888 */ 21889 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 21890 if (!desc) { 21891 verifier_bug(env, "kernel function descriptor not found for func_id %u", 21892 insn->imm); 21893 return -EFAULT; 21894 } 21895 21896 if (!bpf_jit_supports_far_kfunc_call()) 21897 insn->imm = BPF_CALL_IMM(desc->addr); 21898 if (insn->off) 21899 return 0; 21900 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 21901 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 21902 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21903 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 21904 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 21905 21906 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 21907 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 21908 insn_idx); 21909 return -EFAULT; 21910 } 21911 21912 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 21913 insn_buf[1] = addr[0]; 21914 insn_buf[2] = addr[1]; 21915 insn_buf[3] = *insn; 21916 *cnt = 4; 21917 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 21918 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 21919 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 21920 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21921 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 21922 21923 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 21924 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 21925 insn_idx); 21926 return -EFAULT; 21927 } 21928 21929 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 21930 !kptr_struct_meta) { 21931 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 21932 insn_idx); 21933 return -EFAULT; 21934 } 21935 21936 insn_buf[0] = addr[0]; 21937 insn_buf[1] = addr[1]; 21938 insn_buf[2] = *insn; 21939 *cnt = 3; 21940 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 21941 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 21942 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 21943 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 21944 int struct_meta_reg = BPF_REG_3; 21945 int node_offset_reg = BPF_REG_4; 21946 21947 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 21948 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 21949 struct_meta_reg = BPF_REG_4; 21950 node_offset_reg = BPF_REG_5; 21951 } 21952 21953 if (!kptr_struct_meta) { 21954 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 21955 insn_idx); 21956 return -EFAULT; 21957 } 21958 21959 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 21960 node_offset_reg, insn, insn_buf, cnt); 21961 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 21962 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 21963 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 21964 *cnt = 1; 21965 } 21966 21967 if (env->insn_aux_data[insn_idx].arg_prog) { 21968 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 21969 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 21970 int idx = *cnt; 21971 21972 insn_buf[idx++] = ld_addrs[0]; 21973 insn_buf[idx++] = ld_addrs[1]; 21974 insn_buf[idx++] = *insn; 21975 *cnt = idx; 21976 } 21977 return 0; 21978 } 21979 21980 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 21981 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 21982 { 21983 struct bpf_subprog_info *info = env->subprog_info; 21984 int cnt = env->subprog_cnt; 21985 struct bpf_prog *prog; 21986 21987 /* We only reserve one slot for hidden subprogs in subprog_info. */ 21988 if (env->hidden_subprog_cnt) { 21989 verifier_bug(env, "only one hidden subprog supported"); 21990 return -EFAULT; 21991 } 21992 /* We're not patching any existing instruction, just appending the new 21993 * ones for the hidden subprog. Hence all of the adjustment operations 21994 * in bpf_patch_insn_data are no-ops. 21995 */ 21996 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 21997 if (!prog) 21998 return -ENOMEM; 21999 env->prog = prog; 22000 info[cnt + 1].start = info[cnt].start; 22001 info[cnt].start = prog->len - len + 1; 22002 env->subprog_cnt++; 22003 env->hidden_subprog_cnt++; 22004 return 0; 22005 } 22006 22007 /* Do various post-verification rewrites in a single program pass. 22008 * These rewrites simplify JIT and interpreter implementations. 22009 */ 22010 static int do_misc_fixups(struct bpf_verifier_env *env) 22011 { 22012 struct bpf_prog *prog = env->prog; 22013 enum bpf_attach_type eatype = prog->expected_attach_type; 22014 enum bpf_prog_type prog_type = resolve_prog_type(prog); 22015 struct bpf_insn *insn = prog->insnsi; 22016 const struct bpf_func_proto *fn; 22017 const int insn_cnt = prog->len; 22018 const struct bpf_map_ops *ops; 22019 struct bpf_insn_aux_data *aux; 22020 struct bpf_insn *insn_buf = env->insn_buf; 22021 struct bpf_prog *new_prog; 22022 struct bpf_map *map_ptr; 22023 int i, ret, cnt, delta = 0, cur_subprog = 0; 22024 struct bpf_subprog_info *subprogs = env->subprog_info; 22025 u16 stack_depth = subprogs[cur_subprog].stack_depth; 22026 u16 stack_depth_extra = 0; 22027 22028 if (env->seen_exception && !env->exception_callback_subprog) { 22029 struct bpf_insn *patch = insn_buf; 22030 22031 *patch++ = env->prog->insnsi[insn_cnt - 1]; 22032 *patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 22033 *patch++ = BPF_EXIT_INSN(); 22034 ret = add_hidden_subprog(env, insn_buf, patch - insn_buf); 22035 if (ret < 0) 22036 return ret; 22037 prog = env->prog; 22038 insn = prog->insnsi; 22039 22040 env->exception_callback_subprog = env->subprog_cnt - 1; 22041 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 22042 mark_subprog_exc_cb(env, env->exception_callback_subprog); 22043 } 22044 22045 for (i = 0; i < insn_cnt;) { 22046 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 22047 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 22048 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 22049 /* convert to 32-bit mov that clears upper 32-bit */ 22050 insn->code = BPF_ALU | BPF_MOV | BPF_X; 22051 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 22052 insn->off = 0; 22053 insn->imm = 0; 22054 } /* cast from as(0) to as(1) should be handled by JIT */ 22055 goto next_insn; 22056 } 22057 22058 if (env->insn_aux_data[i + delta].needs_zext) 22059 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 22060 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 22061 22062 /* Make sdiv/smod divide-by-minus-one exceptions impossible. */ 22063 if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) || 22064 insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) || 22065 insn->code == (BPF_ALU | BPF_MOD | BPF_K) || 22066 insn->code == (BPF_ALU | BPF_DIV | BPF_K)) && 22067 insn->off == 1 && insn->imm == -1) { 22068 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 22069 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 22070 struct bpf_insn *patch = insn_buf; 22071 22072 if (isdiv) 22073 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22074 BPF_NEG | BPF_K, insn->dst_reg, 22075 0, 0, 0); 22076 else 22077 *patch++ = BPF_MOV32_IMM(insn->dst_reg, 0); 22078 22079 cnt = patch - insn_buf; 22080 22081 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22082 if (!new_prog) 22083 return -ENOMEM; 22084 22085 delta += cnt - 1; 22086 env->prog = prog = new_prog; 22087 insn = new_prog->insnsi + i + delta; 22088 goto next_insn; 22089 } 22090 22091 /* Make divide-by-zero and divide-by-minus-one exceptions impossible. */ 22092 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 22093 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 22094 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 22095 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 22096 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 22097 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 22098 bool is_sdiv = isdiv && insn->off == 1; 22099 bool is_smod = !isdiv && insn->off == 1; 22100 struct bpf_insn *patch = insn_buf; 22101 22102 if (is_sdiv) { 22103 /* [R,W]x sdiv 0 -> 0 22104 * LLONG_MIN sdiv -1 -> LLONG_MIN 22105 * INT_MIN sdiv -1 -> INT_MIN 22106 */ 22107 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 22108 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22109 BPF_ADD | BPF_K, BPF_REG_AX, 22110 0, 0, 1); 22111 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22112 BPF_JGT | BPF_K, BPF_REG_AX, 22113 0, 4, 1); 22114 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22115 BPF_JEQ | BPF_K, BPF_REG_AX, 22116 0, 1, 0); 22117 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22118 BPF_MOV | BPF_K, insn->dst_reg, 22119 0, 0, 0); 22120 /* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */ 22121 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22122 BPF_NEG | BPF_K, insn->dst_reg, 22123 0, 0, 0); 22124 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22125 *patch++ = *insn; 22126 cnt = patch - insn_buf; 22127 } else if (is_smod) { 22128 /* [R,W]x mod 0 -> [R,W]x */ 22129 /* [R,W]x mod -1 -> 0 */ 22130 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 22131 *patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) | 22132 BPF_ADD | BPF_K, BPF_REG_AX, 22133 0, 0, 1); 22134 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22135 BPF_JGT | BPF_K, BPF_REG_AX, 22136 0, 3, 1); 22137 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22138 BPF_JEQ | BPF_K, BPF_REG_AX, 22139 0, 3 + (is64 ? 0 : 1), 1); 22140 *patch++ = BPF_MOV32_IMM(insn->dst_reg, 0); 22141 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22142 *patch++ = *insn; 22143 22144 if (!is64) { 22145 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22146 *patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg); 22147 } 22148 cnt = patch - insn_buf; 22149 } else if (isdiv) { 22150 /* [R,W]x div 0 -> 0 */ 22151 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22152 BPF_JNE | BPF_K, insn->src_reg, 22153 0, 2, 0); 22154 *patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg); 22155 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22156 *patch++ = *insn; 22157 cnt = patch - insn_buf; 22158 } else { 22159 /* [R,W]x mod 0 -> [R,W]x */ 22160 *patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 22161 BPF_JEQ | BPF_K, insn->src_reg, 22162 0, 1 + (is64 ? 0 : 1), 0); 22163 *patch++ = *insn; 22164 22165 if (!is64) { 22166 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22167 *patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg); 22168 } 22169 cnt = patch - insn_buf; 22170 } 22171 22172 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22173 if (!new_prog) 22174 return -ENOMEM; 22175 22176 delta += cnt - 1; 22177 env->prog = prog = new_prog; 22178 insn = new_prog->insnsi + i + delta; 22179 goto next_insn; 22180 } 22181 22182 /* Make it impossible to de-reference a userspace address */ 22183 if (BPF_CLASS(insn->code) == BPF_LDX && 22184 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 22185 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) { 22186 struct bpf_insn *patch = insn_buf; 22187 u64 uaddress_limit = bpf_arch_uaddress_limit(); 22188 22189 if (!uaddress_limit) 22190 goto next_insn; 22191 22192 *patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg); 22193 if (insn->off) 22194 *patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off); 22195 *patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32); 22196 *patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2); 22197 *patch++ = *insn; 22198 *patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1); 22199 *patch++ = BPF_MOV64_IMM(insn->dst_reg, 0); 22200 22201 cnt = patch - insn_buf; 22202 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 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 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 22213 if (BPF_CLASS(insn->code) == BPF_LD && 22214 (BPF_MODE(insn->code) == BPF_ABS || 22215 BPF_MODE(insn->code) == BPF_IND)) { 22216 cnt = env->ops->gen_ld_abs(insn, insn_buf); 22217 if (cnt == 0 || cnt >= INSN_BUF_SIZE) { 22218 verifier_bug(env, "%d insns generated for ld_abs", cnt); 22219 return -EFAULT; 22220 } 22221 22222 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22223 if (!new_prog) 22224 return -ENOMEM; 22225 22226 delta += cnt - 1; 22227 env->prog = prog = new_prog; 22228 insn = new_prog->insnsi + i + delta; 22229 goto next_insn; 22230 } 22231 22232 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 22233 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 22234 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 22235 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 22236 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 22237 struct bpf_insn *patch = insn_buf; 22238 bool issrc, isneg, isimm; 22239 u32 off_reg; 22240 22241 aux = &env->insn_aux_data[i + delta]; 22242 if (!aux->alu_state || 22243 aux->alu_state == BPF_ALU_NON_POINTER) 22244 goto next_insn; 22245 22246 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 22247 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 22248 BPF_ALU_SANITIZE_SRC; 22249 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 22250 22251 off_reg = issrc ? insn->src_reg : insn->dst_reg; 22252 if (isimm) { 22253 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 22254 } else { 22255 if (isneg) 22256 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 22257 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 22258 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 22259 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 22260 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 22261 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 22262 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 22263 } 22264 if (!issrc) 22265 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 22266 insn->src_reg = BPF_REG_AX; 22267 if (isneg) 22268 insn->code = insn->code == code_add ? 22269 code_sub : code_add; 22270 *patch++ = *insn; 22271 if (issrc && isneg && !isimm) 22272 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 22273 cnt = patch - insn_buf; 22274 22275 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22276 if (!new_prog) 22277 return -ENOMEM; 22278 22279 delta += cnt - 1; 22280 env->prog = prog = new_prog; 22281 insn = new_prog->insnsi + i + delta; 22282 goto next_insn; 22283 } 22284 22285 if (is_may_goto_insn(insn) && bpf_jit_supports_timed_may_goto()) { 22286 int stack_off_cnt = -stack_depth - 16; 22287 22288 /* 22289 * Two 8 byte slots, depth-16 stores the count, and 22290 * depth-8 stores the start timestamp of the loop. 22291 * 22292 * The starting value of count is BPF_MAX_TIMED_LOOPS 22293 * (0xffff). Every iteration loads it and subs it by 1, 22294 * until the value becomes 0 in AX (thus, 1 in stack), 22295 * after which we call arch_bpf_timed_may_goto, which 22296 * either sets AX to 0xffff to keep looping, or to 0 22297 * upon timeout. AX is then stored into the stack. In 22298 * the next iteration, we either see 0 and break out, or 22299 * continue iterating until the next time value is 0 22300 * after subtraction, rinse and repeat. 22301 */ 22302 stack_depth_extra = 16; 22303 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off_cnt); 22304 if (insn->off >= 0) 22305 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 5); 22306 else 22307 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 22308 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 22309 insn_buf[3] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2); 22310 /* 22311 * AX is used as an argument to pass in stack_off_cnt 22312 * (to add to r10/fp), and also as the return value of 22313 * the call to arch_bpf_timed_may_goto. 22314 */ 22315 insn_buf[4] = BPF_MOV64_IMM(BPF_REG_AX, stack_off_cnt); 22316 insn_buf[5] = BPF_EMIT_CALL(arch_bpf_timed_may_goto); 22317 insn_buf[6] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off_cnt); 22318 cnt = 7; 22319 22320 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22321 if (!new_prog) 22322 return -ENOMEM; 22323 22324 delta += cnt - 1; 22325 env->prog = prog = new_prog; 22326 insn = new_prog->insnsi + i + delta; 22327 goto next_insn; 22328 } else if (is_may_goto_insn(insn)) { 22329 int stack_off = -stack_depth - 8; 22330 22331 stack_depth_extra = 8; 22332 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 22333 if (insn->off >= 0) 22334 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 22335 else 22336 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off - 1); 22337 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 22338 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 22339 cnt = 4; 22340 22341 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22342 if (!new_prog) 22343 return -ENOMEM; 22344 22345 delta += cnt - 1; 22346 env->prog = prog = new_prog; 22347 insn = new_prog->insnsi + i + delta; 22348 goto next_insn; 22349 } 22350 22351 if (insn->code != (BPF_JMP | BPF_CALL)) 22352 goto next_insn; 22353 if (insn->src_reg == BPF_PSEUDO_CALL) 22354 goto next_insn; 22355 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 22356 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 22357 if (ret) 22358 return ret; 22359 if (cnt == 0) 22360 goto next_insn; 22361 22362 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22363 if (!new_prog) 22364 return -ENOMEM; 22365 22366 delta += cnt - 1; 22367 env->prog = prog = new_prog; 22368 insn = new_prog->insnsi + i + delta; 22369 goto next_insn; 22370 } 22371 22372 /* Skip inlining the helper call if the JIT does it. */ 22373 if (bpf_jit_inlines_helper_call(insn->imm)) 22374 goto next_insn; 22375 22376 if (insn->imm == BPF_FUNC_get_route_realm) 22377 prog->dst_needed = 1; 22378 if (insn->imm == BPF_FUNC_get_prandom_u32) 22379 bpf_user_rnd_init_once(); 22380 if (insn->imm == BPF_FUNC_override_return) 22381 prog->kprobe_override = 1; 22382 if (insn->imm == BPF_FUNC_tail_call) { 22383 /* If we tail call into other programs, we 22384 * cannot make any assumptions since they can 22385 * be replaced dynamically during runtime in 22386 * the program array. 22387 */ 22388 prog->cb_access = 1; 22389 if (!allow_tail_call_in_subprogs(env)) 22390 prog->aux->stack_depth = MAX_BPF_STACK; 22391 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 22392 22393 /* mark bpf_tail_call as different opcode to avoid 22394 * conditional branch in the interpreter for every normal 22395 * call and to prevent accidental JITing by JIT compiler 22396 * that doesn't support bpf_tail_call yet 22397 */ 22398 insn->imm = 0; 22399 insn->code = BPF_JMP | BPF_TAIL_CALL; 22400 22401 aux = &env->insn_aux_data[i + delta]; 22402 if (env->bpf_capable && !prog->blinding_requested && 22403 prog->jit_requested && 22404 !bpf_map_key_poisoned(aux) && 22405 !bpf_map_ptr_poisoned(aux) && 22406 !bpf_map_ptr_unpriv(aux)) { 22407 struct bpf_jit_poke_descriptor desc = { 22408 .reason = BPF_POKE_REASON_TAIL_CALL, 22409 .tail_call.map = aux->map_ptr_state.map_ptr, 22410 .tail_call.key = bpf_map_key_immediate(aux), 22411 .insn_idx = i + delta, 22412 }; 22413 22414 ret = bpf_jit_add_poke_descriptor(prog, &desc); 22415 if (ret < 0) { 22416 verbose(env, "adding tail call poke descriptor failed\n"); 22417 return ret; 22418 } 22419 22420 insn->imm = ret + 1; 22421 goto next_insn; 22422 } 22423 22424 if (!bpf_map_ptr_unpriv(aux)) 22425 goto next_insn; 22426 22427 /* instead of changing every JIT dealing with tail_call 22428 * emit two extra insns: 22429 * if (index >= max_entries) goto out; 22430 * index &= array->index_mask; 22431 * to avoid out-of-bounds cpu speculation 22432 */ 22433 if (bpf_map_ptr_poisoned(aux)) { 22434 verbose(env, "tail_call abusing map_ptr\n"); 22435 return -EINVAL; 22436 } 22437 22438 map_ptr = aux->map_ptr_state.map_ptr; 22439 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 22440 map_ptr->max_entries, 2); 22441 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 22442 container_of(map_ptr, 22443 struct bpf_array, 22444 map)->index_mask); 22445 insn_buf[2] = *insn; 22446 cnt = 3; 22447 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22448 if (!new_prog) 22449 return -ENOMEM; 22450 22451 delta += cnt - 1; 22452 env->prog = prog = new_prog; 22453 insn = new_prog->insnsi + i + delta; 22454 goto next_insn; 22455 } 22456 22457 if (insn->imm == BPF_FUNC_timer_set_callback) { 22458 /* The verifier will process callback_fn as many times as necessary 22459 * with different maps and the register states prepared by 22460 * set_timer_callback_state will be accurate. 22461 * 22462 * The following use case is valid: 22463 * map1 is shared by prog1, prog2, prog3. 22464 * prog1 calls bpf_timer_init for some map1 elements 22465 * prog2 calls bpf_timer_set_callback for some map1 elements. 22466 * Those that were not bpf_timer_init-ed will return -EINVAL. 22467 * prog3 calls bpf_timer_start for some map1 elements. 22468 * Those that were not both bpf_timer_init-ed and 22469 * bpf_timer_set_callback-ed will return -EINVAL. 22470 */ 22471 struct bpf_insn ld_addrs[2] = { 22472 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 22473 }; 22474 22475 insn_buf[0] = ld_addrs[0]; 22476 insn_buf[1] = ld_addrs[1]; 22477 insn_buf[2] = *insn; 22478 cnt = 3; 22479 22480 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22481 if (!new_prog) 22482 return -ENOMEM; 22483 22484 delta += cnt - 1; 22485 env->prog = prog = new_prog; 22486 insn = new_prog->insnsi + i + delta; 22487 goto patch_call_imm; 22488 } 22489 22490 if (is_storage_get_function(insn->imm)) { 22491 if (!in_sleepable(env) || 22492 env->insn_aux_data[i + delta].storage_get_func_atomic) 22493 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 22494 else 22495 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 22496 insn_buf[1] = *insn; 22497 cnt = 2; 22498 22499 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22500 if (!new_prog) 22501 return -ENOMEM; 22502 22503 delta += cnt - 1; 22504 env->prog = prog = new_prog; 22505 insn = new_prog->insnsi + i + delta; 22506 goto patch_call_imm; 22507 } 22508 22509 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 22510 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 22511 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 22512 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 22513 */ 22514 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 22515 insn_buf[1] = *insn; 22516 cnt = 2; 22517 22518 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22519 if (!new_prog) 22520 return -ENOMEM; 22521 22522 delta += cnt - 1; 22523 env->prog = prog = new_prog; 22524 insn = new_prog->insnsi + i + delta; 22525 goto patch_call_imm; 22526 } 22527 22528 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 22529 * and other inlining handlers are currently limited to 64 bit 22530 * only. 22531 */ 22532 if (prog->jit_requested && BITS_PER_LONG == 64 && 22533 (insn->imm == BPF_FUNC_map_lookup_elem || 22534 insn->imm == BPF_FUNC_map_update_elem || 22535 insn->imm == BPF_FUNC_map_delete_elem || 22536 insn->imm == BPF_FUNC_map_push_elem || 22537 insn->imm == BPF_FUNC_map_pop_elem || 22538 insn->imm == BPF_FUNC_map_peek_elem || 22539 insn->imm == BPF_FUNC_redirect_map || 22540 insn->imm == BPF_FUNC_for_each_map_elem || 22541 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 22542 aux = &env->insn_aux_data[i + delta]; 22543 if (bpf_map_ptr_poisoned(aux)) 22544 goto patch_call_imm; 22545 22546 map_ptr = aux->map_ptr_state.map_ptr; 22547 ops = map_ptr->ops; 22548 if (insn->imm == BPF_FUNC_map_lookup_elem && 22549 ops->map_gen_lookup) { 22550 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 22551 if (cnt == -EOPNOTSUPP) 22552 goto patch_map_ops_generic; 22553 if (cnt <= 0 || cnt >= INSN_BUF_SIZE) { 22554 verifier_bug(env, "%d insns generated for map lookup", cnt); 22555 return -EFAULT; 22556 } 22557 22558 new_prog = bpf_patch_insn_data(env, i + delta, 22559 insn_buf, cnt); 22560 if (!new_prog) 22561 return -ENOMEM; 22562 22563 delta += cnt - 1; 22564 env->prog = prog = new_prog; 22565 insn = new_prog->insnsi + i + delta; 22566 goto next_insn; 22567 } 22568 22569 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 22570 (void *(*)(struct bpf_map *map, void *key))NULL)); 22571 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 22572 (long (*)(struct bpf_map *map, void *key))NULL)); 22573 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 22574 (long (*)(struct bpf_map *map, void *key, void *value, 22575 u64 flags))NULL)); 22576 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 22577 (long (*)(struct bpf_map *map, void *value, 22578 u64 flags))NULL)); 22579 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 22580 (long (*)(struct bpf_map *map, void *value))NULL)); 22581 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 22582 (long (*)(struct bpf_map *map, void *value))NULL)); 22583 BUILD_BUG_ON(!__same_type(ops->map_redirect, 22584 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 22585 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 22586 (long (*)(struct bpf_map *map, 22587 bpf_callback_t callback_fn, 22588 void *callback_ctx, 22589 u64 flags))NULL)); 22590 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 22591 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 22592 22593 patch_map_ops_generic: 22594 switch (insn->imm) { 22595 case BPF_FUNC_map_lookup_elem: 22596 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 22597 goto next_insn; 22598 case BPF_FUNC_map_update_elem: 22599 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 22600 goto next_insn; 22601 case BPF_FUNC_map_delete_elem: 22602 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 22603 goto next_insn; 22604 case BPF_FUNC_map_push_elem: 22605 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 22606 goto next_insn; 22607 case BPF_FUNC_map_pop_elem: 22608 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 22609 goto next_insn; 22610 case BPF_FUNC_map_peek_elem: 22611 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 22612 goto next_insn; 22613 case BPF_FUNC_redirect_map: 22614 insn->imm = BPF_CALL_IMM(ops->map_redirect); 22615 goto next_insn; 22616 case BPF_FUNC_for_each_map_elem: 22617 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 22618 goto next_insn; 22619 case BPF_FUNC_map_lookup_percpu_elem: 22620 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 22621 goto next_insn; 22622 } 22623 22624 goto patch_call_imm; 22625 } 22626 22627 /* Implement bpf_jiffies64 inline. */ 22628 if (prog->jit_requested && BITS_PER_LONG == 64 && 22629 insn->imm == BPF_FUNC_jiffies64) { 22630 struct bpf_insn ld_jiffies_addr[2] = { 22631 BPF_LD_IMM64(BPF_REG_0, 22632 (unsigned long)&jiffies), 22633 }; 22634 22635 insn_buf[0] = ld_jiffies_addr[0]; 22636 insn_buf[1] = ld_jiffies_addr[1]; 22637 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 22638 BPF_REG_0, 0); 22639 cnt = 3; 22640 22641 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 22642 cnt); 22643 if (!new_prog) 22644 return -ENOMEM; 22645 22646 delta += cnt - 1; 22647 env->prog = prog = new_prog; 22648 insn = new_prog->insnsi + i + delta; 22649 goto next_insn; 22650 } 22651 22652 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML) 22653 /* Implement bpf_get_smp_processor_id() inline. */ 22654 if (insn->imm == BPF_FUNC_get_smp_processor_id && 22655 verifier_inlines_helper_call(env, insn->imm)) { 22656 /* BPF_FUNC_get_smp_processor_id inlining is an 22657 * optimization, so if cpu_number is ever 22658 * changed in some incompatible and hard to support 22659 * way, it's fine to back out this inlining logic 22660 */ 22661 #ifdef CONFIG_SMP 22662 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number); 22663 insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0); 22664 insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0); 22665 cnt = 3; 22666 #else 22667 insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0); 22668 cnt = 1; 22669 #endif 22670 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22671 if (!new_prog) 22672 return -ENOMEM; 22673 22674 delta += cnt - 1; 22675 env->prog = prog = new_prog; 22676 insn = new_prog->insnsi + i + delta; 22677 goto next_insn; 22678 } 22679 #endif 22680 /* Implement bpf_get_func_arg inline. */ 22681 if (prog_type == BPF_PROG_TYPE_TRACING && 22682 insn->imm == BPF_FUNC_get_func_arg) { 22683 /* Load nr_args from ctx - 8 */ 22684 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22685 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 22686 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 22687 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 22688 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 22689 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 22690 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 22691 insn_buf[7] = BPF_JMP_A(1); 22692 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 22693 cnt = 9; 22694 22695 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22696 if (!new_prog) 22697 return -ENOMEM; 22698 22699 delta += cnt - 1; 22700 env->prog = prog = new_prog; 22701 insn = new_prog->insnsi + i + delta; 22702 goto next_insn; 22703 } 22704 22705 /* Implement bpf_get_func_ret inline. */ 22706 if (prog_type == BPF_PROG_TYPE_TRACING && 22707 insn->imm == BPF_FUNC_get_func_ret) { 22708 if (eatype == BPF_TRACE_FEXIT || 22709 eatype == BPF_MODIFY_RETURN) { 22710 /* Load nr_args from ctx - 8 */ 22711 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22712 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 22713 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 22714 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 22715 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 22716 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 22717 cnt = 6; 22718 } else { 22719 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 22720 cnt = 1; 22721 } 22722 22723 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22724 if (!new_prog) 22725 return -ENOMEM; 22726 22727 delta += cnt - 1; 22728 env->prog = prog = new_prog; 22729 insn = new_prog->insnsi + i + delta; 22730 goto next_insn; 22731 } 22732 22733 /* Implement get_func_arg_cnt inline. */ 22734 if (prog_type == BPF_PROG_TYPE_TRACING && 22735 insn->imm == BPF_FUNC_get_func_arg_cnt) { 22736 /* Load nr_args from ctx - 8 */ 22737 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 22738 22739 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 22740 if (!new_prog) 22741 return -ENOMEM; 22742 22743 env->prog = prog = new_prog; 22744 insn = new_prog->insnsi + i + delta; 22745 goto next_insn; 22746 } 22747 22748 /* Implement bpf_get_func_ip inline. */ 22749 if (prog_type == BPF_PROG_TYPE_TRACING && 22750 insn->imm == BPF_FUNC_get_func_ip) { 22751 /* Load IP address from ctx - 16 */ 22752 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 22753 22754 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 22755 if (!new_prog) 22756 return -ENOMEM; 22757 22758 env->prog = prog = new_prog; 22759 insn = new_prog->insnsi + i + delta; 22760 goto next_insn; 22761 } 22762 22763 /* Implement bpf_get_branch_snapshot inline. */ 22764 if (IS_ENABLED(CONFIG_PERF_EVENTS) && 22765 prog->jit_requested && BITS_PER_LONG == 64 && 22766 insn->imm == BPF_FUNC_get_branch_snapshot) { 22767 /* We are dealing with the following func protos: 22768 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags); 22769 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt); 22770 */ 22771 const u32 br_entry_size = sizeof(struct perf_branch_entry); 22772 22773 /* struct perf_branch_entry is part of UAPI and is 22774 * used as an array element, so extremely unlikely to 22775 * ever grow or shrink 22776 */ 22777 BUILD_BUG_ON(br_entry_size != 24); 22778 22779 /* if (unlikely(flags)) return -EINVAL */ 22780 insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7); 22781 22782 /* Transform size (bytes) into number of entries (cnt = size / 24). 22783 * But to avoid expensive division instruction, we implement 22784 * divide-by-3 through multiplication, followed by further 22785 * division by 8 through 3-bit right shift. 22786 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr., 22787 * p. 227, chapter "Unsigned Division by 3" for details and proofs. 22788 * 22789 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab. 22790 */ 22791 insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab); 22792 insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0); 22793 insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36); 22794 22795 /* call perf_snapshot_branch_stack implementation */ 22796 insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack)); 22797 /* if (entry_cnt == 0) return -ENOENT */ 22798 insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4); 22799 /* return entry_cnt * sizeof(struct perf_branch_entry) */ 22800 insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size); 22801 insn_buf[7] = BPF_JMP_A(3); 22802 /* return -EINVAL; */ 22803 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 22804 insn_buf[9] = BPF_JMP_A(1); 22805 /* return -ENOENT; */ 22806 insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT); 22807 cnt = 11; 22808 22809 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22810 if (!new_prog) 22811 return -ENOMEM; 22812 22813 delta += cnt - 1; 22814 env->prog = prog = new_prog; 22815 insn = new_prog->insnsi + i + delta; 22816 goto next_insn; 22817 } 22818 22819 /* Implement bpf_kptr_xchg inline */ 22820 if (prog->jit_requested && BITS_PER_LONG == 64 && 22821 insn->imm == BPF_FUNC_kptr_xchg && 22822 bpf_jit_supports_ptr_xchg()) { 22823 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 22824 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 22825 cnt = 2; 22826 22827 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 22828 if (!new_prog) 22829 return -ENOMEM; 22830 22831 delta += cnt - 1; 22832 env->prog = prog = new_prog; 22833 insn = new_prog->insnsi + i + delta; 22834 goto next_insn; 22835 } 22836 patch_call_imm: 22837 fn = env->ops->get_func_proto(insn->imm, env->prog); 22838 /* all functions that have prototype and verifier allowed 22839 * programs to call them, must be real in-kernel functions 22840 */ 22841 if (!fn->func) { 22842 verifier_bug(env, 22843 "not inlined functions %s#%d is missing func", 22844 func_id_name(insn->imm), insn->imm); 22845 return -EFAULT; 22846 } 22847 insn->imm = fn->func - __bpf_call_base; 22848 next_insn: 22849 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 22850 subprogs[cur_subprog].stack_depth += stack_depth_extra; 22851 subprogs[cur_subprog].stack_extra = stack_depth_extra; 22852 22853 stack_depth = subprogs[cur_subprog].stack_depth; 22854 if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) { 22855 verbose(env, "stack size %d(extra %d) is too large\n", 22856 stack_depth, stack_depth_extra); 22857 return -EINVAL; 22858 } 22859 cur_subprog++; 22860 stack_depth = subprogs[cur_subprog].stack_depth; 22861 stack_depth_extra = 0; 22862 } 22863 i++; 22864 insn++; 22865 } 22866 22867 env->prog->aux->stack_depth = subprogs[0].stack_depth; 22868 for (i = 0; i < env->subprog_cnt; i++) { 22869 int delta = bpf_jit_supports_timed_may_goto() ? 2 : 1; 22870 int subprog_start = subprogs[i].start; 22871 int stack_slots = subprogs[i].stack_extra / 8; 22872 int slots = delta, cnt = 0; 22873 22874 if (!stack_slots) 22875 continue; 22876 /* We need two slots in case timed may_goto is supported. */ 22877 if (stack_slots > slots) { 22878 verifier_bug(env, "stack_slots supports may_goto only"); 22879 return -EFAULT; 22880 } 22881 22882 stack_depth = subprogs[i].stack_depth; 22883 if (bpf_jit_supports_timed_may_goto()) { 22884 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth, 22885 BPF_MAX_TIMED_LOOPS); 22886 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth + 8, 0); 22887 } else { 22888 /* Add ST insn to subprog prologue to init extra stack */ 22889 insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth, 22890 BPF_MAX_LOOPS); 22891 } 22892 /* Copy first actual insn to preserve it */ 22893 insn_buf[cnt++] = env->prog->insnsi[subprog_start]; 22894 22895 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, cnt); 22896 if (!new_prog) 22897 return -ENOMEM; 22898 env->prog = prog = new_prog; 22899 /* 22900 * If may_goto is a first insn of a prog there could be a jmp 22901 * insn that points to it, hence adjust all such jmps to point 22902 * to insn after BPF_ST that inits may_goto count. 22903 * Adjustment will succeed because bpf_patch_insn_data() didn't fail. 22904 */ 22905 WARN_ON(adjust_jmp_off(env->prog, subprog_start, delta)); 22906 } 22907 22908 /* Since poke tab is now finalized, publish aux to tracker. */ 22909 for (i = 0; i < prog->aux->size_poke_tab; i++) { 22910 map_ptr = prog->aux->poke_tab[i].tail_call.map; 22911 if (!map_ptr->ops->map_poke_track || 22912 !map_ptr->ops->map_poke_untrack || 22913 !map_ptr->ops->map_poke_run) { 22914 verifier_bug(env, "poke tab is misconfigured"); 22915 return -EFAULT; 22916 } 22917 22918 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 22919 if (ret < 0) { 22920 verbose(env, "tracking tail call prog failed\n"); 22921 return ret; 22922 } 22923 } 22924 22925 sort_kfunc_descs_by_imm_off(env->prog); 22926 22927 return 0; 22928 } 22929 22930 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 22931 int position, 22932 s32 stack_base, 22933 u32 callback_subprogno, 22934 u32 *total_cnt) 22935 { 22936 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 22937 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 22938 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 22939 int reg_loop_max = BPF_REG_6; 22940 int reg_loop_cnt = BPF_REG_7; 22941 int reg_loop_ctx = BPF_REG_8; 22942 22943 struct bpf_insn *insn_buf = env->insn_buf; 22944 struct bpf_prog *new_prog; 22945 u32 callback_start; 22946 u32 call_insn_offset; 22947 s32 callback_offset; 22948 u32 cnt = 0; 22949 22950 /* This represents an inlined version of bpf_iter.c:bpf_loop, 22951 * be careful to modify this code in sync. 22952 */ 22953 22954 /* Return error and jump to the end of the patch if 22955 * expected number of iterations is too big. 22956 */ 22957 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2); 22958 insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG); 22959 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16); 22960 /* spill R6, R7, R8 to use these as loop vars */ 22961 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset); 22962 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset); 22963 insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset); 22964 /* initialize loop vars */ 22965 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1); 22966 insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0); 22967 insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3); 22968 /* loop header, 22969 * if reg_loop_cnt >= reg_loop_max skip the loop body 22970 */ 22971 insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5); 22972 /* callback call, 22973 * correct callback offset would be set after patching 22974 */ 22975 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt); 22976 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx); 22977 insn_buf[cnt++] = BPF_CALL_REL(0); 22978 /* increment loop counter */ 22979 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1); 22980 /* jump to loop header if callback returned 0 */ 22981 insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6); 22982 /* return value of bpf_loop, 22983 * set R0 to the number of iterations 22984 */ 22985 insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt); 22986 /* restore original values of R6, R7, R8 */ 22987 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset); 22988 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset); 22989 insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset); 22990 22991 *total_cnt = cnt; 22992 new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt); 22993 if (!new_prog) 22994 return new_prog; 22995 22996 /* callback start is known only after patching */ 22997 callback_start = env->subprog_info[callback_subprogno].start; 22998 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 22999 call_insn_offset = position + 12; 23000 callback_offset = callback_start - call_insn_offset - 1; 23001 new_prog->insnsi[call_insn_offset].imm = callback_offset; 23002 23003 return new_prog; 23004 } 23005 23006 static bool is_bpf_loop_call(struct bpf_insn *insn) 23007 { 23008 return insn->code == (BPF_JMP | BPF_CALL) && 23009 insn->src_reg == 0 && 23010 insn->imm == BPF_FUNC_loop; 23011 } 23012 23013 /* For all sub-programs in the program (including main) check 23014 * insn_aux_data to see if there are bpf_loop calls that require 23015 * inlining. If such calls are found the calls are replaced with a 23016 * sequence of instructions produced by `inline_bpf_loop` function and 23017 * subprog stack_depth is increased by the size of 3 registers. 23018 * This stack space is used to spill values of the R6, R7, R8. These 23019 * registers are used to store the loop bound, counter and context 23020 * variables. 23021 */ 23022 static int optimize_bpf_loop(struct bpf_verifier_env *env) 23023 { 23024 struct bpf_subprog_info *subprogs = env->subprog_info; 23025 int i, cur_subprog = 0, cnt, delta = 0; 23026 struct bpf_insn *insn = env->prog->insnsi; 23027 int insn_cnt = env->prog->len; 23028 u16 stack_depth = subprogs[cur_subprog].stack_depth; 23029 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 23030 u16 stack_depth_extra = 0; 23031 23032 for (i = 0; i < insn_cnt; i++, insn++) { 23033 struct bpf_loop_inline_state *inline_state = 23034 &env->insn_aux_data[i + delta].loop_inline_state; 23035 23036 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 23037 struct bpf_prog *new_prog; 23038 23039 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 23040 new_prog = inline_bpf_loop(env, 23041 i + delta, 23042 -(stack_depth + stack_depth_extra), 23043 inline_state->callback_subprogno, 23044 &cnt); 23045 if (!new_prog) 23046 return -ENOMEM; 23047 23048 delta += cnt - 1; 23049 env->prog = new_prog; 23050 insn = new_prog->insnsi + i + delta; 23051 } 23052 23053 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 23054 subprogs[cur_subprog].stack_depth += stack_depth_extra; 23055 cur_subprog++; 23056 stack_depth = subprogs[cur_subprog].stack_depth; 23057 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 23058 stack_depth_extra = 0; 23059 } 23060 } 23061 23062 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 23063 23064 return 0; 23065 } 23066 23067 /* Remove unnecessary spill/fill pairs, members of fastcall pattern, 23068 * adjust subprograms stack depth when possible. 23069 */ 23070 static int remove_fastcall_spills_fills(struct bpf_verifier_env *env) 23071 { 23072 struct bpf_subprog_info *subprog = env->subprog_info; 23073 struct bpf_insn_aux_data *aux = env->insn_aux_data; 23074 struct bpf_insn *insn = env->prog->insnsi; 23075 int insn_cnt = env->prog->len; 23076 u32 spills_num; 23077 bool modified = false; 23078 int i, j; 23079 23080 for (i = 0; i < insn_cnt; i++, insn++) { 23081 if (aux[i].fastcall_spills_num > 0) { 23082 spills_num = aux[i].fastcall_spills_num; 23083 /* NOPs would be removed by opt_remove_nops() */ 23084 for (j = 1; j <= spills_num; ++j) { 23085 *(insn - j) = NOP; 23086 *(insn + j) = NOP; 23087 } 23088 modified = true; 23089 } 23090 if ((subprog + 1)->start == i + 1) { 23091 if (modified && !subprog->keep_fastcall_stack) 23092 subprog->stack_depth = -subprog->fastcall_stack_off; 23093 subprog++; 23094 modified = false; 23095 } 23096 } 23097 23098 return 0; 23099 } 23100 23101 static void free_states(struct bpf_verifier_env *env) 23102 { 23103 struct bpf_verifier_state_list *sl; 23104 struct list_head *head, *pos, *tmp; 23105 struct bpf_scc_info *info; 23106 int i, j; 23107 23108 free_verifier_state(env->cur_state, true); 23109 env->cur_state = NULL; 23110 while (!pop_stack(env, NULL, NULL, false)); 23111 23112 list_for_each_safe(pos, tmp, &env->free_list) { 23113 sl = container_of(pos, struct bpf_verifier_state_list, node); 23114 free_verifier_state(&sl->state, false); 23115 kfree(sl); 23116 } 23117 INIT_LIST_HEAD(&env->free_list); 23118 23119 for (i = 0; i < env->scc_cnt; ++i) { 23120 info = env->scc_info[i]; 23121 if (!info) 23122 continue; 23123 for (j = 0; j < info->num_visits; j++) 23124 free_backedges(&info->visits[j]); 23125 kvfree(info); 23126 env->scc_info[i] = NULL; 23127 } 23128 23129 if (!env->explored_states) 23130 return; 23131 23132 for (i = 0; i < state_htab_size(env); i++) { 23133 head = &env->explored_states[i]; 23134 23135 list_for_each_safe(pos, tmp, head) { 23136 sl = container_of(pos, struct bpf_verifier_state_list, node); 23137 free_verifier_state(&sl->state, false); 23138 kfree(sl); 23139 } 23140 INIT_LIST_HEAD(&env->explored_states[i]); 23141 } 23142 } 23143 23144 static int do_check_common(struct bpf_verifier_env *env, int subprog) 23145 { 23146 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 23147 struct bpf_subprog_info *sub = subprog_info(env, subprog); 23148 struct bpf_prog_aux *aux = env->prog->aux; 23149 struct bpf_verifier_state *state; 23150 struct bpf_reg_state *regs; 23151 int ret, i; 23152 23153 env->prev_linfo = NULL; 23154 env->pass_cnt++; 23155 23156 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL_ACCOUNT); 23157 if (!state) 23158 return -ENOMEM; 23159 state->curframe = 0; 23160 state->speculative = false; 23161 state->branches = 1; 23162 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL_ACCOUNT); 23163 if (!state->frame[0]) { 23164 kfree(state); 23165 return -ENOMEM; 23166 } 23167 env->cur_state = state; 23168 init_func_state(env, state->frame[0], 23169 BPF_MAIN_FUNC /* callsite */, 23170 0 /* frameno */, 23171 subprog); 23172 state->first_insn_idx = env->subprog_info[subprog].start; 23173 state->last_insn_idx = -1; 23174 23175 regs = state->frame[state->curframe]->regs; 23176 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 23177 const char *sub_name = subprog_name(env, subprog); 23178 struct bpf_subprog_arg_info *arg; 23179 struct bpf_reg_state *reg; 23180 23181 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 23182 ret = btf_prepare_func_args(env, subprog); 23183 if (ret) 23184 goto out; 23185 23186 if (subprog_is_exc_cb(env, subprog)) { 23187 state->frame[0]->in_exception_callback_fn = true; 23188 /* We have already ensured that the callback returns an integer, just 23189 * like all global subprogs. We need to determine it only has a single 23190 * scalar argument. 23191 */ 23192 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 23193 verbose(env, "exception cb only supports single integer argument\n"); 23194 ret = -EINVAL; 23195 goto out; 23196 } 23197 } 23198 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 23199 arg = &sub->args[i - BPF_REG_1]; 23200 reg = ®s[i]; 23201 23202 if (arg->arg_type == ARG_PTR_TO_CTX) { 23203 reg->type = PTR_TO_CTX; 23204 mark_reg_known_zero(env, regs, i); 23205 } else if (arg->arg_type == ARG_ANYTHING) { 23206 reg->type = SCALAR_VALUE; 23207 mark_reg_unknown(env, regs, i); 23208 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 23209 /* assume unspecial LOCAL dynptr type */ 23210 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 23211 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 23212 reg->type = PTR_TO_MEM; 23213 reg->type |= arg->arg_type & 23214 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 23215 mark_reg_known_zero(env, regs, i); 23216 reg->mem_size = arg->mem_size; 23217 if (arg->arg_type & PTR_MAYBE_NULL) 23218 reg->id = ++env->id_gen; 23219 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 23220 reg->type = PTR_TO_BTF_ID; 23221 if (arg->arg_type & PTR_MAYBE_NULL) 23222 reg->type |= PTR_MAYBE_NULL; 23223 if (arg->arg_type & PTR_UNTRUSTED) 23224 reg->type |= PTR_UNTRUSTED; 23225 if (arg->arg_type & PTR_TRUSTED) 23226 reg->type |= PTR_TRUSTED; 23227 mark_reg_known_zero(env, regs, i); 23228 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 23229 reg->btf_id = arg->btf_id; 23230 reg->id = ++env->id_gen; 23231 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 23232 /* caller can pass either PTR_TO_ARENA or SCALAR */ 23233 mark_reg_unknown(env, regs, i); 23234 } else { 23235 verifier_bug(env, "unhandled arg#%d type %d", 23236 i - BPF_REG_1, arg->arg_type); 23237 ret = -EFAULT; 23238 goto out; 23239 } 23240 } 23241 } else { 23242 /* if main BPF program has associated BTF info, validate that 23243 * it's matching expected signature, and otherwise mark BTF 23244 * info for main program as unreliable 23245 */ 23246 if (env->prog->aux->func_info_aux) { 23247 ret = btf_prepare_func_args(env, 0); 23248 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 23249 env->prog->aux->func_info_aux[0].unreliable = true; 23250 } 23251 23252 /* 1st arg to a function */ 23253 regs[BPF_REG_1].type = PTR_TO_CTX; 23254 mark_reg_known_zero(env, regs, BPF_REG_1); 23255 } 23256 23257 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 23258 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 23259 for (i = 0; i < aux->ctx_arg_info_size; i++) 23260 aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ? 23261 acquire_reference(env, 0) : 0; 23262 } 23263 23264 ret = do_check(env); 23265 out: 23266 if (!ret && pop_log) 23267 bpf_vlog_reset(&env->log, 0); 23268 free_states(env); 23269 return ret; 23270 } 23271 23272 /* Lazily verify all global functions based on their BTF, if they are called 23273 * from main BPF program or any of subprograms transitively. 23274 * BPF global subprogs called from dead code are not validated. 23275 * All callable global functions must pass verification. 23276 * Otherwise the whole program is rejected. 23277 * Consider: 23278 * int bar(int); 23279 * int foo(int f) 23280 * { 23281 * return bar(f); 23282 * } 23283 * int bar(int b) 23284 * { 23285 * ... 23286 * } 23287 * foo() will be verified first for R1=any_scalar_value. During verification it 23288 * will be assumed that bar() already verified successfully and call to bar() 23289 * from foo() will be checked for type match only. Later bar() will be verified 23290 * independently to check that it's safe for R1=any_scalar_value. 23291 */ 23292 static int do_check_subprogs(struct bpf_verifier_env *env) 23293 { 23294 struct bpf_prog_aux *aux = env->prog->aux; 23295 struct bpf_func_info_aux *sub_aux; 23296 int i, ret, new_cnt; 23297 23298 if (!aux->func_info) 23299 return 0; 23300 23301 /* exception callback is presumed to be always called */ 23302 if (env->exception_callback_subprog) 23303 subprog_aux(env, env->exception_callback_subprog)->called = true; 23304 23305 again: 23306 new_cnt = 0; 23307 for (i = 1; i < env->subprog_cnt; i++) { 23308 if (!subprog_is_global(env, i)) 23309 continue; 23310 23311 sub_aux = subprog_aux(env, i); 23312 if (!sub_aux->called || sub_aux->verified) 23313 continue; 23314 23315 env->insn_idx = env->subprog_info[i].start; 23316 WARN_ON_ONCE(env->insn_idx == 0); 23317 ret = do_check_common(env, i); 23318 if (ret) { 23319 return ret; 23320 } else if (env->log.level & BPF_LOG_LEVEL) { 23321 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 23322 i, subprog_name(env, i)); 23323 } 23324 23325 /* We verified new global subprog, it might have called some 23326 * more global subprogs that we haven't verified yet, so we 23327 * need to do another pass over subprogs to verify those. 23328 */ 23329 sub_aux->verified = true; 23330 new_cnt++; 23331 } 23332 23333 /* We can't loop forever as we verify at least one global subprog on 23334 * each pass. 23335 */ 23336 if (new_cnt) 23337 goto again; 23338 23339 return 0; 23340 } 23341 23342 static int do_check_main(struct bpf_verifier_env *env) 23343 { 23344 int ret; 23345 23346 env->insn_idx = 0; 23347 ret = do_check_common(env, 0); 23348 if (!ret) 23349 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 23350 return ret; 23351 } 23352 23353 23354 static void print_verification_stats(struct bpf_verifier_env *env) 23355 { 23356 int i; 23357 23358 if (env->log.level & BPF_LOG_STATS) { 23359 verbose(env, "verification time %lld usec\n", 23360 div_u64(env->verification_time, 1000)); 23361 verbose(env, "stack depth "); 23362 for (i = 0; i < env->subprog_cnt; i++) { 23363 u32 depth = env->subprog_info[i].stack_depth; 23364 23365 verbose(env, "%d", depth); 23366 if (i + 1 < env->subprog_cnt) 23367 verbose(env, "+"); 23368 } 23369 verbose(env, "\n"); 23370 } 23371 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 23372 "total_states %d peak_states %d mark_read %d\n", 23373 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 23374 env->max_states_per_insn, env->total_states, 23375 env->peak_states, env->longest_mark_read_walk); 23376 } 23377 23378 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 23379 const struct bpf_ctx_arg_aux *info, u32 cnt) 23380 { 23381 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 23382 prog->aux->ctx_arg_info_size = cnt; 23383 23384 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 23385 } 23386 23387 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 23388 { 23389 const struct btf_type *t, *func_proto; 23390 const struct bpf_struct_ops_desc *st_ops_desc; 23391 const struct bpf_struct_ops *st_ops; 23392 const struct btf_member *member; 23393 struct bpf_prog *prog = env->prog; 23394 bool has_refcounted_arg = false; 23395 u32 btf_id, member_idx, member_off; 23396 struct btf *btf; 23397 const char *mname; 23398 int i, err; 23399 23400 if (!prog->gpl_compatible) { 23401 verbose(env, "struct ops programs must have a GPL compatible license\n"); 23402 return -EINVAL; 23403 } 23404 23405 if (!prog->aux->attach_btf_id) 23406 return -ENOTSUPP; 23407 23408 btf = prog->aux->attach_btf; 23409 if (btf_is_module(btf)) { 23410 /* Make sure st_ops is valid through the lifetime of env */ 23411 env->attach_btf_mod = btf_try_get_module(btf); 23412 if (!env->attach_btf_mod) { 23413 verbose(env, "struct_ops module %s is not found\n", 23414 btf_get_name(btf)); 23415 return -ENOTSUPP; 23416 } 23417 } 23418 23419 btf_id = prog->aux->attach_btf_id; 23420 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 23421 if (!st_ops_desc) { 23422 verbose(env, "attach_btf_id %u is not a supported struct\n", 23423 btf_id); 23424 return -ENOTSUPP; 23425 } 23426 st_ops = st_ops_desc->st_ops; 23427 23428 t = st_ops_desc->type; 23429 member_idx = prog->expected_attach_type; 23430 if (member_idx >= btf_type_vlen(t)) { 23431 verbose(env, "attach to invalid member idx %u of struct %s\n", 23432 member_idx, st_ops->name); 23433 return -EINVAL; 23434 } 23435 23436 member = &btf_type_member(t)[member_idx]; 23437 mname = btf_name_by_offset(btf, member->name_off); 23438 func_proto = btf_type_resolve_func_ptr(btf, member->type, 23439 NULL); 23440 if (!func_proto) { 23441 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 23442 mname, member_idx, st_ops->name); 23443 return -EINVAL; 23444 } 23445 23446 member_off = __btf_member_bit_offset(t, member) / 8; 23447 err = bpf_struct_ops_supported(st_ops, member_off); 23448 if (err) { 23449 verbose(env, "attach to unsupported member %s of struct %s\n", 23450 mname, st_ops->name); 23451 return err; 23452 } 23453 23454 if (st_ops->check_member) { 23455 err = st_ops->check_member(t, member, prog); 23456 23457 if (err) { 23458 verbose(env, "attach to unsupported member %s of struct %s\n", 23459 mname, st_ops->name); 23460 return err; 23461 } 23462 } 23463 23464 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 23465 verbose(env, "Private stack not supported by jit\n"); 23466 return -EACCES; 23467 } 23468 23469 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) { 23470 if (st_ops_desc->arg_info[member_idx].info->refcounted) { 23471 has_refcounted_arg = true; 23472 break; 23473 } 23474 } 23475 23476 /* Tail call is not allowed for programs with refcounted arguments since we 23477 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 23478 */ 23479 for (i = 0; i < env->subprog_cnt; i++) { 23480 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 23481 verbose(env, "program with __ref argument cannot tail call\n"); 23482 return -EINVAL; 23483 } 23484 } 23485 23486 prog->aux->st_ops = st_ops; 23487 prog->aux->attach_st_ops_member_off = member_off; 23488 23489 prog->aux->attach_func_proto = func_proto; 23490 prog->aux->attach_func_name = mname; 23491 env->ops = st_ops->verifier_ops; 23492 23493 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info, 23494 st_ops_desc->arg_info[member_idx].cnt); 23495 } 23496 #define SECURITY_PREFIX "security_" 23497 23498 static int check_attach_modify_return(unsigned long addr, const char *func_name) 23499 { 23500 if (within_error_injection_list(addr) || 23501 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 23502 return 0; 23503 23504 return -EINVAL; 23505 } 23506 23507 /* list of non-sleepable functions that are otherwise on 23508 * ALLOW_ERROR_INJECTION list 23509 */ 23510 BTF_SET_START(btf_non_sleepable_error_inject) 23511 /* Three functions below can be called from sleepable and non-sleepable context. 23512 * Assume non-sleepable from bpf safety point of view. 23513 */ 23514 BTF_ID(func, __filemap_add_folio) 23515 #ifdef CONFIG_FAIL_PAGE_ALLOC 23516 BTF_ID(func, should_fail_alloc_page) 23517 #endif 23518 #ifdef CONFIG_FAILSLAB 23519 BTF_ID(func, should_failslab) 23520 #endif 23521 BTF_SET_END(btf_non_sleepable_error_inject) 23522 23523 static int check_non_sleepable_error_inject(u32 btf_id) 23524 { 23525 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 23526 } 23527 23528 int bpf_check_attach_target(struct bpf_verifier_log *log, 23529 const struct bpf_prog *prog, 23530 const struct bpf_prog *tgt_prog, 23531 u32 btf_id, 23532 struct bpf_attach_target_info *tgt_info) 23533 { 23534 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 23535 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 23536 char trace_symbol[KSYM_SYMBOL_LEN]; 23537 const char prefix[] = "btf_trace_"; 23538 struct bpf_raw_event_map *btp; 23539 int ret = 0, subprog = -1, i; 23540 const struct btf_type *t; 23541 bool conservative = true; 23542 const char *tname, *fname; 23543 struct btf *btf; 23544 long addr = 0; 23545 struct module *mod = NULL; 23546 23547 if (!btf_id) { 23548 bpf_log(log, "Tracing programs must provide btf_id\n"); 23549 return -EINVAL; 23550 } 23551 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 23552 if (!btf) { 23553 bpf_log(log, 23554 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 23555 return -EINVAL; 23556 } 23557 t = btf_type_by_id(btf, btf_id); 23558 if (!t) { 23559 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 23560 return -EINVAL; 23561 } 23562 tname = btf_name_by_offset(btf, t->name_off); 23563 if (!tname) { 23564 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 23565 return -EINVAL; 23566 } 23567 if (tgt_prog) { 23568 struct bpf_prog_aux *aux = tgt_prog->aux; 23569 bool tgt_changes_pkt_data; 23570 bool tgt_might_sleep; 23571 23572 if (bpf_prog_is_dev_bound(prog->aux) && 23573 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 23574 bpf_log(log, "Target program bound device mismatch"); 23575 return -EINVAL; 23576 } 23577 23578 for (i = 0; i < aux->func_info_cnt; i++) 23579 if (aux->func_info[i].type_id == btf_id) { 23580 subprog = i; 23581 break; 23582 } 23583 if (subprog == -1) { 23584 bpf_log(log, "Subprog %s doesn't exist\n", tname); 23585 return -EINVAL; 23586 } 23587 if (aux->func && aux->func[subprog]->aux->exception_cb) { 23588 bpf_log(log, 23589 "%s programs cannot attach to exception callback\n", 23590 prog_extension ? "Extension" : "FENTRY/FEXIT"); 23591 return -EINVAL; 23592 } 23593 conservative = aux->func_info_aux[subprog].unreliable; 23594 if (prog_extension) { 23595 if (conservative) { 23596 bpf_log(log, 23597 "Cannot replace static functions\n"); 23598 return -EINVAL; 23599 } 23600 if (!prog->jit_requested) { 23601 bpf_log(log, 23602 "Extension programs should be JITed\n"); 23603 return -EINVAL; 23604 } 23605 tgt_changes_pkt_data = aux->func 23606 ? aux->func[subprog]->aux->changes_pkt_data 23607 : aux->changes_pkt_data; 23608 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 23609 bpf_log(log, 23610 "Extension program changes packet data, while original does not\n"); 23611 return -EINVAL; 23612 } 23613 23614 tgt_might_sleep = aux->func 23615 ? aux->func[subprog]->aux->might_sleep 23616 : aux->might_sleep; 23617 if (prog->aux->might_sleep && !tgt_might_sleep) { 23618 bpf_log(log, 23619 "Extension program may sleep, while original does not\n"); 23620 return -EINVAL; 23621 } 23622 } 23623 if (!tgt_prog->jited) { 23624 bpf_log(log, "Can attach to only JITed progs\n"); 23625 return -EINVAL; 23626 } 23627 if (prog_tracing) { 23628 if (aux->attach_tracing_prog) { 23629 /* 23630 * Target program is an fentry/fexit which is already attached 23631 * to another tracing program. More levels of nesting 23632 * attachment are not allowed. 23633 */ 23634 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 23635 return -EINVAL; 23636 } 23637 } else if (tgt_prog->type == prog->type) { 23638 /* 23639 * To avoid potential call chain cycles, prevent attaching of a 23640 * program extension to another extension. It's ok to attach 23641 * fentry/fexit to extension program. 23642 */ 23643 bpf_log(log, "Cannot recursively attach\n"); 23644 return -EINVAL; 23645 } 23646 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 23647 prog_extension && 23648 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 23649 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 23650 /* Program extensions can extend all program types 23651 * except fentry/fexit. The reason is the following. 23652 * The fentry/fexit programs are used for performance 23653 * analysis, stats and can be attached to any program 23654 * type. When extension program is replacing XDP function 23655 * it is necessary to allow performance analysis of all 23656 * functions. Both original XDP program and its program 23657 * extension. Hence attaching fentry/fexit to 23658 * BPF_PROG_TYPE_EXT is allowed. If extending of 23659 * fentry/fexit was allowed it would be possible to create 23660 * long call chain fentry->extension->fentry->extension 23661 * beyond reasonable stack size. Hence extending fentry 23662 * is not allowed. 23663 */ 23664 bpf_log(log, "Cannot extend fentry/fexit\n"); 23665 return -EINVAL; 23666 } 23667 } else { 23668 if (prog_extension) { 23669 bpf_log(log, "Cannot replace kernel functions\n"); 23670 return -EINVAL; 23671 } 23672 } 23673 23674 switch (prog->expected_attach_type) { 23675 case BPF_TRACE_RAW_TP: 23676 if (tgt_prog) { 23677 bpf_log(log, 23678 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 23679 return -EINVAL; 23680 } 23681 if (!btf_type_is_typedef(t)) { 23682 bpf_log(log, "attach_btf_id %u is not a typedef\n", 23683 btf_id); 23684 return -EINVAL; 23685 } 23686 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 23687 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 23688 btf_id, tname); 23689 return -EINVAL; 23690 } 23691 tname += sizeof(prefix) - 1; 23692 23693 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 23694 * names. Thus using bpf_raw_event_map to get argument names. 23695 */ 23696 btp = bpf_get_raw_tracepoint(tname); 23697 if (!btp) 23698 return -EINVAL; 23699 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 23700 trace_symbol); 23701 bpf_put_raw_tracepoint(btp); 23702 23703 if (fname) 23704 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 23705 23706 if (!fname || ret < 0) { 23707 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 23708 prefix, tname); 23709 t = btf_type_by_id(btf, t->type); 23710 if (!btf_type_is_ptr(t)) 23711 /* should never happen in valid vmlinux build */ 23712 return -EINVAL; 23713 } else { 23714 t = btf_type_by_id(btf, ret); 23715 if (!btf_type_is_func(t)) 23716 /* should never happen in valid vmlinux build */ 23717 return -EINVAL; 23718 } 23719 23720 t = btf_type_by_id(btf, t->type); 23721 if (!btf_type_is_func_proto(t)) 23722 /* should never happen in valid vmlinux build */ 23723 return -EINVAL; 23724 23725 break; 23726 case BPF_TRACE_ITER: 23727 if (!btf_type_is_func(t)) { 23728 bpf_log(log, "attach_btf_id %u is not a function\n", 23729 btf_id); 23730 return -EINVAL; 23731 } 23732 t = btf_type_by_id(btf, t->type); 23733 if (!btf_type_is_func_proto(t)) 23734 return -EINVAL; 23735 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 23736 if (ret) 23737 return ret; 23738 break; 23739 default: 23740 if (!prog_extension) 23741 return -EINVAL; 23742 fallthrough; 23743 case BPF_MODIFY_RETURN: 23744 case BPF_LSM_MAC: 23745 case BPF_LSM_CGROUP: 23746 case BPF_TRACE_FENTRY: 23747 case BPF_TRACE_FEXIT: 23748 if (!btf_type_is_func(t)) { 23749 bpf_log(log, "attach_btf_id %u is not a function\n", 23750 btf_id); 23751 return -EINVAL; 23752 } 23753 if (prog_extension && 23754 btf_check_type_match(log, prog, btf, t)) 23755 return -EINVAL; 23756 t = btf_type_by_id(btf, t->type); 23757 if (!btf_type_is_func_proto(t)) 23758 return -EINVAL; 23759 23760 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 23761 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 23762 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 23763 return -EINVAL; 23764 23765 if (tgt_prog && conservative) 23766 t = NULL; 23767 23768 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 23769 if (ret < 0) 23770 return ret; 23771 23772 if (tgt_prog) { 23773 if (subprog == 0) 23774 addr = (long) tgt_prog->bpf_func; 23775 else 23776 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 23777 } else { 23778 if (btf_is_module(btf)) { 23779 mod = btf_try_get_module(btf); 23780 if (mod) 23781 addr = find_kallsyms_symbol_value(mod, tname); 23782 else 23783 addr = 0; 23784 } else { 23785 addr = kallsyms_lookup_name(tname); 23786 } 23787 if (!addr) { 23788 module_put(mod); 23789 bpf_log(log, 23790 "The address of function %s cannot be found\n", 23791 tname); 23792 return -ENOENT; 23793 } 23794 } 23795 23796 if (prog->sleepable) { 23797 ret = -EINVAL; 23798 switch (prog->type) { 23799 case BPF_PROG_TYPE_TRACING: 23800 23801 /* fentry/fexit/fmod_ret progs can be sleepable if they are 23802 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 23803 */ 23804 if (!check_non_sleepable_error_inject(btf_id) && 23805 within_error_injection_list(addr)) 23806 ret = 0; 23807 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 23808 * in the fmodret id set with the KF_SLEEPABLE flag. 23809 */ 23810 else { 23811 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 23812 prog); 23813 23814 if (flags && (*flags & KF_SLEEPABLE)) 23815 ret = 0; 23816 } 23817 break; 23818 case BPF_PROG_TYPE_LSM: 23819 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 23820 * Only some of them are sleepable. 23821 */ 23822 if (bpf_lsm_is_sleepable_hook(btf_id)) 23823 ret = 0; 23824 break; 23825 default: 23826 break; 23827 } 23828 if (ret) { 23829 module_put(mod); 23830 bpf_log(log, "%s is not sleepable\n", tname); 23831 return ret; 23832 } 23833 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 23834 if (tgt_prog) { 23835 module_put(mod); 23836 bpf_log(log, "can't modify return codes of BPF programs\n"); 23837 return -EINVAL; 23838 } 23839 ret = -EINVAL; 23840 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 23841 !check_attach_modify_return(addr, tname)) 23842 ret = 0; 23843 if (ret) { 23844 module_put(mod); 23845 bpf_log(log, "%s() is not modifiable\n", tname); 23846 return ret; 23847 } 23848 } 23849 23850 break; 23851 } 23852 tgt_info->tgt_addr = addr; 23853 tgt_info->tgt_name = tname; 23854 tgt_info->tgt_type = t; 23855 tgt_info->tgt_mod = mod; 23856 return 0; 23857 } 23858 23859 BTF_SET_START(btf_id_deny) 23860 BTF_ID_UNUSED 23861 #ifdef CONFIG_SMP 23862 BTF_ID(func, migrate_disable) 23863 BTF_ID(func, migrate_enable) 23864 #endif 23865 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 23866 BTF_ID(func, rcu_read_unlock_strict) 23867 #endif 23868 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 23869 BTF_ID(func, preempt_count_add) 23870 BTF_ID(func, preempt_count_sub) 23871 #endif 23872 #ifdef CONFIG_PREEMPT_RCU 23873 BTF_ID(func, __rcu_read_lock) 23874 BTF_ID(func, __rcu_read_unlock) 23875 #endif 23876 BTF_SET_END(btf_id_deny) 23877 23878 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 23879 * Currently, we must manually list all __noreturn functions here. Once a more 23880 * robust solution is implemented, this workaround can be removed. 23881 */ 23882 BTF_SET_START(noreturn_deny) 23883 #ifdef CONFIG_IA32_EMULATION 23884 BTF_ID(func, __ia32_sys_exit) 23885 BTF_ID(func, __ia32_sys_exit_group) 23886 #endif 23887 #ifdef CONFIG_KUNIT 23888 BTF_ID(func, __kunit_abort) 23889 BTF_ID(func, kunit_try_catch_throw) 23890 #endif 23891 #ifdef CONFIG_MODULES 23892 BTF_ID(func, __module_put_and_kthread_exit) 23893 #endif 23894 #ifdef CONFIG_X86_64 23895 BTF_ID(func, __x64_sys_exit) 23896 BTF_ID(func, __x64_sys_exit_group) 23897 #endif 23898 BTF_ID(func, do_exit) 23899 BTF_ID(func, do_group_exit) 23900 BTF_ID(func, kthread_complete_and_exit) 23901 BTF_ID(func, kthread_exit) 23902 BTF_ID(func, make_task_dead) 23903 BTF_SET_END(noreturn_deny) 23904 23905 static bool can_be_sleepable(struct bpf_prog *prog) 23906 { 23907 if (prog->type == BPF_PROG_TYPE_TRACING) { 23908 switch (prog->expected_attach_type) { 23909 case BPF_TRACE_FENTRY: 23910 case BPF_TRACE_FEXIT: 23911 case BPF_MODIFY_RETURN: 23912 case BPF_TRACE_ITER: 23913 return true; 23914 default: 23915 return false; 23916 } 23917 } 23918 return prog->type == BPF_PROG_TYPE_LSM || 23919 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 23920 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 23921 } 23922 23923 static int check_attach_btf_id(struct bpf_verifier_env *env) 23924 { 23925 struct bpf_prog *prog = env->prog; 23926 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 23927 struct bpf_attach_target_info tgt_info = {}; 23928 u32 btf_id = prog->aux->attach_btf_id; 23929 struct bpf_trampoline *tr; 23930 int ret; 23931 u64 key; 23932 23933 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 23934 if (prog->sleepable) 23935 /* attach_btf_id checked to be zero already */ 23936 return 0; 23937 verbose(env, "Syscall programs can only be sleepable\n"); 23938 return -EINVAL; 23939 } 23940 23941 if (prog->sleepable && !can_be_sleepable(prog)) { 23942 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 23943 return -EINVAL; 23944 } 23945 23946 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 23947 return check_struct_ops_btf_id(env); 23948 23949 if (prog->type != BPF_PROG_TYPE_TRACING && 23950 prog->type != BPF_PROG_TYPE_LSM && 23951 prog->type != BPF_PROG_TYPE_EXT) 23952 return 0; 23953 23954 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 23955 if (ret) 23956 return ret; 23957 23958 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 23959 /* to make freplace equivalent to their targets, they need to 23960 * inherit env->ops and expected_attach_type for the rest of the 23961 * verification 23962 */ 23963 env->ops = bpf_verifier_ops[tgt_prog->type]; 23964 prog->expected_attach_type = tgt_prog->expected_attach_type; 23965 } 23966 23967 /* store info about the attachment target that will be used later */ 23968 prog->aux->attach_func_proto = tgt_info.tgt_type; 23969 prog->aux->attach_func_name = tgt_info.tgt_name; 23970 prog->aux->mod = tgt_info.tgt_mod; 23971 23972 if (tgt_prog) { 23973 prog->aux->saved_dst_prog_type = tgt_prog->type; 23974 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 23975 } 23976 23977 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 23978 prog->aux->attach_btf_trace = true; 23979 return 0; 23980 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 23981 return bpf_iter_prog_supported(prog); 23982 } 23983 23984 if (prog->type == BPF_PROG_TYPE_LSM) { 23985 ret = bpf_lsm_verify_prog(&env->log, prog); 23986 if (ret < 0) 23987 return ret; 23988 } else if (prog->type == BPF_PROG_TYPE_TRACING && 23989 btf_id_set_contains(&btf_id_deny, btf_id)) { 23990 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 23991 tgt_info.tgt_name); 23992 return -EINVAL; 23993 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 23994 prog->expected_attach_type == BPF_MODIFY_RETURN) && 23995 btf_id_set_contains(&noreturn_deny, btf_id)) { 23996 verbose(env, "Attaching fexit/fmod_ret to __noreturn function '%s' is rejected.\n", 23997 tgt_info.tgt_name); 23998 return -EINVAL; 23999 } 24000 24001 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 24002 tr = bpf_trampoline_get(key, &tgt_info); 24003 if (!tr) 24004 return -ENOMEM; 24005 24006 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 24007 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 24008 24009 prog->aux->dst_trampoline = tr; 24010 return 0; 24011 } 24012 24013 struct btf *bpf_get_btf_vmlinux(void) 24014 { 24015 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 24016 mutex_lock(&bpf_verifier_lock); 24017 if (!btf_vmlinux) 24018 btf_vmlinux = btf_parse_vmlinux(); 24019 mutex_unlock(&bpf_verifier_lock); 24020 } 24021 return btf_vmlinux; 24022 } 24023 24024 /* 24025 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 24026 * this case expect that every file descriptor in the array is either a map or 24027 * a BTF. Everything else is considered to be trash. 24028 */ 24029 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) 24030 { 24031 struct bpf_map *map; 24032 struct btf *btf; 24033 CLASS(fd, f)(fd); 24034 int err; 24035 24036 map = __bpf_map_get(f); 24037 if (!IS_ERR(map)) { 24038 err = __add_used_map(env, map); 24039 if (err < 0) 24040 return err; 24041 return 0; 24042 } 24043 24044 btf = __btf_get_by_fd(f); 24045 if (!IS_ERR(btf)) { 24046 err = __add_used_btf(env, btf); 24047 if (err < 0) 24048 return err; 24049 return 0; 24050 } 24051 24052 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 24053 return PTR_ERR(map); 24054 } 24055 24056 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr) 24057 { 24058 size_t size = sizeof(int); 24059 int ret; 24060 int fd; 24061 u32 i; 24062 24063 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 24064 24065 /* 24066 * The only difference between old (no fd_array_cnt is given) and new 24067 * APIs is that in the latter case the fd_array is expected to be 24068 * continuous and is scanned for map fds right away 24069 */ 24070 if (!attr->fd_array_cnt) 24071 return 0; 24072 24073 /* Check for integer overflow */ 24074 if (attr->fd_array_cnt >= (U32_MAX / size)) { 24075 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt); 24076 return -EINVAL; 24077 } 24078 24079 for (i = 0; i < attr->fd_array_cnt; i++) { 24080 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size)) 24081 return -EFAULT; 24082 24083 ret = add_fd_from_fd_array(env, fd); 24084 if (ret) 24085 return ret; 24086 } 24087 24088 return 0; 24089 } 24090 24091 static bool can_fallthrough(struct bpf_insn *insn) 24092 { 24093 u8 class = BPF_CLASS(insn->code); 24094 u8 opcode = BPF_OP(insn->code); 24095 24096 if (class != BPF_JMP && class != BPF_JMP32) 24097 return true; 24098 24099 if (opcode == BPF_EXIT || opcode == BPF_JA) 24100 return false; 24101 24102 return true; 24103 } 24104 24105 static bool can_jump(struct bpf_insn *insn) 24106 { 24107 u8 class = BPF_CLASS(insn->code); 24108 u8 opcode = BPF_OP(insn->code); 24109 24110 if (class != BPF_JMP && class != BPF_JMP32) 24111 return false; 24112 24113 switch (opcode) { 24114 case BPF_JA: 24115 case BPF_JEQ: 24116 case BPF_JNE: 24117 case BPF_JLT: 24118 case BPF_JLE: 24119 case BPF_JGT: 24120 case BPF_JGE: 24121 case BPF_JSGT: 24122 case BPF_JSGE: 24123 case BPF_JSLT: 24124 case BPF_JSLE: 24125 case BPF_JCOND: 24126 case BPF_JSET: 24127 return true; 24128 } 24129 24130 return false; 24131 } 24132 24133 static int insn_successors(struct bpf_prog *prog, u32 idx, u32 succ[2]) 24134 { 24135 struct bpf_insn *insn = &prog->insnsi[idx]; 24136 int i = 0, insn_sz; 24137 u32 dst; 24138 24139 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 24140 if (can_fallthrough(insn) && idx + 1 < prog->len) 24141 succ[i++] = idx + insn_sz; 24142 24143 if (can_jump(insn)) { 24144 dst = idx + jmp_offset(insn) + 1; 24145 if (i == 0 || succ[0] != dst) 24146 succ[i++] = dst; 24147 } 24148 24149 return i; 24150 } 24151 24152 /* Each field is a register bitmask */ 24153 struct insn_live_regs { 24154 u16 use; /* registers read by instruction */ 24155 u16 def; /* registers written by instruction */ 24156 u16 in; /* registers that may be alive before instruction */ 24157 u16 out; /* registers that may be alive after instruction */ 24158 }; 24159 24160 /* Bitmask with 1s for all caller saved registers */ 24161 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 24162 24163 /* Compute info->{use,def} fields for the instruction */ 24164 static void compute_insn_live_regs(struct bpf_verifier_env *env, 24165 struct bpf_insn *insn, 24166 struct insn_live_regs *info) 24167 { 24168 struct call_summary cs; 24169 u8 class = BPF_CLASS(insn->code); 24170 u8 code = BPF_OP(insn->code); 24171 u8 mode = BPF_MODE(insn->code); 24172 u16 src = BIT(insn->src_reg); 24173 u16 dst = BIT(insn->dst_reg); 24174 u16 r0 = BIT(0); 24175 u16 def = 0; 24176 u16 use = 0xffff; 24177 24178 switch (class) { 24179 case BPF_LD: 24180 switch (mode) { 24181 case BPF_IMM: 24182 if (BPF_SIZE(insn->code) == BPF_DW) { 24183 def = dst; 24184 use = 0; 24185 } 24186 break; 24187 case BPF_LD | BPF_ABS: 24188 case BPF_LD | BPF_IND: 24189 /* stick with defaults */ 24190 break; 24191 } 24192 break; 24193 case BPF_LDX: 24194 switch (mode) { 24195 case BPF_MEM: 24196 case BPF_MEMSX: 24197 def = dst; 24198 use = src; 24199 break; 24200 } 24201 break; 24202 case BPF_ST: 24203 switch (mode) { 24204 case BPF_MEM: 24205 def = 0; 24206 use = dst; 24207 break; 24208 } 24209 break; 24210 case BPF_STX: 24211 switch (mode) { 24212 case BPF_MEM: 24213 def = 0; 24214 use = dst | src; 24215 break; 24216 case BPF_ATOMIC: 24217 switch (insn->imm) { 24218 case BPF_CMPXCHG: 24219 use = r0 | dst | src; 24220 def = r0; 24221 break; 24222 case BPF_LOAD_ACQ: 24223 def = dst; 24224 use = src; 24225 break; 24226 case BPF_STORE_REL: 24227 def = 0; 24228 use = dst | src; 24229 break; 24230 default: 24231 use = dst | src; 24232 if (insn->imm & BPF_FETCH) 24233 def = src; 24234 else 24235 def = 0; 24236 } 24237 break; 24238 } 24239 break; 24240 case BPF_ALU: 24241 case BPF_ALU64: 24242 switch (code) { 24243 case BPF_END: 24244 use = dst; 24245 def = dst; 24246 break; 24247 case BPF_MOV: 24248 def = dst; 24249 if (BPF_SRC(insn->code) == BPF_K) 24250 use = 0; 24251 else 24252 use = src; 24253 break; 24254 default: 24255 def = dst; 24256 if (BPF_SRC(insn->code) == BPF_K) 24257 use = dst; 24258 else 24259 use = dst | src; 24260 } 24261 break; 24262 case BPF_JMP: 24263 case BPF_JMP32: 24264 switch (code) { 24265 case BPF_JA: 24266 case BPF_JCOND: 24267 def = 0; 24268 use = 0; 24269 break; 24270 case BPF_EXIT: 24271 def = 0; 24272 use = r0; 24273 break; 24274 case BPF_CALL: 24275 def = ALL_CALLER_SAVED_REGS; 24276 use = def & ~BIT(BPF_REG_0); 24277 if (get_call_summary(env, insn, &cs)) 24278 use = GENMASK(cs.num_params, 1); 24279 break; 24280 default: 24281 def = 0; 24282 if (BPF_SRC(insn->code) == BPF_K) 24283 use = dst; 24284 else 24285 use = dst | src; 24286 } 24287 break; 24288 } 24289 24290 info->def = def; 24291 info->use = use; 24292 } 24293 24294 /* Compute may-live registers after each instruction in the program. 24295 * The register is live after the instruction I if it is read by some 24296 * instruction S following I during program execution and is not 24297 * overwritten between I and S. 24298 * 24299 * Store result in env->insn_aux_data[i].live_regs. 24300 */ 24301 static int compute_live_registers(struct bpf_verifier_env *env) 24302 { 24303 struct bpf_insn_aux_data *insn_aux = env->insn_aux_data; 24304 struct bpf_insn *insns = env->prog->insnsi; 24305 struct insn_live_regs *state; 24306 int insn_cnt = env->prog->len; 24307 int err = 0, i, j; 24308 bool changed; 24309 24310 /* Use the following algorithm: 24311 * - define the following: 24312 * - I.use : a set of all registers read by instruction I; 24313 * - I.def : a set of all registers written by instruction I; 24314 * - I.in : a set of all registers that may be alive before I execution; 24315 * - I.out : a set of all registers that may be alive after I execution; 24316 * - insn_successors(I): a set of instructions S that might immediately 24317 * follow I for some program execution; 24318 * - associate separate empty sets 'I.in' and 'I.out' with each instruction; 24319 * - visit each instruction in a postorder and update 24320 * state[i].in, state[i].out as follows: 24321 * 24322 * state[i].out = U [state[s].in for S in insn_successors(i)] 24323 * state[i].in = (state[i].out / state[i].def) U state[i].use 24324 * 24325 * (where U stands for set union, / stands for set difference) 24326 * - repeat the computation while {in,out} fields changes for 24327 * any instruction. 24328 */ 24329 state = kvcalloc(insn_cnt, sizeof(*state), GFP_KERNEL_ACCOUNT); 24330 if (!state) { 24331 err = -ENOMEM; 24332 goto out; 24333 } 24334 24335 for (i = 0; i < insn_cnt; ++i) 24336 compute_insn_live_regs(env, &insns[i], &state[i]); 24337 24338 changed = true; 24339 while (changed) { 24340 changed = false; 24341 for (i = 0; i < env->cfg.cur_postorder; ++i) { 24342 int insn_idx = env->cfg.insn_postorder[i]; 24343 struct insn_live_regs *live = &state[insn_idx]; 24344 int succ_num; 24345 u32 succ[2]; 24346 u16 new_out = 0; 24347 u16 new_in = 0; 24348 24349 succ_num = insn_successors(env->prog, insn_idx, succ); 24350 for (int s = 0; s < succ_num; ++s) 24351 new_out |= state[succ[s]].in; 24352 new_in = (new_out & ~live->def) | live->use; 24353 if (new_out != live->out || new_in != live->in) { 24354 live->in = new_in; 24355 live->out = new_out; 24356 changed = true; 24357 } 24358 } 24359 } 24360 24361 for (i = 0; i < insn_cnt; ++i) 24362 insn_aux[i].live_regs_before = state[i].in; 24363 24364 if (env->log.level & BPF_LOG_LEVEL2) { 24365 verbose(env, "Live regs before insn:\n"); 24366 for (i = 0; i < insn_cnt; ++i) { 24367 if (env->insn_aux_data[i].scc) 24368 verbose(env, "%3d ", env->insn_aux_data[i].scc); 24369 else 24370 verbose(env, " "); 24371 verbose(env, "%3d: ", i); 24372 for (j = BPF_REG_0; j < BPF_REG_10; ++j) 24373 if (insn_aux[i].live_regs_before & BIT(j)) 24374 verbose(env, "%d", j); 24375 else 24376 verbose(env, "."); 24377 verbose(env, " "); 24378 verbose_insn(env, &insns[i]); 24379 if (bpf_is_ldimm64(&insns[i])) 24380 i++; 24381 } 24382 } 24383 24384 out: 24385 kvfree(state); 24386 kvfree(env->cfg.insn_postorder); 24387 env->cfg.insn_postorder = NULL; 24388 env->cfg.cur_postorder = 0; 24389 return err; 24390 } 24391 24392 /* 24393 * Compute strongly connected components (SCCs) on the CFG. 24394 * Assign an SCC number to each instruction, recorded in env->insn_aux[*].scc. 24395 * If instruction is a sole member of its SCC and there are no self edges, 24396 * assign it SCC number of zero. 24397 * Uses a non-recursive adaptation of Tarjan's algorithm for SCC computation. 24398 */ 24399 static int compute_scc(struct bpf_verifier_env *env) 24400 { 24401 const u32 NOT_ON_STACK = U32_MAX; 24402 24403 struct bpf_insn_aux_data *aux = env->insn_aux_data; 24404 const u32 insn_cnt = env->prog->len; 24405 int stack_sz, dfs_sz, err = 0; 24406 u32 *stack, *pre, *low, *dfs; 24407 u32 succ_cnt, i, j, t, w; 24408 u32 next_preorder_num; 24409 u32 next_scc_id; 24410 bool assign_scc; 24411 u32 succ[2]; 24412 24413 next_preorder_num = 1; 24414 next_scc_id = 1; 24415 /* 24416 * - 'stack' accumulates vertices in DFS order, see invariant comment below; 24417 * - 'pre[t] == p' => preorder number of vertex 't' is 'p'; 24418 * - 'low[t] == n' => smallest preorder number of the vertex reachable from 't' is 'n'; 24419 * - 'dfs' DFS traversal stack, used to emulate explicit recursion. 24420 */ 24421 stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 24422 pre = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 24423 low = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL_ACCOUNT); 24424 dfs = kvcalloc(insn_cnt, sizeof(*dfs), GFP_KERNEL_ACCOUNT); 24425 if (!stack || !pre || !low || !dfs) { 24426 err = -ENOMEM; 24427 goto exit; 24428 } 24429 /* 24430 * References: 24431 * [1] R. Tarjan "Depth-First Search and Linear Graph Algorithms" 24432 * [2] D. J. Pearce "A Space-Efficient Algorithm for Finding Strongly Connected Components" 24433 * 24434 * The algorithm maintains the following invariant: 24435 * - suppose there is a path 'u' ~> 'v', such that 'pre[v] < pre[u]'; 24436 * - then, vertex 'u' remains on stack while vertex 'v' is on stack. 24437 * 24438 * Consequently: 24439 * - If 'low[v] < pre[v]', there is a path from 'v' to some vertex 'u', 24440 * such that 'pre[u] == low[v]'; vertex 'u' is currently on the stack, 24441 * and thus there is an SCC (loop) containing both 'u' and 'v'. 24442 * - If 'low[v] == pre[v]', loops containing 'v' have been explored, 24443 * and 'v' can be considered the root of some SCC. 24444 * 24445 * Here is a pseudo-code for an explicitly recursive version of the algorithm: 24446 * 24447 * NOT_ON_STACK = insn_cnt + 1 24448 * pre = [0] * insn_cnt 24449 * low = [0] * insn_cnt 24450 * scc = [0] * insn_cnt 24451 * stack = [] 24452 * 24453 * next_preorder_num = 1 24454 * next_scc_id = 1 24455 * 24456 * def recur(w): 24457 * nonlocal next_preorder_num 24458 * nonlocal next_scc_id 24459 * 24460 * pre[w] = next_preorder_num 24461 * low[w] = next_preorder_num 24462 * next_preorder_num += 1 24463 * stack.append(w) 24464 * for s in successors(w): 24465 * # Note: for classic algorithm the block below should look as: 24466 * # 24467 * # if pre[s] == 0: 24468 * # recur(s) 24469 * # low[w] = min(low[w], low[s]) 24470 * # elif low[s] != NOT_ON_STACK: 24471 * # low[w] = min(low[w], pre[s]) 24472 * # 24473 * # But replacing both 'min' instructions with 'low[w] = min(low[w], low[s])' 24474 * # does not break the invariant and makes itartive version of the algorithm 24475 * # simpler. See 'Algorithm #3' from [2]. 24476 * 24477 * # 's' not yet visited 24478 * if pre[s] == 0: 24479 * recur(s) 24480 * # if 's' is on stack, pick lowest reachable preorder number from it; 24481 * # if 's' is not on stack 'low[s] == NOT_ON_STACK > low[w]', 24482 * # so 'min' would be a noop. 24483 * low[w] = min(low[w], low[s]) 24484 * 24485 * if low[w] == pre[w]: 24486 * # 'w' is the root of an SCC, pop all vertices 24487 * # below 'w' on stack and assign same SCC to them. 24488 * while True: 24489 * t = stack.pop() 24490 * low[t] = NOT_ON_STACK 24491 * scc[t] = next_scc_id 24492 * if t == w: 24493 * break 24494 * next_scc_id += 1 24495 * 24496 * for i in range(0, insn_cnt): 24497 * if pre[i] == 0: 24498 * recur(i) 24499 * 24500 * Below implementation replaces explicit recursion with array 'dfs'. 24501 */ 24502 for (i = 0; i < insn_cnt; i++) { 24503 if (pre[i]) 24504 continue; 24505 stack_sz = 0; 24506 dfs_sz = 1; 24507 dfs[0] = i; 24508 dfs_continue: 24509 while (dfs_sz) { 24510 w = dfs[dfs_sz - 1]; 24511 if (pre[w] == 0) { 24512 low[w] = next_preorder_num; 24513 pre[w] = next_preorder_num; 24514 next_preorder_num++; 24515 stack[stack_sz++] = w; 24516 } 24517 /* Visit 'w' successors */ 24518 succ_cnt = insn_successors(env->prog, w, succ); 24519 for (j = 0; j < succ_cnt; ++j) { 24520 if (pre[succ[j]]) { 24521 low[w] = min(low[w], low[succ[j]]); 24522 } else { 24523 dfs[dfs_sz++] = succ[j]; 24524 goto dfs_continue; 24525 } 24526 } 24527 /* 24528 * Preserve the invariant: if some vertex above in the stack 24529 * is reachable from 'w', keep 'w' on the stack. 24530 */ 24531 if (low[w] < pre[w]) { 24532 dfs_sz--; 24533 goto dfs_continue; 24534 } 24535 /* 24536 * Assign SCC number only if component has two or more elements, 24537 * or if component has a self reference. 24538 */ 24539 assign_scc = stack[stack_sz - 1] != w; 24540 for (j = 0; j < succ_cnt; ++j) { 24541 if (succ[j] == w) { 24542 assign_scc = true; 24543 break; 24544 } 24545 } 24546 /* Pop component elements from stack */ 24547 do { 24548 t = stack[--stack_sz]; 24549 low[t] = NOT_ON_STACK; 24550 if (assign_scc) 24551 aux[t].scc = next_scc_id; 24552 } while (t != w); 24553 if (assign_scc) 24554 next_scc_id++; 24555 dfs_sz--; 24556 } 24557 } 24558 env->scc_info = kvcalloc(next_scc_id, sizeof(*env->scc_info), GFP_KERNEL_ACCOUNT); 24559 if (!env->scc_info) { 24560 err = -ENOMEM; 24561 goto exit; 24562 } 24563 env->scc_cnt = next_scc_id; 24564 exit: 24565 kvfree(stack); 24566 kvfree(pre); 24567 kvfree(low); 24568 kvfree(dfs); 24569 return err; 24570 } 24571 24572 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 24573 { 24574 u64 start_time = ktime_get_ns(); 24575 struct bpf_verifier_env *env; 24576 int i, len, ret = -EINVAL, err; 24577 u32 log_true_size; 24578 bool is_priv; 24579 24580 BTF_TYPE_EMIT(enum bpf_features); 24581 24582 /* no program is valid */ 24583 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 24584 return -EINVAL; 24585 24586 /* 'struct bpf_verifier_env' can be global, but since it's not small, 24587 * allocate/free it every time bpf_check() is called 24588 */ 24589 env = kvzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL_ACCOUNT); 24590 if (!env) 24591 return -ENOMEM; 24592 24593 env->bt.env = env; 24594 24595 len = (*prog)->len; 24596 env->insn_aux_data = 24597 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 24598 ret = -ENOMEM; 24599 if (!env->insn_aux_data) 24600 goto err_free_env; 24601 for (i = 0; i < len; i++) 24602 env->insn_aux_data[i].orig_idx = i; 24603 env->prog = *prog; 24604 env->ops = bpf_verifier_ops[env->prog->type]; 24605 24606 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 24607 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 24608 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 24609 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 24610 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 24611 24612 bpf_get_btf_vmlinux(); 24613 24614 /* grab the mutex to protect few globals used by verifier */ 24615 if (!is_priv) 24616 mutex_lock(&bpf_verifier_lock); 24617 24618 /* user could have requested verbose verifier output 24619 * and supplied buffer to store the verification trace 24620 */ 24621 ret = bpf_vlog_init(&env->log, attr->log_level, 24622 (char __user *) (unsigned long) attr->log_buf, 24623 attr->log_size); 24624 if (ret) 24625 goto err_unlock; 24626 24627 ret = process_fd_array(env, attr, uattr); 24628 if (ret) 24629 goto skip_full_check; 24630 24631 mark_verifier_state_clean(env); 24632 24633 if (IS_ERR(btf_vmlinux)) { 24634 /* Either gcc or pahole or kernel are broken. */ 24635 verbose(env, "in-kernel BTF is malformed\n"); 24636 ret = PTR_ERR(btf_vmlinux); 24637 goto skip_full_check; 24638 } 24639 24640 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 24641 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 24642 env->strict_alignment = true; 24643 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 24644 env->strict_alignment = false; 24645 24646 if (is_priv) 24647 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 24648 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 24649 24650 env->explored_states = kvcalloc(state_htab_size(env), 24651 sizeof(struct list_head), 24652 GFP_KERNEL_ACCOUNT); 24653 ret = -ENOMEM; 24654 if (!env->explored_states) 24655 goto skip_full_check; 24656 24657 for (i = 0; i < state_htab_size(env); i++) 24658 INIT_LIST_HEAD(&env->explored_states[i]); 24659 INIT_LIST_HEAD(&env->free_list); 24660 24661 ret = check_btf_info_early(env, attr, uattr); 24662 if (ret < 0) 24663 goto skip_full_check; 24664 24665 ret = add_subprog_and_kfunc(env); 24666 if (ret < 0) 24667 goto skip_full_check; 24668 24669 ret = check_subprogs(env); 24670 if (ret < 0) 24671 goto skip_full_check; 24672 24673 ret = check_btf_info(env, attr, uattr); 24674 if (ret < 0) 24675 goto skip_full_check; 24676 24677 ret = resolve_pseudo_ldimm64(env); 24678 if (ret < 0) 24679 goto skip_full_check; 24680 24681 if (bpf_prog_is_offloaded(env->prog->aux)) { 24682 ret = bpf_prog_offload_verifier_prep(env->prog); 24683 if (ret) 24684 goto skip_full_check; 24685 } 24686 24687 ret = check_cfg(env); 24688 if (ret < 0) 24689 goto skip_full_check; 24690 24691 ret = check_attach_btf_id(env); 24692 if (ret) 24693 goto skip_full_check; 24694 24695 ret = compute_scc(env); 24696 if (ret < 0) 24697 goto skip_full_check; 24698 24699 ret = compute_live_registers(env); 24700 if (ret < 0) 24701 goto skip_full_check; 24702 24703 ret = mark_fastcall_patterns(env); 24704 if (ret < 0) 24705 goto skip_full_check; 24706 24707 ret = do_check_main(env); 24708 ret = ret ?: do_check_subprogs(env); 24709 24710 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 24711 ret = bpf_prog_offload_finalize(env); 24712 24713 skip_full_check: 24714 kvfree(env->explored_states); 24715 24716 /* might decrease stack depth, keep it before passes that 24717 * allocate additional slots. 24718 */ 24719 if (ret == 0) 24720 ret = remove_fastcall_spills_fills(env); 24721 24722 if (ret == 0) 24723 ret = check_max_stack_depth(env); 24724 24725 /* instruction rewrites happen after this point */ 24726 if (ret == 0) 24727 ret = optimize_bpf_loop(env); 24728 24729 if (is_priv) { 24730 if (ret == 0) 24731 opt_hard_wire_dead_code_branches(env); 24732 if (ret == 0) 24733 ret = opt_remove_dead_code(env); 24734 if (ret == 0) 24735 ret = opt_remove_nops(env); 24736 } else { 24737 if (ret == 0) 24738 sanitize_dead_code(env); 24739 } 24740 24741 if (ret == 0) 24742 /* program is valid, convert *(u32*)(ctx + off) accesses */ 24743 ret = convert_ctx_accesses(env); 24744 24745 if (ret == 0) 24746 ret = do_misc_fixups(env); 24747 24748 /* do 32-bit optimization after insn patching has done so those patched 24749 * insns could be handled correctly. 24750 */ 24751 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 24752 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 24753 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 24754 : false; 24755 } 24756 24757 if (ret == 0) 24758 ret = fixup_call_args(env); 24759 24760 env->verification_time = ktime_get_ns() - start_time; 24761 print_verification_stats(env); 24762 env->prog->aux->verified_insns = env->insn_processed; 24763 24764 /* preserve original error even if log finalization is successful */ 24765 err = bpf_vlog_finalize(&env->log, &log_true_size); 24766 if (err) 24767 ret = err; 24768 24769 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 24770 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 24771 &log_true_size, sizeof(log_true_size))) { 24772 ret = -EFAULT; 24773 goto err_release_maps; 24774 } 24775 24776 if (ret) 24777 goto err_release_maps; 24778 24779 if (env->used_map_cnt) { 24780 /* if program passed verifier, update used_maps in bpf_prog_info */ 24781 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 24782 sizeof(env->used_maps[0]), 24783 GFP_KERNEL_ACCOUNT); 24784 24785 if (!env->prog->aux->used_maps) { 24786 ret = -ENOMEM; 24787 goto err_release_maps; 24788 } 24789 24790 memcpy(env->prog->aux->used_maps, env->used_maps, 24791 sizeof(env->used_maps[0]) * env->used_map_cnt); 24792 env->prog->aux->used_map_cnt = env->used_map_cnt; 24793 } 24794 if (env->used_btf_cnt) { 24795 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 24796 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 24797 sizeof(env->used_btfs[0]), 24798 GFP_KERNEL_ACCOUNT); 24799 if (!env->prog->aux->used_btfs) { 24800 ret = -ENOMEM; 24801 goto err_release_maps; 24802 } 24803 24804 memcpy(env->prog->aux->used_btfs, env->used_btfs, 24805 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 24806 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 24807 } 24808 if (env->used_map_cnt || env->used_btf_cnt) { 24809 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 24810 * bpf_ld_imm64 instructions 24811 */ 24812 convert_pseudo_ld_imm64(env); 24813 } 24814 24815 adjust_btf_func(env); 24816 24817 err_release_maps: 24818 if (!env->prog->aux->used_maps) 24819 /* if we didn't copy map pointers into bpf_prog_info, release 24820 * them now. Otherwise free_used_maps() will release them. 24821 */ 24822 release_maps(env); 24823 if (!env->prog->aux->used_btfs) 24824 release_btfs(env); 24825 24826 /* extension progs temporarily inherit the attach_type of their targets 24827 for verification purposes, so set it back to zero before returning 24828 */ 24829 if (env->prog->type == BPF_PROG_TYPE_EXT) 24830 env->prog->expected_attach_type = 0; 24831 24832 *prog = env->prog; 24833 24834 module_put(env->attach_btf_mod); 24835 err_unlock: 24836 if (!is_priv) 24837 mutex_unlock(&bpf_verifier_lock); 24838 vfree(env->insn_aux_data); 24839 err_free_env: 24840 kvfree(env->cfg.insn_postorder); 24841 kvfree(env->scc_info); 24842 kvfree(env); 24843 return ret; 24844 } 24845