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/security.h> 26 #include <linux/verification.h> 27 #include <linux/btf_ids.h> 28 #include <linux/poison.h> 29 #include <linux/module.h> 30 #include <linux/cpumask.h> 31 #include <linux/cnum.h> 32 #include <linux/bpf_mem_alloc.h> 33 #include <net/xdp.h> 34 #include <linux/trace_events.h> 35 #include <linux/kallsyms.h> 36 37 #include "disasm.h" 38 39 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 40 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 41 [_id] = & _name ## _verifier_ops, 42 #define BPF_MAP_TYPE(_id, _ops) 43 #define BPF_LINK_TYPE(_id, _name) 44 #include <linux/bpf_types.h> 45 #undef BPF_PROG_TYPE 46 #undef BPF_MAP_TYPE 47 #undef BPF_LINK_TYPE 48 }; 49 50 enum bpf_features { 51 BPF_FEAT_RDONLY_CAST_TO_VOID = 0, 52 BPF_FEAT_STREAMS = 1, 53 __MAX_BPF_FEAT, 54 }; 55 56 struct bpf_mem_alloc bpf_global_percpu_ma; 57 static bool bpf_global_percpu_ma_set; 58 59 /* bpf_check() is a static code analyzer that walks eBPF program 60 * instruction by instruction and updates register/stack state. 61 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 62 * 63 * The first pass is depth-first-search to check that the program is a DAG. 64 * It rejects the following programs: 65 * - larger than BPF_MAXINSNS insns 66 * - if loop is present (detected via back-edge) 67 * - unreachable insns exist (shouldn't be a forest. program = one function) 68 * - out of bounds or malformed jumps 69 * The second pass is all possible path descent from the 1st insn. 70 * Since it's analyzing all paths through the program, the length of the 71 * analysis is limited to 64k insn, which may be hit even if total number of 72 * insn is less then 4K, but there are too many branches that change stack/regs. 73 * Number of 'branches to be analyzed' is limited to 1k 74 * 75 * On entry to each instruction, each register has a type, and the instruction 76 * changes the types of the registers depending on instruction semantics. 77 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 78 * copied to R1. 79 * 80 * All registers are 64-bit. 81 * R0 - return register 82 * R1-R5 argument passing registers 83 * R6-R9 callee saved registers 84 * R10 - frame pointer read-only 85 * 86 * At the start of BPF program the register R1 contains a pointer to bpf_context 87 * and has type PTR_TO_CTX. 88 * 89 * Verifier tracks arithmetic operations on pointers in case: 90 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 91 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 92 * 1st insn copies R10 (which has FRAME_PTR) type into R1 93 * and 2nd arithmetic instruction is pattern matched to recognize 94 * that it wants to construct a pointer to some element within stack. 95 * So after 2nd insn, the register R1 has type PTR_TO_STACK 96 * (and -20 constant is saved for further stack bounds checking). 97 * Meaning that this reg is a pointer to stack plus known immediate constant. 98 * 99 * Most of the time the registers have SCALAR_VALUE type, which 100 * means the register has some value, but it's not a valid pointer. 101 * (like pointer plus pointer becomes SCALAR_VALUE type) 102 * 103 * When verifier sees load or store instructions the type of base register 104 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 105 * four pointer types recognized by check_mem_access() function. 106 * 107 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 108 * and the range of [ptr, ptr + map's value_size) is accessible. 109 * 110 * registers used to pass values to function calls are checked against 111 * function argument constraints. 112 * 113 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 114 * It means that the register type passed to this function must be 115 * PTR_TO_STACK and it will be used inside the function as 116 * 'pointer to map element key' 117 * 118 * For example the argument constraints for bpf_map_lookup_elem(): 119 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 120 * .arg1_type = ARG_CONST_MAP_PTR, 121 * .arg2_type = ARG_PTR_TO_MAP_KEY, 122 * 123 * ret_type says that this function returns 'pointer to map elem value or null' 124 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 125 * 2nd argument should be a pointer to stack, which will be used inside 126 * the helper function as a pointer to map element key. 127 * 128 * On the kernel side the helper function looks like: 129 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 130 * { 131 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 132 * void *key = (void *) (unsigned long) r2; 133 * void *value; 134 * 135 * here kernel can access 'key' and 'map' pointers safely, knowing that 136 * [key, key + map->key_size) bytes are valid and were initialized on 137 * the stack of eBPF program. 138 * } 139 * 140 * Corresponding eBPF program may look like: 141 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 142 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 143 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 144 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 145 * here verifier looks at prototype of map_lookup_elem() and sees: 146 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 147 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 148 * 149 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 150 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 151 * and were initialized prior to this call. 152 * If it's ok, then verifier allows this BPF_CALL insn and looks at 153 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 154 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 155 * returns either pointer to map value or NULL. 156 * 157 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 158 * insn, the register holding that pointer in the true branch changes state to 159 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 160 * branch. See check_cond_jmp_op(). 161 * 162 * After the call R0 is set to return type of the function and registers R1-R5 163 * are set to NOT_INIT to indicate that they are no longer readable. 164 * 165 * The following reference types represent a potential reference to a kernel 166 * resource which, after first being allocated, must be checked and freed by 167 * the BPF program: 168 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 169 * 170 * When the verifier sees a helper call return a reference type, it allocates a 171 * pointer id for the reference and stores it in the current function state. 172 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 173 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 174 * passes through a NULL-check conditional. For the branch wherein the state is 175 * changed to CONST_IMM, the verifier releases the reference. 176 * 177 * For each helper function that allocates a reference, such as 178 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 179 * bpf_sk_release(). When a reference type passes into the release function, 180 * the verifier also releases the reference. If any unchecked or unreleased 181 * reference remains at the end of the program, the verifier rejects it. 182 */ 183 184 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 185 struct bpf_verifier_stack_elem { 186 /* verifier state is 'st' 187 * before processing instruction 'insn_idx' 188 * and after processing instruction 'prev_insn_idx' 189 */ 190 struct bpf_verifier_state st; 191 int insn_idx; 192 int prev_insn_idx; 193 struct bpf_verifier_stack_elem *next; 194 /* length of verifier log at the time this state was pushed on stack */ 195 u32 log_pos; 196 }; 197 198 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 199 #define BPF_COMPLEXITY_LIMIT_STATES 64 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, int parent_id); 206 static int release_reference_nomark(struct bpf_verifier_state *state, int id); 207 static int release_reference(struct bpf_verifier_env *env, int id); 208 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 209 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env); 210 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 211 static bool is_tracing_prog_type(enum bpf_prog_type type); 212 static int ref_set_non_owning(struct bpf_verifier_env *env, 213 struct bpf_reg_state *reg); 214 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg); 215 static inline bool in_sleepable_context(struct bpf_verifier_env *env); 216 static const char *non_sleepable_context_description(struct bpf_verifier_env *env); 217 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 218 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 219 220 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 221 struct bpf_map *map, 222 bool unpriv, bool poison) 223 { 224 unpriv |= bpf_map_ptr_unpriv(aux); 225 aux->map_ptr_state.unpriv = unpriv; 226 aux->map_ptr_state.poison = poison; 227 aux->map_ptr_state.map_ptr = map; 228 } 229 230 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 231 { 232 bool poisoned = bpf_map_key_poisoned(aux); 233 234 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 235 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 236 } 237 238 static void update_ref_obj(struct ref_obj_desc *ref_obj, struct bpf_reg_state *reg) 239 { 240 ref_obj->id = reg->id; 241 ref_obj->parent_id = reg->parent_id; 242 ref_obj->cnt++; 243 } 244 245 static int validate_ref_obj(struct bpf_verifier_env *env, struct ref_obj_desc *ref_obj) 246 { 247 if (ref_obj->cnt > 1) { 248 verifier_bug(env, "function expects only one referenced object but got %d\n", 249 ref_obj->cnt); 250 return -EFAULT; 251 } 252 253 return 0; 254 } 255 256 struct bpf_kfunc_meta { 257 struct btf *btf; 258 const struct btf_type *proto; 259 const char *name; 260 const u32 *flags; 261 s32 id; 262 }; 263 264 struct btf *btf_vmlinux; 265 266 typedef struct argno { 267 int argno; 268 } argno_t; 269 270 static argno_t argno_from_reg(u32 regno) 271 { 272 return (argno_t){ .argno = regno }; 273 } 274 275 static argno_t argno_from_arg(u32 arg) 276 { 277 return (argno_t){ .argno = -arg }; 278 } 279 280 static int reg_from_argno(argno_t a) 281 { 282 if (a.argno >= 0) 283 return a.argno; 284 if (a.argno >= -MAX_BPF_FUNC_REG_ARGS) 285 return -a.argno; 286 return -1; 287 } 288 289 static int arg_from_argno(argno_t a) 290 { 291 if (a.argno < 0) 292 return -a.argno; 293 return -1; 294 } 295 296 static int arg_idx_from_argno(argno_t a) 297 { 298 return arg_from_argno(a) - 1; 299 } 300 301 static const char *btf_type_name(const struct btf *btf, u32 id) 302 { 303 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 304 } 305 306 static DEFINE_MUTEX(bpf_verifier_lock); 307 static DEFINE_MUTEX(btf_vmlinux_lock); 308 static DEFINE_MUTEX(bpf_percpu_ma_lock); 309 310 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 311 { 312 struct bpf_verifier_env *env = private_data; 313 va_list args; 314 315 if (!bpf_verifier_log_needed(&env->log)) 316 return; 317 318 va_start(args, fmt); 319 bpf_verifier_vlog(&env->log, fmt, args); 320 va_end(args); 321 } 322 323 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 324 struct bpf_reg_state *reg, 325 struct bpf_retval_range range, const char *ctx, 326 const char *reg_name) 327 { 328 bool unknown = true; 329 330 verbose(env, "%s the register %s has", ctx, reg_name); 331 if (reg_smin(reg) > S64_MIN) { 332 verbose(env, " smin=%lld", reg_smin(reg)); 333 unknown = false; 334 } 335 if (reg_smax(reg) < S64_MAX) { 336 verbose(env, " smax=%lld", reg_smax(reg)); 337 unknown = false; 338 } 339 if (unknown) 340 verbose(env, " unknown scalar value"); 341 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 342 } 343 344 static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 345 { 346 enum bpf_reg_type type; 347 348 type = reg->type; 349 if (type_may_be_null(type)) 350 return false; 351 352 type = base_type(type); 353 return type == PTR_TO_SOCKET || 354 type == PTR_TO_TCP_SOCK || 355 type == PTR_TO_MAP_VALUE || 356 type == PTR_TO_MAP_KEY || 357 type == PTR_TO_SOCK_COMMON || 358 (type == PTR_TO_BTF_ID && is_trusted_reg(env, reg)) || 359 (type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) || 360 type == CONST_PTR_TO_MAP; 361 } 362 363 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 364 { 365 struct btf_record *rec = NULL; 366 struct btf_struct_meta *meta; 367 368 if (reg->type == PTR_TO_MAP_VALUE) { 369 rec = reg->map_ptr->record; 370 } else if (type_is_ptr_alloc_obj(reg->type)) { 371 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 372 if (meta) 373 rec = meta->record; 374 } 375 return rec; 376 } 377 378 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog) 379 { 380 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 381 382 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 383 } 384 385 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog) 386 { 387 const struct btf_type *type, *func, *func_proto; 388 const struct btf *btf = env->prog->aux->btf; 389 u32 btf_id; 390 391 btf_id = env->prog->aux->func_info[subprog].type_id; 392 393 func = btf_type_by_id(btf, btf_id); 394 if (verifier_bug_if(!func, env, "btf_id %u not found", btf_id)) 395 return false; 396 397 func_proto = btf_type_by_id(btf, func->type); 398 if (!func_proto) 399 return false; 400 401 type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 402 if (!type) 403 return false; 404 405 return btf_type_is_void(type); 406 } 407 408 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 409 { 410 struct bpf_func_info *info; 411 412 if (!env->prog->aux->func_info) 413 return ""; 414 415 info = &env->prog->aux->func_info[subprog]; 416 return btf_type_name(env->prog->aux->btf, info->type_id); 417 } 418 419 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 420 { 421 struct bpf_subprog_info *info = subprog_info(env, subprog); 422 423 info->is_cb = true; 424 info->is_async_cb = true; 425 info->is_exception_cb = true; 426 } 427 428 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 429 { 430 return subprog_info(env, subprog)->is_exception_cb; 431 } 432 433 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 434 { 435 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK); 436 } 437 438 static bool type_is_rdonly_mem(u32 type) 439 { 440 return type & MEM_RDONLY; 441 } 442 443 static bool is_acquire_function(enum bpf_func_id func_id, 444 const struct bpf_map *map) 445 { 446 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 447 448 if (func_id == BPF_FUNC_sk_lookup_tcp || 449 func_id == BPF_FUNC_sk_lookup_udp || 450 func_id == BPF_FUNC_skc_lookup_tcp || 451 func_id == BPF_FUNC_ringbuf_reserve || 452 func_id == BPF_FUNC_kptr_xchg) 453 return true; 454 455 if (func_id == BPF_FUNC_map_lookup_elem && 456 (map_type == BPF_MAP_TYPE_SOCKMAP || 457 map_type == BPF_MAP_TYPE_SOCKHASH)) 458 return true; 459 460 return false; 461 } 462 463 static bool is_ptr_cast_function(enum bpf_func_id func_id) 464 { 465 return func_id == BPF_FUNC_tcp_sock || 466 func_id == BPF_FUNC_sk_fullsock || 467 func_id == BPF_FUNC_skc_to_tcp_sock || 468 func_id == BPF_FUNC_skc_to_tcp6_sock || 469 func_id == BPF_FUNC_skc_to_udp6_sock || 470 func_id == BPF_FUNC_skc_to_mptcp_sock || 471 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 472 func_id == BPF_FUNC_skc_to_tcp_request_sock; 473 } 474 475 static bool is_sync_callback_calling_kfunc(u32 btf_id); 476 static bool is_async_callback_calling_kfunc(u32 btf_id); 477 static bool is_callback_calling_kfunc(u32 btf_id); 478 479 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id); 480 static bool is_task_work_add_kfunc(u32 func_id); 481 482 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 483 { 484 return func_id == BPF_FUNC_for_each_map_elem || 485 func_id == BPF_FUNC_find_vma || 486 func_id == BPF_FUNC_loop || 487 func_id == BPF_FUNC_user_ringbuf_drain; 488 } 489 490 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 491 { 492 return func_id == BPF_FUNC_timer_set_callback; 493 } 494 495 static bool is_callback_calling_function(enum bpf_func_id func_id) 496 { 497 return is_sync_callback_calling_function(func_id) || 498 is_async_callback_calling_function(func_id); 499 } 500 501 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn) 502 { 503 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 504 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 505 } 506 507 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn) 508 { 509 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 510 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 511 } 512 513 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn) 514 { 515 /* bpf_timer callbacks are never sleepable. */ 516 if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback) 517 return false; 518 519 /* bpf_wq and bpf_task_work callbacks are always sleepable. */ 520 if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 521 (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm))) 522 return true; 523 524 verifier_bug(env, "unhandled async callback in is_async_cb_sleepable"); 525 return false; 526 } 527 528 bool bpf_is_may_goto_insn(struct bpf_insn *insn) 529 { 530 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 531 } 532 533 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 534 { 535 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 536 537 /* We need to check that slots between [spi - nr_slots + 1, spi] are 538 * within [0, allocated_stack). 539 * 540 * Please note that the spi grows downwards. For example, a dynptr 541 * takes the size of two stack slots; the first slot will be at 542 * spi and the second slot will be at spi - 1. 543 */ 544 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 545 } 546 547 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 548 const char *obj_kind, int nr_slots) 549 { 550 int off, spi; 551 552 if (!tnum_is_const(reg->var_off)) { 553 verbose(env, "%s has to be at a constant offset\n", obj_kind); 554 return -EINVAL; 555 } 556 557 off = reg->var_off.value; 558 if (off % BPF_REG_SIZE) { 559 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 560 return -EINVAL; 561 } 562 563 spi = bpf_get_spi(off); 564 if (spi + 1 < nr_slots) { 565 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 566 return -EINVAL; 567 } 568 569 if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots)) 570 return -ERANGE; 571 return spi; 572 } 573 574 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 575 { 576 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 577 } 578 579 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 580 { 581 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 582 } 583 584 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 585 { 586 return stack_slot_obj_get_spi(env, reg, "irq_flag", 1); 587 } 588 589 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 590 { 591 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 592 case DYNPTR_TYPE_LOCAL: 593 return BPF_DYNPTR_TYPE_LOCAL; 594 case DYNPTR_TYPE_RINGBUF: 595 return BPF_DYNPTR_TYPE_RINGBUF; 596 case DYNPTR_TYPE_SKB: 597 return BPF_DYNPTR_TYPE_SKB; 598 case DYNPTR_TYPE_XDP: 599 return BPF_DYNPTR_TYPE_XDP; 600 case DYNPTR_TYPE_SKB_META: 601 return BPF_DYNPTR_TYPE_SKB_META; 602 case DYNPTR_TYPE_FILE: 603 return BPF_DYNPTR_TYPE_FILE; 604 default: 605 return BPF_DYNPTR_TYPE_INVALID; 606 } 607 } 608 609 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 610 { 611 switch (type) { 612 case BPF_DYNPTR_TYPE_LOCAL: 613 return DYNPTR_TYPE_LOCAL; 614 case BPF_DYNPTR_TYPE_RINGBUF: 615 return DYNPTR_TYPE_RINGBUF; 616 case BPF_DYNPTR_TYPE_SKB: 617 return DYNPTR_TYPE_SKB; 618 case BPF_DYNPTR_TYPE_XDP: 619 return DYNPTR_TYPE_XDP; 620 case BPF_DYNPTR_TYPE_SKB_META: 621 return DYNPTR_TYPE_SKB_META; 622 case BPF_DYNPTR_TYPE_FILE: 623 return DYNPTR_TYPE_FILE; 624 default: 625 return 0; 626 } 627 } 628 629 static bool dynptr_type_referenced(enum bpf_dynptr_type type) 630 { 631 return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE; 632 } 633 634 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 635 enum bpf_dynptr_type type, 636 bool first_slot, int id, int parent_id); 637 638 639 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 640 struct bpf_reg_state *sreg1, 641 struct bpf_reg_state *sreg2, 642 enum bpf_dynptr_type type, int parent_id) 643 { 644 int id = ++env->id_gen; 645 646 __mark_dynptr_reg(sreg1, type, true, id, parent_id); 647 __mark_dynptr_reg(sreg2, type, false, id, parent_id); 648 } 649 650 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 651 struct bpf_reg_state *reg, 652 enum bpf_dynptr_type type) 653 { 654 __mark_dynptr_reg(reg, type, true, ++env->id_gen, 0); 655 } 656 657 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 658 struct bpf_func_state *state, int spi); 659 660 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 661 enum bpf_arg_type arg_type, int insn_idx, 662 struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr) 663 { 664 struct bpf_func_state *state = bpf_func(env, reg); 665 int spi, i, err, parent_id = 0; 666 enum bpf_dynptr_type type; 667 668 spi = dynptr_get_spi(env, reg); 669 if (spi < 0) 670 return spi; 671 672 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 673 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 674 * to ensure that for the following example: 675 * [d1][d1][d2][d2] 676 * spi 3 2 1 0 677 * So marking spi = 2 should lead to destruction of both d1 and d2. In 678 * case they do belong to same dynptr, second call won't see slot_type 679 * as STACK_DYNPTR and will simply skip destruction. 680 */ 681 err = destroy_if_dynptr_stack_slot(env, state, spi); 682 if (err) 683 return err; 684 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 685 if (err) 686 return err; 687 688 for (i = 0; i < BPF_REG_SIZE; i++) { 689 state->stack[spi].slot_type[i] = STACK_DYNPTR; 690 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 691 } 692 693 type = arg_to_dynptr_type(arg_type); 694 if (type == BPF_DYNPTR_TYPE_INVALID) 695 return -EINVAL; 696 697 if (dynptr->type == BPF_DYNPTR_TYPE_INVALID) { /* dynptr constructors */ 698 err = validate_ref_obj(env, ref_obj); 699 if (err) 700 return err; 701 702 /* Track parent's id if the parent is a referenced object */ 703 parent_id = ref_obj->id; 704 705 if (dynptr_type_referenced(type)) { 706 int id; 707 708 /* 709 * Create an intermediate reference that tracks the referenced 710 * object for the referenced dynptr. Freeing a referenced dynptr 711 * through helpers/kfuncs will invalidate all clones. 712 */ 713 id = acquire_reference(env, insn_idx, parent_id); 714 if (id < 0) 715 return id; 716 717 parent_id = id; 718 } 719 } else { /* bpf_dynptr_clone() */ 720 parent_id = dynptr->parent_id; 721 } 722 723 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 724 &state->stack[spi - 1].spilled_ptr, type, parent_id); 725 726 return 0; 727 } 728 729 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_stack_state *stack) 730 { 731 int i; 732 733 for (i = 0; i < BPF_REG_SIZE; i++) { 734 stack[0].slot_type[i] = STACK_INVALID; 735 stack[1].slot_type[i] = STACK_INVALID; 736 } 737 738 bpf_mark_reg_not_init(env, &stack[0].spilled_ptr); 739 bpf_mark_reg_not_init(env, &stack[1].spilled_ptr); 740 } 741 742 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 743 { 744 struct bpf_func_state *state = bpf_func(env, reg); 745 int spi; 746 747 spi = dynptr_get_spi(env, reg); 748 if (spi < 0) 749 return spi; 750 751 /* 752 * For referenced dynptr, release the parent ref which cascades to 753 * all clones and derived slices. For non-referenced dynptr, only 754 * the dynptr and slices derived from it will be invalidated. 755 */ 756 reg = &state->stack[spi].spilled_ptr; 757 return release_reference(env, dynptr_type_referenced(reg->dynptr.type) 758 ? reg->parent_id 759 : reg->id); 760 } 761 762 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 763 struct bpf_reg_state *reg); 764 765 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 766 { 767 if (!env->allow_ptr_leaks) 768 bpf_mark_reg_not_init(env, reg); 769 else 770 __mark_reg_unknown(env, reg); 771 } 772 773 static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id) 774 { 775 struct bpf_stack_state *stack; 776 struct bpf_func_state *state; 777 struct bpf_reg_state *reg; 778 int ref_cnt = 0; 779 780 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({ 781 if (!stack || stack->slot_type[0] != STACK_DYNPTR) 782 continue; 783 if (!stack->spilled_ptr.dynptr.first_slot) 784 continue; 785 if (stack->spilled_ptr.parent_id == v_parent_id) 786 ref_cnt++; 787 })); 788 789 return ref_cnt; 790 } 791 792 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 793 struct bpf_func_state *state, int spi) 794 { 795 int err = 0; 796 797 /* We always ensure that STACK_DYNPTR is never set partially, 798 * hence just checking for slot_type[0] is enough. This is 799 * different for STACK_SPILL, where it may be only set for 800 * 1 byte, so code has to use is_spilled_reg. 801 */ 802 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 803 return 0; 804 805 /* Reposition spi to first slot */ 806 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 807 spi = spi + 1; 808 809 /* 810 * A referenced dynptr can be overwritten only if there is at 811 * least one other dynptr sharing the same virtual ref parent, 812 * ensuring the reference can still be properly released. 813 */ 814 if (dynptr_type_referenced(state->stack[spi].spilled_ptr.dynptr.type) && 815 dynptr_ref_cnt(env, state->stack[spi].spilled_ptr.parent_id) <= 1) { 816 verbose(env, "cannot overwrite referenced dynptr\n"); 817 return -EINVAL; 818 } 819 820 /* Invalidate the dynptr and any derived slices */ 821 err = release_reference(env, state->stack[spi].spilled_ptr.id); 822 if (!err) { 823 mark_stack_slot_scratched(env, spi); 824 mark_stack_slot_scratched(env, spi - 1); 825 } 826 827 return err; 828 } 829 830 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 831 { 832 int spi; 833 834 if (reg->type == CONST_PTR_TO_DYNPTR) 835 return false; 836 837 spi = dynptr_get_spi(env, reg); 838 839 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 840 * error because this just means the stack state hasn't been updated yet. 841 * We will do check_mem_access to check and update stack bounds later. 842 */ 843 if (spi < 0 && spi != -ERANGE) 844 return false; 845 846 /* We don't need to check if the stack slots are marked by previous 847 * dynptr initializations because we allow overwriting existing unreferenced 848 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 849 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 850 * touching are completely destructed before we reinitialize them for a new 851 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 852 * instead of delaying it until the end where the user will get "Unreleased 853 * reference" error. 854 */ 855 return true; 856 } 857 858 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 859 { 860 struct bpf_func_state *state = bpf_func(env, reg); 861 int i, spi; 862 863 /* This already represents first slot of initialized bpf_dynptr. 864 * 865 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 866 * check_func_arg_reg_off's logic, so we don't need to check its 867 * offset and alignment. 868 */ 869 if (reg->type == CONST_PTR_TO_DYNPTR) 870 return true; 871 872 spi = dynptr_get_spi(env, reg); 873 if (spi < 0) 874 return false; 875 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 876 return false; 877 878 for (i = 0; i < BPF_REG_SIZE; i++) { 879 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 880 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 881 return false; 882 } 883 884 return true; 885 } 886 887 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 888 enum bpf_arg_type arg_type) 889 { 890 struct bpf_func_state *state = bpf_func(env, reg); 891 enum bpf_dynptr_type dynptr_type; 892 int spi; 893 894 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 895 if (arg_type == ARG_PTR_TO_DYNPTR) 896 return true; 897 898 dynptr_type = arg_to_dynptr_type(arg_type); 899 if (reg->type == CONST_PTR_TO_DYNPTR) { 900 return reg->dynptr.type == dynptr_type; 901 } else { 902 spi = dynptr_get_spi(env, reg); 903 if (spi < 0) 904 return false; 905 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 906 } 907 } 908 909 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 910 911 static bool in_rcu_cs(struct bpf_verifier_env *env); 912 913 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta); 914 915 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 916 struct bpf_call_arg_meta *meta, 917 struct bpf_reg_state *reg, int insn_idx, 918 struct btf *btf, u32 btf_id, int nr_slots) 919 { 920 struct bpf_func_state *state = bpf_func(env, reg); 921 int spi, i, j, id; 922 923 spi = iter_get_spi(env, reg, nr_slots); 924 if (spi < 0) 925 return spi; 926 927 id = acquire_reference(env, insn_idx, 0); 928 if (id < 0) 929 return id; 930 931 for (i = 0; i < nr_slots; i++) { 932 struct bpf_stack_state *slot = &state->stack[spi - i]; 933 struct bpf_reg_state *st = &slot->spilled_ptr; 934 935 __mark_reg_known_zero(st); 936 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 937 if (is_kfunc_rcu_protected(meta)) { 938 if (in_rcu_cs(env)) 939 st->type |= MEM_RCU; 940 else 941 st->type |= PTR_UNTRUSTED; 942 } 943 st->id = i == 0 ? id : 0; 944 st->iter.btf = btf; 945 st->iter.btf_id = btf_id; 946 st->iter.state = BPF_ITER_STATE_ACTIVE; 947 st->iter.depth = 0; 948 949 for (j = 0; j < BPF_REG_SIZE; j++) 950 slot->slot_type[j] = STACK_ITER; 951 952 mark_stack_slot_scratched(env, spi - i); 953 } 954 955 return 0; 956 } 957 958 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 959 struct bpf_reg_state *reg, int nr_slots) 960 { 961 struct bpf_func_state *state = bpf_func(env, reg); 962 int spi, i, j; 963 964 spi = iter_get_spi(env, reg, nr_slots); 965 if (spi < 0) 966 return spi; 967 968 for (i = 0; i < nr_slots; i++) { 969 struct bpf_stack_state *slot = &state->stack[spi - i]; 970 struct bpf_reg_state *st = &slot->spilled_ptr; 971 972 if (i == 0) 973 WARN_ON_ONCE(release_reference(env, st->id)); 974 975 bpf_mark_reg_not_init(env, st); 976 977 for (j = 0; j < BPF_REG_SIZE; j++) 978 slot->slot_type[j] = STACK_INVALID; 979 980 mark_stack_slot_scratched(env, spi - i); 981 } 982 983 return 0; 984 } 985 986 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 987 struct bpf_reg_state *reg, int nr_slots) 988 { 989 struct bpf_func_state *state = bpf_func(env, reg); 990 int spi, i, j; 991 992 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 993 * will do check_mem_access to check and update stack bounds later, so 994 * return true for that case. 995 */ 996 spi = iter_get_spi(env, reg, nr_slots); 997 if (spi == -ERANGE) 998 return true; 999 if (spi < 0) 1000 return false; 1001 1002 for (i = 0; i < nr_slots; i++) { 1003 struct bpf_stack_state *slot = &state->stack[spi - i]; 1004 1005 for (j = 0; j < BPF_REG_SIZE; j++) 1006 if (slot->slot_type[j] == STACK_ITER) 1007 return false; 1008 } 1009 1010 return true; 1011 } 1012 1013 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1014 struct btf *btf, u32 btf_id, int nr_slots) 1015 { 1016 struct bpf_func_state *state = bpf_func(env, reg); 1017 int spi, i, j; 1018 1019 spi = iter_get_spi(env, reg, nr_slots); 1020 if (spi < 0) 1021 return -EINVAL; 1022 1023 for (i = 0; i < nr_slots; i++) { 1024 struct bpf_stack_state *slot = &state->stack[spi - i]; 1025 struct bpf_reg_state *st = &slot->spilled_ptr; 1026 1027 if (st->type & PTR_UNTRUSTED) 1028 return -EPROTO; 1029 /* only main (first) slot has id set */ 1030 if (i == 0 && !st->id) 1031 return -EINVAL; 1032 if (i != 0 && st->id) 1033 return -EINVAL; 1034 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1035 return -EINVAL; 1036 1037 for (j = 0; j < BPF_REG_SIZE; j++) 1038 if (slot->slot_type[j] != STACK_ITER) 1039 return -EINVAL; 1040 } 1041 1042 return 0; 1043 } 1044 1045 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx); 1046 static int release_irq_state(struct bpf_verifier_state *state, int id); 1047 1048 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env, 1049 struct bpf_call_arg_meta *meta, 1050 struct bpf_reg_state *reg, int insn_idx, 1051 int kfunc_class) 1052 { 1053 struct bpf_func_state *state = bpf_func(env, reg); 1054 struct bpf_stack_state *slot; 1055 struct bpf_reg_state *st; 1056 int spi, i, id; 1057 1058 spi = irq_flag_get_spi(env, reg); 1059 if (spi < 0) 1060 return spi; 1061 1062 id = acquire_irq_state(env, insn_idx); 1063 if (id < 0) 1064 return id; 1065 1066 slot = &state->stack[spi]; 1067 st = &slot->spilled_ptr; 1068 1069 __mark_reg_known_zero(st); 1070 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1071 st->id = id; 1072 st->irq.kfunc_class = kfunc_class; 1073 1074 for (i = 0; i < BPF_REG_SIZE; i++) 1075 slot->slot_type[i] = STACK_IRQ_FLAG; 1076 1077 mark_stack_slot_scratched(env, spi); 1078 return 0; 1079 } 1080 1081 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1082 int kfunc_class) 1083 { 1084 struct bpf_func_state *state = bpf_func(env, reg); 1085 struct bpf_stack_state *slot; 1086 struct bpf_reg_state *st; 1087 int spi, i, err; 1088 1089 spi = irq_flag_get_spi(env, reg); 1090 if (spi < 0) 1091 return spi; 1092 1093 slot = &state->stack[spi]; 1094 st = &slot->spilled_ptr; 1095 1096 if (st->irq.kfunc_class != kfunc_class) { 1097 const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1098 const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1099 1100 verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n", 1101 flag_kfunc, used_kfunc); 1102 return -EINVAL; 1103 } 1104 1105 err = release_irq_state(env->cur_state, st->id); 1106 WARN_ON_ONCE(err && err != -EACCES); 1107 if (err) { 1108 int insn_idx = 0; 1109 1110 for (int i = 0; i < env->cur_state->acquired_refs; i++) { 1111 if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) { 1112 insn_idx = env->cur_state->refs[i].insn_idx; 1113 break; 1114 } 1115 } 1116 1117 verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n", 1118 env->cur_state->active_irq_id, insn_idx); 1119 return err; 1120 } 1121 1122 bpf_mark_reg_not_init(env, st); 1123 1124 for (i = 0; i < BPF_REG_SIZE; i++) 1125 slot->slot_type[i] = STACK_INVALID; 1126 1127 mark_stack_slot_scratched(env, spi); 1128 return 0; 1129 } 1130 1131 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1132 { 1133 struct bpf_func_state *state = bpf_func(env, reg); 1134 struct bpf_stack_state *slot; 1135 int spi, i; 1136 1137 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1138 * will do check_mem_access to check and update stack bounds later, so 1139 * return true for that case. 1140 */ 1141 spi = irq_flag_get_spi(env, reg); 1142 if (spi == -ERANGE) 1143 return true; 1144 if (spi < 0) 1145 return false; 1146 1147 slot = &state->stack[spi]; 1148 1149 for (i = 0; i < BPF_REG_SIZE; i++) 1150 if (slot->slot_type[i] == STACK_IRQ_FLAG) 1151 return false; 1152 return true; 1153 } 1154 1155 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1156 { 1157 struct bpf_func_state *state = bpf_func(env, reg); 1158 struct bpf_stack_state *slot; 1159 struct bpf_reg_state *st; 1160 int spi, i; 1161 1162 spi = irq_flag_get_spi(env, reg); 1163 if (spi < 0) 1164 return -EINVAL; 1165 1166 slot = &state->stack[spi]; 1167 st = &slot->spilled_ptr; 1168 1169 if (!st->id) 1170 return -EINVAL; 1171 1172 for (i = 0; i < BPF_REG_SIZE; i++) 1173 if (slot->slot_type[i] != STACK_IRQ_FLAG) 1174 return -EINVAL; 1175 return 0; 1176 } 1177 1178 /* Check if given stack slot is "special": 1179 * - spilled register state (STACK_SPILL); 1180 * - dynptr state (STACK_DYNPTR); 1181 * - iter state (STACK_ITER). 1182 * - irq flag state (STACK_IRQ_FLAG) 1183 */ 1184 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1185 { 1186 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1187 1188 switch (type) { 1189 case STACK_SPILL: 1190 case STACK_DYNPTR: 1191 case STACK_ITER: 1192 case STACK_IRQ_FLAG: 1193 return true; 1194 case STACK_INVALID: 1195 case STACK_POISON: 1196 case STACK_MISC: 1197 case STACK_ZERO: 1198 return false; 1199 default: 1200 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1201 return true; 1202 } 1203 } 1204 1205 /* The reg state of a pointer or a bounded scalar was saved when 1206 * it was spilled to the stack. 1207 */ 1208 1209 /* 1210 * Mark stack slot as STACK_MISC, unless it is already: 1211 * - STACK_INVALID, in which case they are equivalent. 1212 * - STACK_ZERO, in which case we preserve more precise STACK_ZERO. 1213 * - STACK_POISON, which truly forbids access to the slot. 1214 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged 1215 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is 1216 * unnecessary as both are considered equivalent when loading data and pruning, 1217 * in case of unprivileged mode it will be incorrect to allow reads of invalid 1218 * slots. 1219 */ 1220 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1221 { 1222 if (*stype == STACK_ZERO) 1223 return; 1224 if (*stype == STACK_INVALID || *stype == STACK_POISON) 1225 return; 1226 *stype = STACK_MISC; 1227 } 1228 1229 static void scrub_spilled_slot(u8 *stype) 1230 { 1231 if (*stype != STACK_INVALID && *stype != STACK_POISON) 1232 *stype = STACK_MISC; 1233 } 1234 1235 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1236 * small to hold src. This is different from krealloc since we don't want to preserve 1237 * the contents of dst. 1238 * 1239 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1240 * not be allocated. 1241 */ 1242 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1243 { 1244 size_t alloc_bytes; 1245 void *orig = dst; 1246 size_t bytes; 1247 1248 if (ZERO_OR_NULL_PTR(src)) 1249 goto out; 1250 1251 if (unlikely(check_mul_overflow(n, size, &bytes))) 1252 return NULL; 1253 1254 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1255 dst = krealloc(orig, alloc_bytes, flags); 1256 if (!dst) { 1257 kfree(orig); 1258 return NULL; 1259 } 1260 1261 memcpy(dst, src, bytes); 1262 out: 1263 return dst ? dst : ZERO_SIZE_PTR; 1264 } 1265 1266 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1267 * small to hold new_n items. new items are zeroed out if the array grows. 1268 * 1269 * Contrary to krealloc_array, does not free arr if new_n is zero. 1270 */ 1271 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1272 { 1273 size_t alloc_size; 1274 void *new_arr; 1275 1276 if (!new_n || old_n == new_n) 1277 goto out; 1278 1279 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1280 new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT); 1281 if (!new_arr) { 1282 kfree(arr); 1283 return NULL; 1284 } 1285 arr = new_arr; 1286 1287 if (new_n > old_n) 1288 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1289 1290 out: 1291 return arr ? arr : ZERO_SIZE_PTR; 1292 } 1293 1294 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) 1295 { 1296 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1297 sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT); 1298 if (!dst->refs) 1299 return -ENOMEM; 1300 1301 dst->acquired_refs = src->acquired_refs; 1302 dst->active_locks = src->active_locks; 1303 dst->active_preempt_locks = src->active_preempt_locks; 1304 dst->active_rcu_locks = src->active_rcu_locks; 1305 dst->active_irq_id = src->active_irq_id; 1306 dst->active_lock_id = src->active_lock_id; 1307 dst->active_lock_ptr = src->active_lock_ptr; 1308 return 0; 1309 } 1310 1311 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1312 { 1313 size_t n = src->allocated_stack / BPF_REG_SIZE; 1314 1315 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1316 GFP_KERNEL_ACCOUNT); 1317 if (!dst->stack) 1318 return -ENOMEM; 1319 1320 dst->allocated_stack = src->allocated_stack; 1321 1322 /* copy stack args state */ 1323 n = src->out_stack_arg_cnt; 1324 if (n) { 1325 dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n, 1326 sizeof(struct bpf_reg_state), 1327 GFP_KERNEL_ACCOUNT); 1328 if (!dst->stack_arg_regs) 1329 return -ENOMEM; 1330 } 1331 1332 dst->out_stack_arg_cnt = src->out_stack_arg_cnt; 1333 return 0; 1334 } 1335 1336 static int resize_reference_state(struct bpf_verifier_state *state, size_t n) 1337 { 1338 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1339 sizeof(struct bpf_reference_state)); 1340 if (!state->refs) 1341 return -ENOMEM; 1342 1343 state->acquired_refs = n; 1344 return 0; 1345 } 1346 1347 /* Possibly update state->allocated_stack to be at least size bytes. Also 1348 * possibly update the function's high-water mark in its bpf_subprog_info. 1349 */ 1350 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1351 { 1352 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1353 1354 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1355 size = round_up(size, BPF_REG_SIZE); 1356 n = size / BPF_REG_SIZE; 1357 1358 if (old_n >= n) 1359 return 0; 1360 1361 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1362 if (!state->stack) 1363 return -ENOMEM; 1364 1365 state->allocated_stack = size; 1366 1367 /* update known max for given subprogram */ 1368 if (env->subprog_info[state->subprogno].stack_depth < size) 1369 env->subprog_info[state->subprogno].stack_depth = size; 1370 1371 return 0; 1372 } 1373 1374 static int grow_stack_arg_slots(struct bpf_verifier_env *env, 1375 struct bpf_func_state *state, int cnt) 1376 { 1377 size_t old_n = state->out_stack_arg_cnt; 1378 1379 if (old_n >= cnt) 1380 return 0; 1381 1382 state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt, 1383 sizeof(struct bpf_reg_state)); 1384 if (!state->stack_arg_regs) 1385 return -ENOMEM; 1386 1387 state->out_stack_arg_cnt = cnt; 1388 return 0; 1389 } 1390 1391 /* Acquire a pointer id from the env and update the state->refs to include 1392 * this new pointer reference. 1393 * On success, returns a valid pointer id to associate with the register 1394 * On failure, returns a negative errno. 1395 */ 1396 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1397 { 1398 struct bpf_verifier_state *state = env->cur_state; 1399 int new_ofs = state->acquired_refs; 1400 int err; 1401 1402 err = resize_reference_state(state, state->acquired_refs + 1); 1403 if (err) 1404 return NULL; 1405 state->refs[new_ofs].insn_idx = insn_idx; 1406 1407 return &state->refs[new_ofs]; 1408 } 1409 1410 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id) 1411 { 1412 struct bpf_reference_state *s; 1413 1414 s = acquire_reference_state(env, insn_idx); 1415 if (!s) 1416 return -ENOMEM; 1417 s->type = REF_TYPE_PTR; 1418 s->id = ++env->id_gen; 1419 s->parent_id = parent_id; 1420 return s->id; 1421 } 1422 1423 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type, 1424 int id, void *ptr) 1425 { 1426 struct bpf_verifier_state *state = env->cur_state; 1427 struct bpf_reference_state *s; 1428 1429 s = acquire_reference_state(env, insn_idx); 1430 if (!s) 1431 return -ENOMEM; 1432 s->type = type; 1433 s->id = id; 1434 s->ptr = ptr; 1435 1436 state->active_locks++; 1437 state->active_lock_id = id; 1438 state->active_lock_ptr = ptr; 1439 return 0; 1440 } 1441 1442 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx) 1443 { 1444 struct bpf_verifier_state *state = env->cur_state; 1445 struct bpf_reference_state *s; 1446 1447 s = acquire_reference_state(env, insn_idx); 1448 if (!s) 1449 return -ENOMEM; 1450 s->type = REF_TYPE_IRQ; 1451 s->id = ++env->id_gen; 1452 1453 state->active_irq_id = s->id; 1454 return s->id; 1455 } 1456 1457 static void release_reference_state(struct bpf_verifier_state *state, int idx) 1458 { 1459 int last_idx; 1460 size_t rem; 1461 1462 /* IRQ state requires the relative ordering of elements remaining the 1463 * same, since it relies on the refs array to behave as a stack, so that 1464 * it can detect out-of-order IRQ restore. Hence use memmove to shift 1465 * the array instead of swapping the final element into the deleted idx. 1466 */ 1467 last_idx = state->acquired_refs - 1; 1468 rem = state->acquired_refs - idx - 1; 1469 if (last_idx && idx != last_idx) 1470 memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem); 1471 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1472 state->acquired_refs--; 1473 return; 1474 } 1475 1476 static bool find_reference_state(struct bpf_verifier_state *state, int id) 1477 { 1478 int i; 1479 1480 for (i = 0; i < state->acquired_refs; i++) { 1481 if (state->refs[i].type != REF_TYPE_PTR) 1482 continue; 1483 if (state->refs[i].id == id) 1484 return true; 1485 } 1486 1487 return false; 1488 } 1489 1490 static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 1491 { 1492 return find_reference_state(env->cur_state, reg->id); 1493 } 1494 1495 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr) 1496 { 1497 void *prev_ptr = NULL; 1498 u32 prev_id = 0; 1499 int i; 1500 1501 for (i = 0; i < state->acquired_refs; i++) { 1502 if (state->refs[i].type == type && state->refs[i].id == id && 1503 state->refs[i].ptr == ptr) { 1504 release_reference_state(state, i); 1505 state->active_locks--; 1506 /* Reassign active lock (id, ptr). */ 1507 state->active_lock_id = prev_id; 1508 state->active_lock_ptr = prev_ptr; 1509 return 0; 1510 } 1511 if (state->refs[i].type & REF_TYPE_LOCK_MASK) { 1512 prev_id = state->refs[i].id; 1513 prev_ptr = state->refs[i].ptr; 1514 } 1515 } 1516 return -EINVAL; 1517 } 1518 1519 static int release_irq_state(struct bpf_verifier_state *state, int id) 1520 { 1521 u32 prev_id = 0; 1522 int i; 1523 1524 if (id != state->active_irq_id) 1525 return -EACCES; 1526 1527 for (i = 0; i < state->acquired_refs; i++) { 1528 if (state->refs[i].type != REF_TYPE_IRQ) 1529 continue; 1530 if (state->refs[i].id == id) { 1531 release_reference_state(state, i); 1532 state->active_irq_id = prev_id; 1533 return 0; 1534 } else { 1535 prev_id = state->refs[i].id; 1536 } 1537 } 1538 return -EINVAL; 1539 } 1540 1541 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type, 1542 int id, void *ptr) 1543 { 1544 int i; 1545 1546 for (i = 0; i < state->acquired_refs; i++) { 1547 struct bpf_reference_state *s = &state->refs[i]; 1548 1549 if (!(s->type & type)) 1550 continue; 1551 1552 if (s->id == id && s->ptr == ptr) 1553 return s; 1554 } 1555 return NULL; 1556 } 1557 1558 static void free_func_state(struct bpf_func_state *state) 1559 { 1560 if (!state) 1561 return; 1562 kfree(state->stack_arg_regs); 1563 kfree(state->stack); 1564 kfree(state); 1565 } 1566 1567 void bpf_clear_jmp_history(struct bpf_verifier_state *state) 1568 { 1569 kfree(state->jmp_history); 1570 state->jmp_history = NULL; 1571 state->jmp_history_cnt = 0; 1572 } 1573 1574 void bpf_free_verifier_state(struct bpf_verifier_state *state, 1575 bool free_self) 1576 { 1577 int i; 1578 1579 for (i = 0; i <= state->curframe; i++) { 1580 free_func_state(state->frame[i]); 1581 state->frame[i] = NULL; 1582 } 1583 kfree(state->refs); 1584 bpf_clear_jmp_history(state); 1585 if (free_self) 1586 kfree(state); 1587 } 1588 1589 /* copy verifier state from src to dst growing dst stack space 1590 * when necessary to accommodate larger src stack 1591 */ 1592 static int copy_func_state(struct bpf_func_state *dst, 1593 const struct bpf_func_state *src) 1594 { 1595 memcpy(dst, src, offsetof(struct bpf_func_state, stack)); 1596 return copy_stack_state(dst, src); 1597 } 1598 1599 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state, 1600 const struct bpf_verifier_state *src) 1601 { 1602 struct bpf_func_state *dst; 1603 int i, err; 1604 1605 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1606 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1607 GFP_KERNEL_ACCOUNT); 1608 if (!dst_state->jmp_history) 1609 return -ENOMEM; 1610 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1611 1612 /* if dst has more stack frames then src frame, free them, this is also 1613 * necessary in case of exceptional exits using bpf_throw. 1614 */ 1615 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1616 free_func_state(dst_state->frame[i]); 1617 dst_state->frame[i] = NULL; 1618 } 1619 err = copy_reference_state(dst_state, src); 1620 if (err) 1621 return err; 1622 dst_state->speculative = src->speculative; 1623 dst_state->in_sleepable = src->in_sleepable; 1624 dst_state->curframe = src->curframe; 1625 dst_state->branches = src->branches; 1626 dst_state->parent = src->parent; 1627 dst_state->first_insn_idx = src->first_insn_idx; 1628 dst_state->last_insn_idx = src->last_insn_idx; 1629 dst_state->dfs_depth = src->dfs_depth; 1630 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1631 dst_state->may_goto_depth = src->may_goto_depth; 1632 dst_state->equal_state = src->equal_state; 1633 for (i = 0; i <= src->curframe; i++) { 1634 dst = dst_state->frame[i]; 1635 if (!dst) { 1636 dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT); 1637 if (!dst) 1638 return -ENOMEM; 1639 dst_state->frame[i] = dst; 1640 } 1641 err = copy_func_state(dst, src->frame[i]); 1642 if (err) 1643 return err; 1644 } 1645 return 0; 1646 } 1647 1648 static u32 state_htab_size(struct bpf_verifier_env *env) 1649 { 1650 return env->prog->len; 1651 } 1652 1653 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx) 1654 { 1655 struct bpf_verifier_state *cur = env->cur_state; 1656 struct bpf_func_state *state = cur->frame[cur->curframe]; 1657 1658 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1659 } 1660 1661 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1662 { 1663 int fr; 1664 1665 if (a->curframe != b->curframe) 1666 return false; 1667 1668 for (fr = a->curframe; fr >= 0; fr--) 1669 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1670 return false; 1671 1672 return true; 1673 } 1674 1675 1676 void bpf_free_backedges(struct bpf_scc_visit *visit) 1677 { 1678 struct bpf_scc_backedge *backedge, *next; 1679 1680 for (backedge = visit->backedges; backedge; backedge = next) { 1681 bpf_free_verifier_state(&backedge->state, false); 1682 next = backedge->next; 1683 kfree(backedge); 1684 } 1685 visit->backedges = NULL; 1686 } 1687 1688 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1689 int *insn_idx, bool pop_log) 1690 { 1691 struct bpf_verifier_state *cur = env->cur_state; 1692 struct bpf_verifier_stack_elem *elem, *head = env->head; 1693 int err; 1694 1695 if (env->head == NULL) 1696 return -ENOENT; 1697 1698 if (cur) { 1699 err = bpf_copy_verifier_state(cur, &head->st); 1700 if (err) 1701 return err; 1702 } 1703 if (pop_log) 1704 bpf_vlog_reset(&env->log, head->log_pos); 1705 if (insn_idx) 1706 *insn_idx = head->insn_idx; 1707 if (prev_insn_idx) 1708 *prev_insn_idx = head->prev_insn_idx; 1709 elem = head->next; 1710 bpf_free_verifier_state(&head->st, false); 1711 kfree(head); 1712 env->head = elem; 1713 env->stack_size--; 1714 return 0; 1715 } 1716 1717 static bool error_recoverable_with_nospec(int err) 1718 { 1719 /* Should only return true for non-fatal errors that are allowed to 1720 * occur during speculative verification. For these we can insert a 1721 * nospec and the program might still be accepted. Do not include 1722 * something like ENOMEM because it is likely to re-occur for the next 1723 * architectural path once it has been recovered-from in all speculative 1724 * paths. 1725 */ 1726 return err == -EPERM || err == -EACCES || err == -EINVAL; 1727 } 1728 1729 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1730 int insn_idx, int prev_insn_idx, 1731 bool speculative) 1732 { 1733 struct bpf_verifier_state *cur = env->cur_state; 1734 struct bpf_verifier_stack_elem *elem; 1735 int err; 1736 1737 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 1738 if (!elem) 1739 return ERR_PTR(-ENOMEM); 1740 1741 elem->insn_idx = insn_idx; 1742 elem->prev_insn_idx = prev_insn_idx; 1743 elem->next = env->head; 1744 elem->log_pos = env->log.end_pos; 1745 env->head = elem; 1746 env->stack_size++; 1747 err = bpf_copy_verifier_state(&elem->st, cur); 1748 if (err) 1749 return ERR_PTR(-ENOMEM); 1750 elem->st.speculative |= speculative; 1751 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1752 verbose(env, "The sequence of %d jumps is too complex.\n", 1753 env->stack_size); 1754 return ERR_PTR(-E2BIG); 1755 } 1756 if (elem->st.parent) { 1757 ++elem->st.parent->branches; 1758 /* WARN_ON(branches > 2) technically makes sense here, 1759 * but 1760 * 1. speculative states will bump 'branches' for non-branch 1761 * instructions 1762 * 2. is_state_visited() heuristics may decide not to create 1763 * a new state for a sequence of branches and all such current 1764 * and cloned states will be pointing to a single parent state 1765 * which might have large 'branches' count. 1766 */ 1767 } 1768 return &elem->st; 1769 } 1770 1771 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno) 1772 { 1773 char *buf = env->tmp_arg_name; 1774 int len = sizeof(env->tmp_arg_name); 1775 int arg, regno = reg_from_argno(argno); 1776 1777 if (regno >= 0) { 1778 snprintf(buf, len, "R%d", regno); 1779 } else { 1780 arg = arg_from_argno(argno); 1781 snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE); 1782 } 1783 1784 return buf; 1785 } 1786 1787 static const int caller_saved[CALLER_SAVED_REGS] = { 1788 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1789 }; 1790 1791 /* This helper doesn't clear reg->id */ 1792 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1793 { 1794 reg->var_off = tnum_const(imm); 1795 reg->r64 = cnum64_from_urange(imm, imm); 1796 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 1797 } 1798 1799 /* Mark the unknown part of a register (variable offset or scalar value) as 1800 * known to have the value @imm. 1801 */ 1802 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1803 { 1804 /* Clear off and union(map_ptr, range) */ 1805 memset(((u8 *)reg) + sizeof(reg->type), 0, 1806 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1807 reg->id = 0; 1808 reg->parent_id = 0; 1809 ___mark_reg_known(reg, imm); 1810 } 1811 1812 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1813 { 1814 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1815 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 1816 } 1817 1818 /* Mark the 'variable offset' part of a register as zero. This should be 1819 * used only on registers holding a pointer type. 1820 */ 1821 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1822 { 1823 __mark_reg_known(reg, 0); 1824 } 1825 1826 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1827 { 1828 __mark_reg_known(reg, 0); 1829 reg->type = SCALAR_VALUE; 1830 /* all scalars are assumed imprecise initially (unless unprivileged, 1831 * in which case everything is forced to be precise) 1832 */ 1833 reg->precise = !env->bpf_capable; 1834 } 1835 1836 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1837 struct bpf_reg_state *regs, u32 regno) 1838 { 1839 __mark_reg_known_zero(regs + regno); 1840 } 1841 1842 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1843 bool first_slot, int id, int parent_id) 1844 { 1845 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1846 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1847 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1848 */ 1849 __mark_reg_known_zero(reg); 1850 reg->type = CONST_PTR_TO_DYNPTR; 1851 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1852 reg->id = id; 1853 reg->parent_id = parent_id; 1854 reg->dynptr.type = type; 1855 reg->dynptr.first_slot = first_slot; 1856 } 1857 1858 /* 1859 * Refine the return type of the bpf_map_lookup_elem() for special map types: 1860 * map-in-map, xskmap, sockmap and sockhash. 1861 */ 1862 static void refine_map_lookup_value(struct bpf_reg_state *reg) 1863 { 1864 enum bpf_type_flag maybe_null = reg->type & PTR_MAYBE_NULL; 1865 const struct bpf_map *map = reg->map_ptr; 1866 1867 if (map->inner_map_meta) { 1868 reg->type = CONST_PTR_TO_MAP | maybe_null; 1869 reg->map_ptr = map->inner_map_meta; 1870 /* transfer reg's id which is unique for every map_lookup_elem 1871 * as UID of the inner map. 1872 */ 1873 if (btf_record_has_field(map->inner_map_meta->record, 1874 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) 1875 reg->map_uid = reg->id; 1876 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1877 reg->type = PTR_TO_XDP_SOCK | maybe_null; 1878 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1879 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1880 reg->type = PTR_TO_SOCKET | maybe_null; 1881 } 1882 } 1883 1884 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1885 { 1886 reg->type &= ~PTR_MAYBE_NULL; 1887 } 1888 1889 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1890 struct btf_field_graph_root *ds_head) 1891 { 1892 __mark_reg_known(®s[regno], ds_head->node_offset); 1893 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1894 regs[regno].btf = ds_head->btf; 1895 regs[regno].btf_id = ds_head->value_btf_id; 1896 } 1897 1898 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1899 { 1900 return type_is_pkt_pointer(reg->type); 1901 } 1902 1903 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1904 { 1905 return reg_is_pkt_pointer(reg) || 1906 reg->type == PTR_TO_PACKET_END; 1907 } 1908 1909 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1910 { 1911 return base_type(reg->type) == PTR_TO_MEM && 1912 (reg->type & 1913 (DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META)); 1914 } 1915 1916 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1917 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1918 enum bpf_reg_type which) 1919 { 1920 /* The register can already have a range from prior markings. 1921 * This is fine as long as it hasn't been advanced from its 1922 * origin. 1923 */ 1924 return reg->type == which && 1925 reg->id == 0 && 1926 tnum_equals_const(reg->var_off, 0); 1927 } 1928 1929 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1930 { 1931 reg->r32 = CNUM32_UNBOUNDED; 1932 } 1933 1934 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1935 { 1936 reg->r64 = CNUM64_UNBOUNDED; 1937 } 1938 1939 /* Reset the min/max bounds of a register */ 1940 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1941 { 1942 __mark_reg64_unbounded(reg); 1943 __mark_reg32_unbounded(reg); 1944 } 1945 1946 static void reset_reg64_and_tnum(struct bpf_reg_state *reg) 1947 { 1948 __mark_reg64_unbounded(reg); 1949 reg->var_off = tnum_unknown; 1950 } 1951 1952 static void reset_reg32_and_tnum(struct bpf_reg_state *reg) 1953 { 1954 __mark_reg32_unbounded(reg); 1955 reg->var_off = tnum_unknown; 1956 } 1957 1958 static struct cnum32 cnum32_from_tnum(struct tnum tnum) 1959 { 1960 tnum = tnum_subreg(tnum); 1961 if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN)) 1962 /* min signed is max(sign bit) | min(other bits) */ 1963 /* max signed is min(sign bit) | max(other bits) */ 1964 return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN), 1965 tnum.value | (tnum.mask & S32_MAX)); 1966 else 1967 return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask)); 1968 } 1969 1970 static struct cnum64 cnum64_from_tnum(struct tnum tnum) 1971 { 1972 if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN)) 1973 /* min signed is max(sign bit) | min(other bits) */ 1974 /* max signed is min(sign bit) | max(other bits) */ 1975 return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN), 1976 tnum.value | (tnum.mask & S64_MAX)); 1977 else 1978 return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask)); 1979 } 1980 1981 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1982 { 1983 cnum32_intersect_with(®->r32, cnum32_from_tnum(reg->var_off)); 1984 } 1985 1986 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1987 { 1988 u64 tnum_next, tmax; 1989 bool umin_in_tnum; 1990 1991 cnum64_intersect_with(®->r64, cnum64_from_tnum(reg->var_off)); 1992 1993 /* Check if u64 and tnum overlap in a single value */ 1994 tnum_next = tnum_step(reg->var_off, reg_umin(reg)); 1995 umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value; 1996 tmax = reg->var_off.value | reg->var_off.mask; 1997 if (umin_in_tnum && tnum_next > reg_umax(reg)) { 1998 /* The u64 range and the tnum only overlap in umin. 1999 * u64: ---[xxxxxx]----- 2000 * tnum: --xx----------x- 2001 */ 2002 ___mark_reg_known(reg, reg_umin(reg)); 2003 } else if (!umin_in_tnum && tnum_next == tmax) { 2004 /* The u64 range and the tnum only overlap in the maximum value 2005 * represented by the tnum, called tmax. 2006 * u64: ---[xxxxxx]----- 2007 * tnum: xx-----x-------- 2008 */ 2009 ___mark_reg_known(reg, tmax); 2010 } else if (!umin_in_tnum && tnum_next <= reg_umax(reg) && 2011 tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) { 2012 /* The u64 range and the tnum only overlap in between umin 2013 * (excluded) and umax. 2014 * u64: ---[xxxxxx]----- 2015 * tnum: xx----x-------x- 2016 */ 2017 ___mark_reg_known(reg, tnum_next); 2018 } 2019 } 2020 2021 static void __update_reg_bounds(struct bpf_reg_state *reg) 2022 { 2023 __update_reg32_bounds(reg); 2024 __update_reg64_bounds(reg); 2025 } 2026 2027 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg) 2028 { 2029 cnum32_intersect_with(®->r32, cnum32_from_cnum64(reg->r64)); 2030 } 2031 2032 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg) 2033 { 2034 reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32); 2035 } 2036 2037 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2038 { 2039 deduce_bounds_32_from_64(reg); 2040 deduce_bounds_64_from_32(reg); 2041 } 2042 2043 /* Attempts to improve var_off based on unsigned min/max information */ 2044 static void __reg_bound_offset(struct bpf_reg_state *reg) 2045 { 2046 struct tnum var64_off = tnum_intersect(reg->var_off, 2047 tnum_range(reg_umin(reg), 2048 reg_umax(reg))); 2049 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2050 tnum_range(reg_u32_min(reg), 2051 reg_u32_max(reg))); 2052 2053 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2054 } 2055 2056 static bool range_bounds_violation(struct bpf_reg_state *reg); 2057 2058 static void reg_bounds_sync(struct bpf_reg_state *reg) 2059 { 2060 /* If the input reg_state is invalid, we can exit early */ 2061 if (range_bounds_violation(reg)) 2062 return; 2063 /* We might have learned new bounds from the var_off. */ 2064 __update_reg_bounds(reg); 2065 /* We might have learned something about the sign bit. */ 2066 __reg_deduce_bounds(reg); 2067 __reg_deduce_bounds(reg); 2068 /* We might have learned some bits from the bounds. */ 2069 __reg_bound_offset(reg); 2070 /* Intersecting with the old var_off might have improved our bounds 2071 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2072 * then new var_off is (0; 0x7f...fc) which improves our umax. 2073 */ 2074 __update_reg_bounds(reg); 2075 } 2076 2077 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg) 2078 { 2079 if (!tnum_is_const(reg->var_off)) 2080 return false; 2081 2082 return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value; 2083 } 2084 2085 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg) 2086 { 2087 if (!tnum_subreg_is_const(reg->var_off)) 2088 return false; 2089 2090 return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value; 2091 } 2092 2093 static bool range_bounds_violation(struct bpf_reg_state *reg) 2094 { 2095 return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64); 2096 } 2097 2098 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2099 struct bpf_reg_state *reg, const char *ctx) 2100 { 2101 const char *msg; 2102 2103 if (range_bounds_violation(reg)) { 2104 msg = "range bounds violation"; 2105 goto out; 2106 } 2107 2108 if (const_tnum_range_mismatch(reg)) { 2109 msg = "const tnum out of sync with range bounds"; 2110 goto out; 2111 } 2112 2113 if (const_tnum_range_mismatch_32(reg)) { 2114 msg = "const subreg tnum out of sync with range bounds"; 2115 goto out; 2116 } 2117 2118 return 0; 2119 out: 2120 verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} " 2121 "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx)", 2122 ctx, msg, 2123 reg->r64.base, reg->r64.size, 2124 reg->r32.base, reg->r32.size, 2125 reg->var_off.value, reg->var_off.mask); 2126 if (env->test_reg_invariants) 2127 return -EFAULT; 2128 __mark_reg_unbounded(reg); 2129 return 0; 2130 } 2131 2132 /* Mark a register as having a completely unknown (scalar) value. */ 2133 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2134 { 2135 memset(reg, 0, sizeof(*reg)); 2136 reg->type = SCALAR_VALUE; 2137 reg->var_off = tnum_unknown; 2138 __mark_reg_unbounded(reg); 2139 } 2140 2141 /* Mark a register as having a completely unknown (scalar) value, 2142 * initialize .precise as true when not bpf capable. 2143 */ 2144 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2145 struct bpf_reg_state *reg) 2146 { 2147 bpf_mark_reg_unknown_imprecise(reg); 2148 reg->precise = !env->bpf_capable; 2149 } 2150 2151 static void mark_reg_unknown(struct bpf_verifier_env *env, 2152 struct bpf_reg_state *regs, u32 regno) 2153 { 2154 __mark_reg_unknown(env, regs + regno); 2155 } 2156 2157 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2158 struct bpf_reg_state *regs, 2159 u32 regno, 2160 s32 s32_min, 2161 s32 s32_max) 2162 { 2163 struct bpf_reg_state *reg = regs + regno; 2164 2165 reg_set_srange32(reg, 2166 max_t(s32, reg_s32_min(reg), s32_min), 2167 min_t(s32, reg_s32_max(reg), s32_max)); 2168 reg_set_srange64(reg, 2169 max_t(s64, reg_smin(reg), s32_min), 2170 min_t(s64, reg_smax(reg), s32_max)); 2171 2172 reg_bounds_sync(reg); 2173 2174 return reg_bounds_sanity_check(env, reg, "s32_range"); 2175 } 2176 2177 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env, 2178 struct bpf_reg_state *reg) 2179 { 2180 __mark_reg_unknown(env, reg); 2181 reg->type = NOT_INIT; 2182 } 2183 2184 static int mark_btf_ld_reg(struct bpf_verifier_env *env, 2185 struct bpf_reg_state *regs, u32 regno, 2186 enum bpf_reg_type reg_type, 2187 struct btf *btf, u32 btf_id, 2188 enum bpf_type_flag flag) 2189 { 2190 switch (reg_type) { 2191 case SCALAR_VALUE: 2192 mark_reg_unknown(env, regs, regno); 2193 return 0; 2194 case PTR_TO_BTF_ID: 2195 mark_reg_known_zero(env, regs, regno); 2196 regs[regno].type = PTR_TO_BTF_ID | flag; 2197 regs[regno].btf = btf; 2198 regs[regno].btf_id = btf_id; 2199 if (type_may_be_null(flag)) 2200 regs[regno].id = ++env->id_gen; 2201 return 0; 2202 case PTR_TO_MEM: 2203 mark_reg_known_zero(env, regs, regno); 2204 regs[regno].type = PTR_TO_MEM | flag; 2205 regs[regno].mem_size = 0; 2206 return 0; 2207 default: 2208 verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__); 2209 return -EFAULT; 2210 } 2211 } 2212 2213 static void init_reg_state(struct bpf_verifier_env *env, 2214 struct bpf_func_state *state) 2215 { 2216 struct bpf_reg_state *regs = state->regs; 2217 int i; 2218 2219 for (i = 0; i < MAX_BPF_REG; i++) { 2220 bpf_mark_reg_not_init(env, ®s[i]); 2221 } 2222 2223 /* frame pointer */ 2224 regs[BPF_REG_FP].type = PTR_TO_STACK; 2225 mark_reg_known_zero(env, regs, BPF_REG_FP); 2226 regs[BPF_REG_FP].frameno = state->frameno; 2227 } 2228 2229 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2230 { 2231 /* 2232 * return_32bit is set to false by default and set explicitly 2233 * by the caller when necessary. 2234 */ 2235 return (struct bpf_retval_range){ minval, maxval, false }; 2236 } 2237 2238 static void init_func_state(struct bpf_verifier_env *env, 2239 struct bpf_func_state *state, 2240 int callsite, int frameno, int subprogno) 2241 { 2242 state->callsite = callsite; 2243 state->frameno = frameno; 2244 state->subprogno = subprogno; 2245 state->callback_ret_range = retval_range(0, 0); 2246 init_reg_state(env, state); 2247 mark_verifier_state_scratched(env); 2248 } 2249 2250 /* Similar to push_stack(), but for async callbacks */ 2251 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2252 int insn_idx, int prev_insn_idx, 2253 int subprog, bool is_sleepable) 2254 { 2255 struct bpf_verifier_stack_elem *elem; 2256 struct bpf_func_state *frame; 2257 2258 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 2259 if (!elem) 2260 return ERR_PTR(-ENOMEM); 2261 2262 elem->insn_idx = insn_idx; 2263 elem->prev_insn_idx = prev_insn_idx; 2264 elem->next = env->head; 2265 elem->log_pos = env->log.end_pos; 2266 env->head = elem; 2267 env->stack_size++; 2268 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2269 verbose(env, 2270 "The sequence of %d jumps is too complex for async cb.\n", 2271 env->stack_size); 2272 return ERR_PTR(-E2BIG); 2273 } 2274 /* Unlike push_stack() do not bpf_copy_verifier_state(). 2275 * The caller state doesn't matter. 2276 * This is async callback. It starts in a fresh stack. 2277 * Initialize it similar to do_check_common(). 2278 */ 2279 elem->st.branches = 1; 2280 elem->st.in_sleepable = is_sleepable; 2281 frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT); 2282 if (!frame) 2283 return ERR_PTR(-ENOMEM); 2284 init_func_state(env, frame, 2285 BPF_MAIN_FUNC /* callsite */, 2286 0 /* frameno within this callchain */, 2287 subprog /* subprog number within this prog */); 2288 elem->st.frame[0] = frame; 2289 return &elem->st; 2290 } 2291 2292 2293 static int cmp_subprogs(const void *a, const void *b) 2294 { 2295 return ((struct bpf_subprog_info *)a)->start - 2296 ((struct bpf_subprog_info *)b)->start; 2297 } 2298 2299 /* Find subprogram that contains instruction at 'off' */ 2300 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off) 2301 { 2302 struct bpf_subprog_info *vals = env->subprog_info; 2303 int l, r, m; 2304 2305 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0) 2306 return NULL; 2307 2308 l = 0; 2309 r = env->subprog_cnt - 1; 2310 while (l < r) { 2311 m = l + (r - l + 1) / 2; 2312 if (vals[m].start <= off) 2313 l = m; 2314 else 2315 r = m - 1; 2316 } 2317 return &vals[l]; 2318 } 2319 2320 /* Find subprogram that starts exactly at 'off' */ 2321 int bpf_find_subprog(struct bpf_verifier_env *env, int off) 2322 { 2323 struct bpf_subprog_info *p; 2324 2325 p = bpf_find_containing_subprog(env, off); 2326 if (!p || p->start != off) 2327 return -ENOENT; 2328 return p - env->subprog_info; 2329 } 2330 2331 static int add_subprog(struct bpf_verifier_env *env, int off) 2332 { 2333 int insn_cnt = env->prog->len; 2334 int ret; 2335 2336 if (off >= insn_cnt || off < 0) { 2337 verbose(env, "call to invalid destination\n"); 2338 return -EINVAL; 2339 } 2340 ret = bpf_find_subprog(env, off); 2341 if (ret >= 0) 2342 return ret; 2343 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2344 verbose(env, "too many subprograms\n"); 2345 return -E2BIG; 2346 } 2347 /* determine subprog starts. The end is one before the next starts */ 2348 env->subprog_info[env->subprog_cnt++].start = off; 2349 sort(env->subprog_info, env->subprog_cnt, 2350 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2351 return env->subprog_cnt - 1; 2352 } 2353 2354 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2355 { 2356 struct bpf_prog_aux *aux = env->prog->aux; 2357 struct btf *btf = aux->btf; 2358 const struct btf_type *t; 2359 u32 main_btf_id, id; 2360 const char *name; 2361 int ret, i; 2362 2363 /* Non-zero func_info_cnt implies valid btf */ 2364 if (!aux->func_info_cnt) 2365 return 0; 2366 main_btf_id = aux->func_info[0].type_id; 2367 2368 t = btf_type_by_id(btf, main_btf_id); 2369 if (!t) { 2370 verbose(env, "invalid btf id for main subprog in func_info\n"); 2371 return -EINVAL; 2372 } 2373 2374 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2375 if (IS_ERR(name)) { 2376 ret = PTR_ERR(name); 2377 /* If there is no tag present, there is no exception callback */ 2378 if (ret == -ENOENT) 2379 ret = 0; 2380 else if (ret == -EEXIST) 2381 verbose(env, "multiple exception callback tags for main subprog\n"); 2382 return ret; 2383 } 2384 2385 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2386 if (ret < 0) { 2387 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2388 return ret; 2389 } 2390 id = ret; 2391 t = btf_type_by_id(btf, id); 2392 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2393 verbose(env, "exception callback '%s' must have global linkage\n", name); 2394 return -EINVAL; 2395 } 2396 ret = 0; 2397 for (i = 0; i < aux->func_info_cnt; i++) { 2398 if (aux->func_info[i].type_id != id) 2399 continue; 2400 ret = aux->func_info[i].insn_off; 2401 /* Further func_info and subprog checks will also happen 2402 * later, so assume this is the right insn_off for now. 2403 */ 2404 if (!ret) { 2405 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2406 ret = -EINVAL; 2407 } 2408 } 2409 if (!ret) { 2410 verbose(env, "exception callback type id not found in func_info\n"); 2411 ret = -EINVAL; 2412 } 2413 return ret; 2414 } 2415 2416 #define MAX_KFUNC_BTFS 256 2417 2418 struct bpf_kfunc_btf { 2419 struct btf *btf; 2420 struct module *module; 2421 u16 offset; 2422 }; 2423 2424 struct bpf_kfunc_btf_tab { 2425 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2426 u32 nr_descs; 2427 }; 2428 2429 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2430 { 2431 const struct bpf_kfunc_desc *d0 = a; 2432 const struct bpf_kfunc_desc *d1 = b; 2433 2434 /* func_id is not greater than BTF_MAX_TYPE */ 2435 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2436 } 2437 2438 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2439 { 2440 const struct bpf_kfunc_btf *d0 = a; 2441 const struct bpf_kfunc_btf *d1 = b; 2442 2443 return d0->offset - d1->offset; 2444 } 2445 2446 static struct bpf_kfunc_desc * 2447 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2448 { 2449 struct bpf_kfunc_desc desc = { 2450 .func_id = func_id, 2451 .offset = offset, 2452 }; 2453 struct bpf_kfunc_desc_tab *tab; 2454 2455 tab = prog->aux->kfunc_tab; 2456 return bsearch(&desc, tab->descs, tab->nr_descs, 2457 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2458 } 2459 2460 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2461 u16 btf_fd_idx, u8 **func_addr) 2462 { 2463 const struct bpf_kfunc_desc *desc; 2464 2465 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2466 if (!desc) 2467 return -EFAULT; 2468 2469 *func_addr = (u8 *)desc->addr; 2470 return 0; 2471 } 2472 2473 #define BPF_FD_SLOT_BTF 1UL 2474 2475 static void fd_slot_set_map(struct bpf_fd_array *slot, struct bpf_map *map) 2476 { 2477 slot->val = (unsigned long)map; 2478 } 2479 2480 static void fd_slot_set_btf(struct bpf_fd_array *slot, struct btf *btf) 2481 { 2482 slot->val = (unsigned long)btf | BPF_FD_SLOT_BTF; 2483 } 2484 2485 static struct bpf_map *fd_slot_map(struct bpf_fd_array slot) 2486 { 2487 if (slot.val & BPF_FD_SLOT_BTF) 2488 return NULL; 2489 return (struct bpf_map *)slot.val; 2490 } 2491 2492 static struct btf *fd_slot_btf(struct bpf_fd_array slot) 2493 { 2494 if (!(slot.val & BPF_FD_SLOT_BTF)) 2495 return NULL; 2496 return (struct btf *)(slot.val & ~BPF_FD_SLOT_BTF); 2497 } 2498 2499 static struct btf * 2500 fd_array_get_btf_continuous(struct bpf_verifier_env *env, u32 idx) 2501 { 2502 struct btf *btf; 2503 2504 if (idx >= env->fd_array_cnt) { 2505 verbose(env, "kfunc fd_idx %u out of bounds, fd_array_cnt %u\n", 2506 idx, env->fd_array_cnt); 2507 return ERR_PTR(-EINVAL); 2508 } 2509 btf = fd_slot_btf(env->fd_array[idx]); 2510 if (!btf) { 2511 verbose(env, "kfunc fd_idx %u is not a module BTF\n", idx); 2512 return ERR_PTR(-EINVAL); 2513 } 2514 btf_get(btf); 2515 return btf; 2516 } 2517 2518 static struct btf * 2519 fd_array_get_btf_sparse(struct bpf_verifier_env *env, u32 idx) 2520 { 2521 struct btf *btf; 2522 int btf_fd; 2523 2524 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array_raw, 2525 (size_t)idx * sizeof(btf_fd), sizeof(btf_fd))) 2526 return ERR_PTR(-EFAULT); 2527 btf = btf_get_by_fd(btf_fd); 2528 if (IS_ERR(btf)) { 2529 verbose(env, "invalid module BTF fd specified\n"); 2530 return btf; 2531 } 2532 return btf; 2533 } 2534 2535 static struct btf *fd_array_get_btf(struct bpf_verifier_env *env, u32 idx) 2536 { 2537 if (env->signature) { 2538 verbose(env, "signed program cannot bind any BTF\n"); 2539 return ERR_PTR(-EACCES); 2540 } 2541 if (env->fd_array) 2542 return fd_array_get_btf_continuous(env, idx); 2543 if (!bpfptr_is_null(env->fd_array_raw)) 2544 return fd_array_get_btf_sparse(env, idx); 2545 2546 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2547 return ERR_PTR(-EPROTO); 2548 } 2549 2550 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2551 s16 offset) 2552 { 2553 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2554 struct bpf_kfunc_btf_tab *tab; 2555 struct bpf_kfunc_btf *b; 2556 struct module *mod; 2557 struct btf *btf; 2558 2559 tab = env->prog->aux->kfunc_btf_tab; 2560 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2561 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2562 if (!b) { 2563 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2564 verbose(env, "too many different module BTFs\n"); 2565 return ERR_PTR(-E2BIG); 2566 } 2567 2568 btf = fd_array_get_btf(env, offset); 2569 if (IS_ERR(btf)) 2570 return btf; 2571 if (!btf_is_module(btf)) { 2572 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2573 btf_put(btf); 2574 return ERR_PTR(-EINVAL); 2575 } 2576 2577 mod = btf_try_get_module(btf); 2578 if (!mod) { 2579 btf_put(btf); 2580 return ERR_PTR(-ENXIO); 2581 } 2582 2583 b = &tab->descs[tab->nr_descs++]; 2584 b->btf = btf; 2585 b->module = mod; 2586 b->offset = offset; 2587 2588 /* sort() reorders entries by value, so b may no longer point 2589 * to the right entry after this 2590 */ 2591 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2592 kfunc_btf_cmp_by_off, NULL); 2593 } else { 2594 btf = b->btf; 2595 } 2596 2597 return btf; 2598 } 2599 2600 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2601 { 2602 if (!tab) 2603 return; 2604 2605 while (tab->nr_descs--) { 2606 module_put(tab->descs[tab->nr_descs].module); 2607 btf_put(tab->descs[tab->nr_descs].btf); 2608 } 2609 kfree(tab); 2610 } 2611 2612 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2613 { 2614 if (offset) { 2615 if (offset < 0) { 2616 /* In the future, this can be allowed to increase limit 2617 * of fd index into fd_array, interpreted as u16. 2618 */ 2619 verbose(env, "negative offset disallowed for kernel module function call\n"); 2620 return ERR_PTR(-EINVAL); 2621 } 2622 2623 return __find_kfunc_desc_btf(env, offset); 2624 } 2625 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2626 } 2627 2628 #define KF_IMPL_SUFFIX "_impl" 2629 2630 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_log *log, 2631 struct btf *btf, 2632 const char *func_name) 2633 { 2634 const struct btf_type *func; 2635 char buf[KSYM_NAME_LEN]; 2636 s32 impl_id; 2637 int len; 2638 2639 len = snprintf(buf, sizeof(buf), "%s%s", func_name, KF_IMPL_SUFFIX); 2640 if (len < 0 || len >= sizeof(buf)) { 2641 bpf_log(log, "function name %s%s is too long\n", 2642 func_name, KF_IMPL_SUFFIX); 2643 return NULL; 2644 } 2645 2646 impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC); 2647 if (impl_id <= 0) { 2648 bpf_log(log, "cannot find function %s in BTF\n", buf); 2649 return NULL; 2650 } 2651 2652 func = btf_type_by_id(btf, impl_id); 2653 2654 return btf_type_by_id(btf, func->type); 2655 } 2656 2657 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 2658 s32 func_id, 2659 s16 offset, 2660 struct bpf_kfunc_meta *kfunc) 2661 { 2662 const struct btf_type *func, *func_proto; 2663 const char *func_name; 2664 u32 *kfunc_flags; 2665 struct btf *btf; 2666 2667 if (func_id <= 0) { 2668 verbose(env, "invalid kernel function btf_id %d\n", func_id); 2669 return -EINVAL; 2670 } 2671 2672 btf = find_kfunc_desc_btf(env, offset); 2673 if (IS_ERR(btf)) { 2674 verbose(env, "failed to find BTF for kernel function\n"); 2675 return PTR_ERR(btf); 2676 } 2677 2678 /* 2679 * Note that kfunc_flags may be NULL at this point, which 2680 * means that we couldn't find func_id in any relevant 2681 * kfunc_id_set. This most likely indicates an invalid kfunc 2682 * call. However we don't fail with an error here, 2683 * and let the caller decide what to do with NULL kfunc->flags. 2684 */ 2685 kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog); 2686 2687 func = btf_type_by_id(btf, func_id); 2688 if (!func || !btf_type_is_func(func)) { 2689 verbose(env, "kernel btf_id %d is not a function\n", func_id); 2690 return -EINVAL; 2691 } 2692 2693 func_name = btf_name_by_offset(btf, func->name_off); 2694 2695 /* 2696 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag 2697 * can be found through the counterpart _impl kfunc. 2698 */ 2699 if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS)) 2700 func_proto = find_kfunc_impl_proto(&env->log, btf, func_name); 2701 else 2702 func_proto = btf_type_by_id(btf, func->type); 2703 2704 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2705 verbose(env, "kernel function btf_id %d does not have a valid func_proto\n", 2706 func_id); 2707 return -EINVAL; 2708 } 2709 2710 memset(kfunc, 0, sizeof(*kfunc)); 2711 kfunc->btf = btf; 2712 kfunc->id = func_id; 2713 kfunc->name = func_name; 2714 kfunc->proto = func_proto; 2715 kfunc->flags = kfunc_flags; 2716 2717 return 0; 2718 } 2719 2720 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 2721 struct bpf_func_proto *proto); 2722 2723 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset) 2724 { 2725 struct bpf_call_arg_meta meta; 2726 struct bpf_kfunc_btf_tab *btf_tab; 2727 struct btf_func_model func_model; 2728 struct bpf_kfunc_desc_tab *tab; 2729 struct bpf_prog_aux *prog_aux; 2730 struct bpf_kfunc_meta kfunc; 2731 struct bpf_kfunc_desc *desc; 2732 unsigned long addr; 2733 int err; 2734 2735 prog_aux = env->prog->aux; 2736 tab = prog_aux->kfunc_tab; 2737 btf_tab = prog_aux->kfunc_btf_tab; 2738 if (!tab) { 2739 if (!btf_vmlinux) { 2740 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2741 return -ENOTSUPP; 2742 } 2743 2744 if (!env->prog->jit_requested) { 2745 verbose(env, "JIT is required for calling kernel function\n"); 2746 return -ENOTSUPP; 2747 } 2748 2749 if (!bpf_jit_supports_kfunc_call()) { 2750 verbose(env, "JIT does not support calling kernel function\n"); 2751 return -ENOTSUPP; 2752 } 2753 2754 if (!env->prog->gpl_compatible) { 2755 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2756 return -EINVAL; 2757 } 2758 2759 tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT); 2760 if (!tab) 2761 return -ENOMEM; 2762 prog_aux->kfunc_tab = tab; 2763 } 2764 2765 env->prog->jit_required = 1; 2766 2767 /* func_id == 0 is always invalid, but instead of returning an error, be 2768 * conservative and wait until the code elimination pass before returning 2769 * error, so that invalid calls that get pruned out can be in BPF programs 2770 * loaded from userspace. It is also required that offset be untouched 2771 * for such calls. 2772 */ 2773 if (!func_id && !offset) 2774 return 0; 2775 2776 if (!btf_tab && offset) { 2777 btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT); 2778 if (!btf_tab) 2779 return -ENOMEM; 2780 prog_aux->kfunc_btf_tab = btf_tab; 2781 } 2782 2783 if (find_kfunc_desc(env->prog, func_id, offset)) 2784 return 0; 2785 2786 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2787 verbose(env, "too many different kernel function calls\n"); 2788 return -E2BIG; 2789 } 2790 2791 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 2792 if (err) 2793 return err; 2794 2795 addr = kallsyms_lookup_name(kfunc.name); 2796 if (!addr) { 2797 verbose(env, "cannot find address for kernel function %s\n", kfunc.name); 2798 return -EINVAL; 2799 } 2800 2801 if (bpf_dev_bound_kfunc_id(func_id)) { 2802 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2803 if (err) 2804 return err; 2805 } 2806 2807 err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model); 2808 if (err) 2809 return err; 2810 2811 memset(&meta, 0, sizeof(meta)); 2812 meta.btf = kfunc.btf; 2813 meta.func_id = kfunc.id; 2814 meta.func_proto = kfunc.proto; 2815 meta.func_name = kfunc.name; 2816 meta.kfunc_flags = kfunc.flags ? *kfunc.flags : 0; 2817 2818 tab = krealloc(tab, struct_size(tab, descs, tab->nr_descs + 1), GFP_KERNEL_ACCOUNT); 2819 if (!tab) 2820 return -ENOMEM; 2821 prog_aux->kfunc_tab = tab; 2822 2823 desc = &tab->descs[tab->nr_descs]; 2824 memset(desc, 0, sizeof(*desc)); 2825 2826 err = gen_kfunc_arg_proto(env, &meta, &desc->proto); 2827 if (err) 2828 return err; 2829 2830 desc->func_id = func_id; 2831 desc->offset = offset; 2832 desc->addr = addr; 2833 desc->func_model = func_model; 2834 tab->nr_descs++; 2835 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2836 kfunc_desc_cmp_by_id_off, NULL); 2837 return 0; 2838 } 2839 2840 static int add_subprogs(struct bpf_verifier_env *env) 2841 { 2842 struct bpf_subprog_info *subprog = env->subprog_info; 2843 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2844 struct bpf_insn *insn = env->prog->insnsi; 2845 2846 /* Add entry function. */ 2847 ret = add_subprog(env, 0); 2848 if (ret) 2849 return ret; 2850 2851 for (i = 0; i < insn_cnt; i++, insn++) { 2852 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 2853 continue; 2854 2855 if (!env->bpf_capable) { 2856 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2857 return -EPERM; 2858 } 2859 2860 ret = add_subprog(env, i + insn->imm + 1); 2861 if (ret < 0) 2862 return ret; 2863 } 2864 2865 ret = bpf_find_exception_callback_insn_off(env); 2866 if (ret < 0) 2867 return ret; 2868 ex_cb_insn = ret; 2869 2870 /* If ex_cb_insn > 0, this means that the main program has a subprog 2871 * marked using BTF decl tag to serve as the exception callback. 2872 */ 2873 if (ex_cb_insn) { 2874 ret = add_subprog(env, ex_cb_insn); 2875 if (ret < 0) 2876 return ret; 2877 for (i = 1; i < env->subprog_cnt; i++) { 2878 if (env->subprog_info[i].start != ex_cb_insn) 2879 continue; 2880 env->exception_callback_subprog = i; 2881 bpf_mark_subprog_exc_cb(env, i); 2882 break; 2883 } 2884 } 2885 2886 /* Add a fake 'exit' subprog which could simplify subprog iteration 2887 * logic. 'subprog_cnt' should not be increased. 2888 */ 2889 subprog[env->subprog_cnt].start = insn_cnt; 2890 2891 if (env->log.level & BPF_LOG_LEVEL2) 2892 for (i = 0; i < env->subprog_cnt; i++) 2893 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2894 2895 return 0; 2896 } 2897 2898 static int add_kfuncs(struct bpf_verifier_env *env) 2899 { 2900 struct bpf_insn *insn = env->prog->insnsi; 2901 int i, ret, insn_cnt = env->prog->len; 2902 2903 for (i = 0; i < insn_cnt; i++, insn++) { 2904 if (!bpf_pseudo_kfunc_call(insn)) 2905 continue; 2906 2907 if (!env->bpf_capable) { 2908 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2909 return -EPERM; 2910 } 2911 2912 ret = bpf_add_kfunc_call(env, insn->imm, insn->off); 2913 if (ret < 0) 2914 return ret; 2915 } 2916 2917 return 0; 2918 } 2919 2920 static int check_subprogs(struct bpf_verifier_env *env) 2921 { 2922 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2923 struct bpf_subprog_info *subprog = env->subprog_info; 2924 struct bpf_insn *insn = env->prog->insnsi; 2925 int insn_cnt = env->prog->len; 2926 2927 /* now check that all jumps are within the same subprog */ 2928 subprog_start = subprog[cur_subprog].start; 2929 subprog_end = subprog[cur_subprog + 1].start; 2930 for (i = 0; i < insn_cnt; i++) { 2931 u8 code = insn[i].code; 2932 2933 if (code == (BPF_JMP | BPF_CALL) && 2934 insn[i].src_reg == 0 && 2935 insn[i].imm == BPF_FUNC_tail_call) { 2936 subprog[cur_subprog].has_tail_call = true; 2937 subprog[cur_subprog].tail_call_reachable = true; 2938 } 2939 if (BPF_CLASS(code) == BPF_LD && 2940 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2941 subprog[cur_subprog].has_ld_abs = true; 2942 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2943 goto next; 2944 if (BPF_OP(code) == BPF_CALL) 2945 goto next; 2946 if (BPF_OP(code) == BPF_EXIT) { 2947 subprog[cur_subprog].exit_idx = i; 2948 goto next; 2949 } 2950 off = i + bpf_jmp_offset(&insn[i]) + 1; 2951 if (off < subprog_start || off >= subprog_end) { 2952 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2953 return -EINVAL; 2954 } 2955 next: 2956 if (i == subprog_end - 1) { 2957 /* to avoid fall-through from one subprog into another 2958 * the last insn of the subprog should be either exit 2959 * or unconditional jump back or bpf_throw call 2960 */ 2961 if (code != (BPF_JMP | BPF_EXIT) && 2962 code != (BPF_JMP32 | BPF_JA) && 2963 code != (BPF_JMP | BPF_JA)) { 2964 verbose(env, "last insn is not an exit or jmp\n"); 2965 return -EINVAL; 2966 } 2967 subprog_start = subprog_end; 2968 cur_subprog++; 2969 if (cur_subprog < env->subprog_cnt) 2970 subprog_end = subprog[cur_subprog + 1].start; 2971 } 2972 } 2973 return 0; 2974 } 2975 2976 /* 2977 * Sort subprogs in topological order so that leaf subprogs come first and 2978 * their callers come later. This is a DFS post-order traversal of the call 2979 * graph. Scan only reachable instructions (those in the computed postorder) of 2980 * the current subprog to discover callees (direct subprogs and sync 2981 * callbacks). 2982 */ 2983 static int sort_subprogs_topo(struct bpf_verifier_env *env) 2984 { 2985 struct bpf_subprog_info *si = env->subprog_info; 2986 int *insn_postorder = env->cfg.insn_postorder; 2987 struct bpf_insn *insn = env->prog->insnsi; 2988 int cnt = env->subprog_cnt; 2989 int *dfs_stack = NULL; 2990 int top = 0, order = 0; 2991 int i, ret = 0; 2992 u8 *color = NULL; 2993 2994 color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT); 2995 dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT); 2996 if (!color || !dfs_stack) { 2997 ret = -ENOMEM; 2998 goto out; 2999 } 3000 3001 /* 3002 * DFS post-order traversal. 3003 * Color values: 0 = unvisited, 1 = on stack, 2 = done. 3004 */ 3005 for (i = 0; i < cnt; i++) { 3006 if (color[i]) 3007 continue; 3008 color[i] = 1; 3009 dfs_stack[top++] = i; 3010 3011 while (top > 0) { 3012 int cur = dfs_stack[top - 1]; 3013 int po_start = si[cur].postorder_start; 3014 int po_end = si[cur + 1].postorder_start; 3015 bool pushed = false; 3016 int j; 3017 3018 for (j = po_start; j < po_end; j++) { 3019 int idx = insn_postorder[j]; 3020 int callee; 3021 3022 if (!bpf_pseudo_call(&insn[idx]) && !bpf_pseudo_func(&insn[idx])) 3023 continue; 3024 callee = bpf_find_subprog(env, idx + insn[idx].imm + 1); 3025 if (callee < 0) { 3026 ret = -EFAULT; 3027 goto out; 3028 } 3029 if (color[callee] == 2) 3030 continue; 3031 if (color[callee] == 1) { 3032 if (bpf_pseudo_func(&insn[idx])) 3033 continue; 3034 verbose(env, "recursive call from %s() to %s()\n", 3035 subprog_name(env, cur), 3036 subprog_name(env, callee)); 3037 ret = -EINVAL; 3038 goto out; 3039 } 3040 color[callee] = 1; 3041 dfs_stack[top++] = callee; 3042 pushed = true; 3043 break; 3044 } 3045 3046 if (!pushed) { 3047 color[cur] = 2; 3048 env->subprog_topo_order[order++] = cur; 3049 top--; 3050 } 3051 } 3052 } 3053 3054 if (env->log.level & BPF_LOG_LEVEL2) 3055 for (i = 0; i < cnt; i++) 3056 verbose(env, "topo_order[%d] = %s\n", 3057 i, subprog_name(env, env->subprog_topo_order[i])); 3058 out: 3059 kvfree(dfs_stack); 3060 kvfree(color); 3061 return ret; 3062 } 3063 3064 static void mark_stack_slots_scratched(struct bpf_verifier_env *env, 3065 int spi, int nr_slots) 3066 { 3067 int i; 3068 3069 for (i = 0; i < nr_slots; i++) 3070 mark_stack_slot_scratched(env, spi - i); 3071 } 3072 3073 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3074 enum bpf_reg_arg_type t) 3075 { 3076 struct bpf_reg_state *reg; 3077 3078 mark_reg_scratched(env, regno); 3079 3080 reg = ®s[regno]; 3081 if (t == SRC_OP) { 3082 /* check whether register used as source operand can be read */ 3083 if (reg->type == NOT_INIT) { 3084 verbose(env, "R%d !read_ok\n", regno); 3085 return -EACCES; 3086 } 3087 /* We don't need to worry about FP liveness because it's read-only */ 3088 if (regno == BPF_REG_FP) 3089 return 0; 3090 3091 return 0; 3092 } else { 3093 /* check whether register used as dest operand can be written to */ 3094 if (regno == BPF_REG_FP) { 3095 verbose(env, "frame pointer is read only\n"); 3096 return -EACCES; 3097 } 3098 if (t == DST_OP) 3099 mark_reg_unknown(env, regs, regno); 3100 } 3101 return 0; 3102 } 3103 3104 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3105 enum bpf_reg_arg_type t) 3106 { 3107 struct bpf_verifier_state *vstate = env->cur_state; 3108 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3109 3110 return __check_reg_arg(env, state->regs, regno, t); 3111 } 3112 3113 static void mark_indirect_target(struct bpf_verifier_env *env, int idx) 3114 { 3115 env->insn_aux_data[idx].indirect_target = true; 3116 } 3117 3118 #define LR_FRAMENO_BITS 4 3119 #define LR_SPI_BITS 6 3120 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3121 #define LR_SIZE_BITS 4 3122 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3123 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3124 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3125 #define LR_SPI_OFF LR_FRAMENO_BITS 3126 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3127 #define LINKED_REGS_MAX 5 3128 3129 static_assert(MAX_CALL_FRAMES <= (1 << LR_FRAMENO_BITS)); 3130 static_assert(LINKED_REGS_MAX < (1 << LR_SIZE_BITS)); 3131 static_assert(LINKED_REGS_MAX * LR_ENTRY_BITS + LR_SIZE_BITS <= 64); 3132 3133 struct linked_reg { 3134 u8 frameno; 3135 union { 3136 u8 spi; 3137 u8 regno; 3138 }; 3139 bool is_reg; 3140 }; 3141 3142 struct linked_regs { 3143 int cnt; 3144 struct linked_reg entries[LINKED_REGS_MAX]; 3145 }; 3146 3147 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3148 { 3149 if (s->cnt < LINKED_REGS_MAX) 3150 return &s->entries[s->cnt++]; 3151 3152 return NULL; 3153 } 3154 3155 /* 3156 * Use u64 as a vector of 5 11-bit values, use first 4-bits to track 3157 * number of elements currently in stack. 3158 * Pack one history entry for linked registers as 11 bits in the following format: 3159 * - 4-bits frameno 3160 * - 6-bits spi_or_reg 3161 * - 1-bit is_reg 3162 */ 3163 static u64 linked_regs_pack(struct linked_regs *s) 3164 { 3165 u64 val = 0; 3166 int i; 3167 3168 for (i = 0; i < s->cnt; ++i) { 3169 struct linked_reg *e = &s->entries[i]; 3170 u64 tmp = 0; 3171 3172 tmp |= e->frameno; 3173 tmp |= e->spi << LR_SPI_OFF; 3174 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3175 3176 val <<= LR_ENTRY_BITS; 3177 val |= tmp; 3178 } 3179 val <<= LR_SIZE_BITS; 3180 val |= s->cnt; 3181 return val; 3182 } 3183 3184 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3185 { 3186 int i; 3187 3188 s->cnt = val & LR_SIZE_MASK; 3189 val >>= LR_SIZE_BITS; 3190 3191 for (i = 0; i < s->cnt; ++i) { 3192 struct linked_reg *e = &s->entries[i]; 3193 3194 e->frameno = val & LR_FRAMENO_MASK; 3195 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3196 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3197 val >>= LR_ENTRY_BITS; 3198 } 3199 } 3200 3201 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3202 { 3203 const struct btf_type *func; 3204 struct btf *desc_btf; 3205 3206 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3207 return NULL; 3208 3209 desc_btf = find_kfunc_desc_btf(data, insn->off); 3210 if (IS_ERR(desc_btf)) 3211 return "<error>"; 3212 3213 func = btf_type_by_id(desc_btf, insn->imm); 3214 return btf_name_by_offset(desc_btf, func->name_off); 3215 } 3216 3217 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn) 3218 { 3219 const struct bpf_insn_cbs cbs = { 3220 .cb_call = disasm_kfunc_name, 3221 .cb_print = verbose, 3222 .private_data = env, 3223 }; 3224 3225 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3226 } 3227 3228 /* If any register R in hist->linked_regs is marked as precise in bt, 3229 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 3230 */ 3231 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 3232 { 3233 struct linked_regs linked_regs; 3234 bool some_precise = false; 3235 int i; 3236 3237 if (!hist || hist->linked_regs == 0) 3238 return; 3239 3240 linked_regs_unpack(hist->linked_regs, &linked_regs); 3241 for (i = 0; i < linked_regs.cnt; ++i) { 3242 struct linked_reg *e = &linked_regs.entries[i]; 3243 3244 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 3245 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 3246 some_precise = true; 3247 break; 3248 } 3249 } 3250 3251 if (!some_precise) 3252 return; 3253 3254 for (i = 0; i < linked_regs.cnt; ++i) { 3255 struct linked_reg *e = &linked_regs.entries[i]; 3256 3257 if (e->is_reg) 3258 bpf_bt_set_frame_reg(bt, e->frameno, e->regno); 3259 else 3260 bpf_bt_set_frame_slot(bt, e->frameno, e->spi); 3261 } 3262 } 3263 3264 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3265 { 3266 return bpf_mark_chain_precision(env, env->cur_state, regno, NULL); 3267 } 3268 3269 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 3270 * desired reg and stack masks across all relevant frames 3271 */ 3272 static int mark_chain_precision_batch(struct bpf_verifier_env *env, 3273 struct bpf_verifier_state *starting_state) 3274 { 3275 return bpf_mark_chain_precision(env, starting_state, -1, NULL); 3276 } 3277 3278 /* check if register is a constant scalar value */ 3279 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 3280 { 3281 return reg->type == SCALAR_VALUE && 3282 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 3283 } 3284 3285 /* assuming is_reg_const() is true, return constant value of a register */ 3286 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 3287 { 3288 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 3289 } 3290 3291 static bool is_pointer_regtype(enum bpf_reg_type type) 3292 { 3293 return type != SCALAR_VALUE && type != NOT_INIT; 3294 } 3295 3296 static bool __is_pointer_value(bool allow_ptr_leaks, 3297 const struct bpf_reg_state *reg) 3298 { 3299 if (allow_ptr_leaks) 3300 return false; 3301 3302 return is_pointer_regtype(reg->type); 3303 } 3304 3305 static void clear_scalar_id(struct bpf_reg_state *reg) 3306 { 3307 reg->id = 0; 3308 reg->delta = 0; 3309 } 3310 3311 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 3312 struct bpf_reg_state *src_reg) 3313 { 3314 if (src_reg->type != SCALAR_VALUE) 3315 return; 3316 /* 3317 * The verifier is processing rX = rY insn and 3318 * rY->id has special linked register already. 3319 * Cleared it, since multiple rX += const are not supported. 3320 */ 3321 if (src_reg->id & BPF_ADD_CONST) 3322 clear_scalar_id(src_reg); 3323 /* 3324 * Ensure that src_reg has a valid ID that will be copied to 3325 * dst_reg and then will be used by sync_linked_regs() to 3326 * propagate min/max range. 3327 */ 3328 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 3329 src_reg->id = ++env->id_gen; 3330 } 3331 3332 static void save_register_state(struct bpf_verifier_env *env, 3333 struct bpf_func_state *state, 3334 int spi, struct bpf_reg_state *reg, 3335 int size) 3336 { 3337 int i; 3338 3339 state->stack[spi].spilled_ptr = *reg; 3340 3341 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3342 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 3343 3344 /* size < 8 bytes spill */ 3345 for (; i; i--) 3346 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 3347 } 3348 3349 static bool is_bpf_st_mem(struct bpf_insn *insn) 3350 { 3351 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 3352 } 3353 3354 static int get_reg_width(struct bpf_reg_state *reg) 3355 { 3356 return fls64(reg_umax(reg)); 3357 } 3358 3359 /* See comment for mark_fastcall_pattern_for_call() */ 3360 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 3361 struct bpf_func_state *state, int insn_idx, int off) 3362 { 3363 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 3364 struct bpf_insn_aux_data *aux = env->insn_aux_data; 3365 int i; 3366 3367 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 3368 return; 3369 /* access to the region [max_stack_depth .. fastcall_stack_off) 3370 * from something that is not a part of the fastcall pattern, 3371 * disable fastcall rewrites for current subprogram by setting 3372 * fastcall_stack_off to a value smaller than any possible offset. 3373 */ 3374 subprog->fastcall_stack_off = S16_MIN; 3375 /* reset fastcall aux flags within subprogram, 3376 * happens at most once per subprogram 3377 */ 3378 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 3379 aux[i].fastcall_spills_num = 0; 3380 aux[i].fastcall_pattern = 0; 3381 } 3382 } 3383 3384 static void scrub_special_slot(struct bpf_func_state *state, int spi) 3385 { 3386 int i; 3387 3388 /* regular write of data into stack destroys any spilled ptr */ 3389 state->stack[spi].spilled_ptr.type = NOT_INIT; 3390 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 3391 if (is_stack_slot_special(&state->stack[spi])) 3392 for (i = 0; i < BPF_REG_SIZE; i++) 3393 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 3394 } 3395 3396 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3397 * stack boundary and alignment are checked in check_mem_access() 3398 */ 3399 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3400 /* stack frame we're writing to */ 3401 struct bpf_func_state *state, 3402 int off, int size, int value_regno, 3403 int insn_idx) 3404 { 3405 struct bpf_func_state *cur; /* state of the current function */ 3406 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3407 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3408 struct bpf_reg_state *reg = NULL; 3409 int insn_flags = INSN_F_STACK_ACCESS; 3410 int hist_spi = spi, hist_frame = state->frameno; 3411 3412 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 3413 * so it's aligned access and [off, off + size) are within stack limits 3414 */ 3415 if (!env->allow_ptr_leaks && 3416 bpf_is_spilled_reg(&state->stack[spi]) && 3417 !bpf_is_spilled_scalar_reg(&state->stack[spi]) && 3418 size != BPF_REG_SIZE) { 3419 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3420 return -EACCES; 3421 } 3422 3423 cur = env->cur_state->frame[env->cur_state->curframe]; 3424 if (value_regno >= 0) 3425 reg = &cur->regs[value_regno]; 3426 if (!env->bypass_spec_v4) { 3427 bool sanitize = reg && is_pointer_regtype(reg->type); 3428 3429 for (i = 0; i < size; i++) { 3430 u8 type = state->stack[spi].slot_type[(slot - i) % 3431 BPF_REG_SIZE]; 3432 3433 if (type != STACK_MISC && type != STACK_ZERO) { 3434 sanitize = true; 3435 break; 3436 } 3437 } 3438 3439 if (sanitize) 3440 env->insn_aux_data[insn_idx].nospec_result = true; 3441 } 3442 3443 err = destroy_if_dynptr_stack_slot(env, state, spi); 3444 if (err) 3445 return err; 3446 3447 check_fastcall_stack_contract(env, state, insn_idx, off); 3448 mark_stack_slot_scratched(env, spi); 3449 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 3450 bool reg_value_fits; 3451 3452 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 3453 /* Make sure that reg had an ID to build a relation on spill. */ 3454 if (reg_value_fits) 3455 assign_scalar_id_before_mov(env, reg); 3456 save_register_state(env, state, spi, reg, size); 3457 /* Break the relation on a narrowing spill. */ 3458 if (!reg_value_fits) 3459 state->stack[spi].spilled_ptr.id = 0; 3460 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 3461 env->bpf_capable) { 3462 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 3463 3464 memset(tmp_reg, 0, sizeof(*tmp_reg)); 3465 __mark_reg_known(tmp_reg, insn->imm); 3466 tmp_reg->type = SCALAR_VALUE; 3467 save_register_state(env, state, spi, tmp_reg, size); 3468 } else if (reg && is_pointer_regtype(reg->type)) { 3469 /* register containing pointer is being spilled into stack */ 3470 if (size != BPF_REG_SIZE) { 3471 verbose_linfo(env, insn_idx, "; "); 3472 verbose(env, "invalid size of register spill\n"); 3473 return -EACCES; 3474 } 3475 if (state != cur && reg->type == PTR_TO_STACK) { 3476 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 3477 return -EINVAL; 3478 } 3479 save_register_state(env, state, spi, reg, size); 3480 } else { 3481 u8 type = STACK_MISC; 3482 3483 scrub_special_slot(state, spi); 3484 3485 /* when we zero initialize stack slots mark them as such */ 3486 if ((reg && bpf_register_is_null(reg)) || 3487 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 3488 /* STACK_ZERO case happened because register spill 3489 * wasn't properly aligned at the stack slot boundary, 3490 * so it's not a register spill anymore; force 3491 * originating register to be precise to make 3492 * STACK_ZERO correct for subsequent states 3493 */ 3494 err = mark_chain_precision(env, value_regno); 3495 if (err) 3496 return err; 3497 type = STACK_ZERO; 3498 } 3499 3500 /* Mark slots affected by this stack write. */ 3501 for (i = 0; i < size; i++) 3502 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 3503 insn_flags = 0; /* not a register spill */ 3504 } 3505 3506 if (insn_flags) 3507 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3508 hist_spi, hist_frame, 0); 3509 return 0; 3510 } 3511 3512 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is 3513 * known to contain a variable offset. 3514 * This function checks whether the write is permitted and conservatively 3515 * tracks the effects of the write, considering that each stack slot in the 3516 * dynamic range is potentially written to. 3517 * 3518 * 'value_regno' can be -1, meaning that an unknown value is being written to 3519 * the stack. 3520 * 3521 * Spilled pointers in range are not marked as written because we don't know 3522 * what's going to be actually written. This means that read propagation for 3523 * future reads cannot be terminated by this write. 3524 * 3525 * For privileged programs, uninitialized stack slots are considered 3526 * initialized by this write (even though we don't know exactly what offsets 3527 * are going to be written to). The idea is that we don't want the verifier to 3528 * reject future reads that access slots written to through variable offsets. 3529 */ 3530 static int check_stack_write_var_off(struct bpf_verifier_env *env, 3531 /* func where register points to */ 3532 struct bpf_func_state *state, 3533 struct bpf_reg_state *ptr_reg, int off, int size, 3534 int value_regno, int insn_idx) 3535 { 3536 struct bpf_func_state *cur; /* state of the current function */ 3537 int min_off, max_off; 3538 int i, err; 3539 struct bpf_reg_state *value_reg = NULL; 3540 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3541 bool writing_zero = false; 3542 /* set if the fact that we're writing a zero is used to let any 3543 * stack slots remain STACK_ZERO 3544 */ 3545 bool zero_used = false; 3546 3547 cur = env->cur_state->frame[env->cur_state->curframe]; 3548 min_off = reg_smin(ptr_reg) + off; 3549 max_off = reg_smax(ptr_reg) + off + size; 3550 if (value_regno >= 0) 3551 value_reg = &cur->regs[value_regno]; 3552 if ((value_reg && bpf_register_is_null(value_reg)) || 3553 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 3554 writing_zero = true; 3555 3556 for (i = min_off; i < max_off; i++) { 3557 int spi; 3558 3559 spi = bpf_get_spi(i); 3560 err = destroy_if_dynptr_stack_slot(env, state, spi); 3561 if (err) 3562 return err; 3563 } 3564 3565 check_fastcall_stack_contract(env, state, insn_idx, min_off); 3566 /* Variable offset writes destroy any spilled pointers in range. */ 3567 for (i = min_off; i < max_off; i++) { 3568 u8 new_type, *stype; 3569 int slot, spi; 3570 3571 slot = -i - 1; 3572 spi = slot / BPF_REG_SIZE; 3573 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 3574 mark_stack_slot_scratched(env, spi); 3575 3576 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 3577 /* Reject the write if range we may write to has not 3578 * been initialized beforehand. If we didn't reject 3579 * here, the ptr status would be erased below (even 3580 * though not all slots are actually overwritten), 3581 * possibly opening the door to leaks. 3582 * 3583 * We do however catch STACK_INVALID case below, and 3584 * only allow reading possibly uninitialized memory 3585 * later for CAP_PERFMON, as the write may not happen to 3586 * that slot. 3587 */ 3588 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 3589 insn_idx, i); 3590 return -EINVAL; 3591 } 3592 3593 /* If writing_zero and the spi slot contains a spill of value 0, 3594 * maintain the spill type. 3595 */ 3596 if (writing_zero && *stype == STACK_SPILL && 3597 bpf_is_spilled_scalar_reg(&state->stack[spi])) { 3598 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 3599 3600 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 3601 zero_used = true; 3602 continue; 3603 } 3604 } 3605 3606 /* 3607 * Scrub slots if variable-offset stack write goes over spilled pointers. 3608 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT 3609 * and valid program is rejected by check_stack_read_fixed_off() 3610 * with obscure "invalid size of register fill" message. 3611 */ 3612 scrub_special_slot(state, spi); 3613 3614 /* Update the slot type. */ 3615 new_type = STACK_MISC; 3616 if (writing_zero && *stype == STACK_ZERO) { 3617 new_type = STACK_ZERO; 3618 zero_used = true; 3619 } 3620 /* If the slot is STACK_INVALID, we check whether it's OK to 3621 * pretend that it will be initialized by this write. The slot 3622 * might not actually be written to, and so if we mark it as 3623 * initialized future reads might leak uninitialized memory. 3624 * For privileged programs, we will accept such reads to slots 3625 * that may or may not be written because, if we're reject 3626 * them, the error would be too confusing. 3627 * Conservatively, treat STACK_POISON in a similar way. 3628 */ 3629 if ((*stype == STACK_INVALID || *stype == STACK_POISON) && 3630 !env->allow_uninit_stack) { 3631 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 3632 insn_idx, i); 3633 return -EINVAL; 3634 } 3635 *stype = new_type; 3636 } 3637 if (zero_used) { 3638 /* backtracking doesn't work for STACK_ZERO yet. */ 3639 err = mark_chain_precision(env, value_regno); 3640 if (err) 3641 return err; 3642 } 3643 return 0; 3644 } 3645 3646 /* When register 'dst_regno' is assigned some values from stack[min_off, 3647 * max_off), we set the register's type according to the types of the 3648 * respective stack slots. If all the stack values are known to be zeros, then 3649 * so is the destination reg. Otherwise, the register is considered to be 3650 * SCALAR. This function does not deal with register filling; the caller must 3651 * ensure that all spilled registers in the stack range have been marked as 3652 * read. 3653 * 3654 * STACK_SPILL bytes backed by spilled scalar const zeroes are also considered 3655 * zero bytes. In that case, mark the contributing stack slots precise so 3656 * pruning cannot reuse a zero-spill state for a later non-zero spill state. 3657 * 3658 * Returns an error if precision backtracking fails. 3659 */ 3660 static int mark_reg_stack_read(struct bpf_verifier_env *env, 3661 /* func where src register points to */ 3662 struct bpf_func_state *ptr_state, 3663 int min_off, int max_off, int dst_regno) 3664 { 3665 struct bpf_verifier_state *vstate = env->cur_state; 3666 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3667 u64 zero_spill_mask = 0; 3668 int i, slot, spi; 3669 u8 *stype; 3670 int zeros = 0; 3671 3672 for (i = min_off; i < max_off; i++) { 3673 slot = -i - 1; 3674 spi = slot / BPF_REG_SIZE; 3675 mark_stack_slot_scratched(env, spi); 3676 stype = ptr_state->stack[spi].slot_type; 3677 if (stype[slot % BPF_REG_SIZE] == STACK_ZERO) { 3678 zeros++; 3679 continue; 3680 } 3681 if (stype[slot % BPF_REG_SIZE] == STACK_SPILL && 3682 bpf_register_is_null(&ptr_state->stack[spi].spilled_ptr)) { 3683 zero_spill_mask |= 1ull << spi; 3684 zeros++; 3685 continue; 3686 } 3687 break; 3688 } 3689 if (zeros == max_off - min_off) { 3690 /* Any access_size read into register is zero extended, 3691 * so the whole register == const_zero. 3692 */ 3693 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3694 if (zero_spill_mask) { 3695 bpf_bt_set_frame_slot_mask(&env->bt, ptr_state->frameno, zero_spill_mask); 3696 return mark_chain_precision_batch(env, env->cur_state); 3697 } 3698 } else { 3699 /* have read misc data from the stack */ 3700 mark_reg_unknown(env, state->regs, dst_regno); 3701 } 3702 3703 return 0; 3704 } 3705 3706 /* Read the stack at 'off' and put the results into the register indicated by 3707 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 3708 * spilled reg. 3709 * 3710 * 'dst_regno' can be -1, meaning that the read value is not going to a 3711 * register. 3712 * 3713 * The access is assumed to be within the current stack bounds. 3714 */ 3715 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 3716 /* func where src register points to */ 3717 struct bpf_func_state *reg_state, 3718 int off, int size, int dst_regno) 3719 { 3720 struct bpf_verifier_state *vstate = env->cur_state; 3721 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3722 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 3723 struct bpf_reg_state *reg; 3724 u8 *stype, type; 3725 int err; 3726 int insn_flags = INSN_F_STACK_ACCESS; 3727 int hist_spi = spi, hist_frame = reg_state->frameno; 3728 3729 stype = reg_state->stack[spi].slot_type; 3730 reg = ®_state->stack[spi].spilled_ptr; 3731 3732 mark_stack_slot_scratched(env, spi); 3733 check_fastcall_stack_contract(env, state, env->insn_idx, off); 3734 3735 if (bpf_is_spilled_reg(®_state->stack[spi])) { 3736 u8 spill_size = 1; 3737 3738 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 3739 spill_size++; 3740 3741 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 3742 if (reg->type != SCALAR_VALUE) { 3743 verbose_linfo(env, env->insn_idx, "; "); 3744 verbose(env, "invalid size of register fill\n"); 3745 return -EACCES; 3746 } 3747 3748 if (dst_regno < 0) 3749 return 0; 3750 3751 if (size <= spill_size && 3752 bpf_stack_narrow_access_ok(off, size, spill_size)) { 3753 if (env->bpf_capable && size == 4 && spill_size == 4 && 3754 get_reg_width(reg) <= 32) 3755 /* Ensure stack slot has an ID to build a relation 3756 * with the destination register on fill. 3757 */ 3758 assign_scalar_id_before_mov(env, reg); 3759 state->regs[dst_regno] = *reg; 3760 3761 /* Break the relation on a narrowing fill. 3762 * coerce_reg_to_size will adjust the boundaries. 3763 */ 3764 if (get_reg_width(reg) > size * BITS_PER_BYTE) 3765 clear_scalar_id(&state->regs[dst_regno]); 3766 } else { 3767 int spill_cnt = 0, zero_cnt = 0; 3768 3769 for (i = 0; i < size; i++) { 3770 type = stype[(slot - i) % BPF_REG_SIZE]; 3771 if (type == STACK_SPILL) { 3772 spill_cnt++; 3773 continue; 3774 } 3775 if (type == STACK_MISC) 3776 continue; 3777 if (type == STACK_ZERO) { 3778 zero_cnt++; 3779 continue; 3780 } 3781 if (type == STACK_INVALID && env->allow_uninit_stack) 3782 continue; 3783 if (type == STACK_POISON) { 3784 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3785 off, i, size); 3786 } else { 3787 verbose(env, "invalid read from stack off %d+%d size %d\n", 3788 off, i, size); 3789 } 3790 return -EACCES; 3791 } 3792 3793 if (spill_cnt == size && 3794 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 3795 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3796 /* this IS register fill, so keep insn_flags */ 3797 } else if (zero_cnt == size) { 3798 /* similarly to mark_reg_stack_read(), preserve zeroes */ 3799 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3800 insn_flags = 0; /* not restoring original register state */ 3801 } else { 3802 err = mark_reg_stack_read(env, reg_state, off, off + size, 3803 dst_regno); 3804 if (err) 3805 return err; 3806 insn_flags = 0; /* not restoring original register state */ 3807 } 3808 } 3809 } else if (dst_regno >= 0) { 3810 /* restore register state from stack */ 3811 if (env->bpf_capable) 3812 /* Ensure stack slot has an ID to build a relation 3813 * with the destination register on fill. 3814 */ 3815 assign_scalar_id_before_mov(env, reg); 3816 state->regs[dst_regno] = *reg; 3817 /* mark reg as written since spilled pointer state likely 3818 * has its liveness marks cleared by is_state_visited() 3819 * which resets stack/reg liveness for state transitions 3820 */ 3821 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 3822 /* If dst_regno==-1, the caller is asking us whether 3823 * it is acceptable to use this value as a SCALAR_VALUE 3824 * (e.g. for XADD). 3825 * We must not allow unprivileged callers to do that 3826 * with spilled pointers. 3827 */ 3828 verbose(env, "leaking pointer from stack off %d\n", 3829 off); 3830 return -EACCES; 3831 } 3832 } else { 3833 for (i = 0; i < size; i++) { 3834 type = stype[(slot - i) % BPF_REG_SIZE]; 3835 if (type == STACK_MISC) 3836 continue; 3837 if (type == STACK_ZERO) 3838 continue; 3839 if (type == STACK_INVALID && env->allow_uninit_stack) 3840 continue; 3841 if (type == STACK_POISON) { 3842 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3843 off, i, size); 3844 } else { 3845 verbose(env, "invalid read from stack off %d+%d size %d\n", 3846 off, i, size); 3847 } 3848 return -EACCES; 3849 } 3850 if (dst_regno >= 0) { 3851 err = mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3852 if (err) 3853 return err; 3854 } 3855 insn_flags = 0; /* we are not restoring spilled register */ 3856 } 3857 if (insn_flags) 3858 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3859 hist_spi, hist_frame, 0); 3860 return 0; 3861 } 3862 3863 enum bpf_access_src { 3864 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3865 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3866 }; 3867 3868 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3869 argno_t argno, int off, int access_size, 3870 bool zero_size_allowed, 3871 enum bpf_access_type type, 3872 struct bpf_call_arg_meta *meta); 3873 3874 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3875 { 3876 return cur_regs(env) + regno; 3877 } 3878 3879 /* Read the stack at 'reg + off' and put the result into the register 3880 * 'dst_regno'. 3881 * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'), 3882 * but not its variable offset. 3883 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3884 * 3885 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3886 * filling registers (i.e. reads of spilled register cannot be detected when 3887 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3888 * SCALAR_VALUE. That's why we assert that the 'reg' has a variable 3889 * offset; for a fixed offset check_stack_read_fixed_off should be used 3890 * instead. 3891 */ 3892 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3893 argno_t ptr_argno, int off, int size, int dst_regno) 3894 { 3895 struct bpf_func_state *ptr_state = bpf_func(env, reg); 3896 int err; 3897 int min_off, max_off; 3898 3899 /* Note that we pass a NULL meta, so raw access will not be permitted. 3900 */ 3901 err = check_stack_range_initialized(env, reg, ptr_argno, off, size, 3902 false, BPF_READ, NULL); 3903 if (err) 3904 return err; 3905 3906 min_off = reg_smin(reg) + off; 3907 max_off = reg_smax(reg) + off; 3908 err = mark_reg_stack_read(env, ptr_state, min_off, max_off + size, 3909 dst_regno); 3910 if (err) 3911 return err; 3912 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 3913 return 0; 3914 } 3915 3916 /* check_stack_read dispatches to check_stack_read_fixed_off or 3917 * check_stack_read_var_off. 3918 * 3919 * The caller must ensure that the offset falls within the allocated stack 3920 * bounds. 3921 * 3922 * 'dst_regno' is a register which will receive the value from the stack. It 3923 * can be -1, meaning that the read value is not going to a register. 3924 */ 3925 static int check_stack_read(struct bpf_verifier_env *env, 3926 struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size, 3927 int dst_regno) 3928 { 3929 struct bpf_func_state *state = bpf_func(env, reg); 3930 int err; 3931 /* Some accesses are only permitted with a static offset. */ 3932 bool var_off = !tnum_is_const(reg->var_off); 3933 3934 /* The offset is required to be static when reads don't go to a 3935 * register, in order to not leak pointers (see 3936 * check_stack_read_fixed_off). 3937 */ 3938 if (dst_regno < 0 && var_off) { 3939 char tn_buf[48]; 3940 3941 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3942 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 3943 tn_buf, off, size); 3944 return -EACCES; 3945 } 3946 /* Variable offset is prohibited for unprivileged mode for simplicity 3947 * since it requires corresponding support in Spectre masking for stack 3948 * ALU. See also retrieve_ptr_limit(). The check in 3949 * check_stack_access_for_ptr_arithmetic() called by 3950 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 3951 * with variable offsets, therefore no check is required here. Further, 3952 * just checking it here would be insufficient as speculative stack 3953 * writes could still lead to unsafe speculative behaviour. 3954 */ 3955 if (!var_off) { 3956 off += reg->var_off.value; 3957 err = check_stack_read_fixed_off(env, state, off, size, 3958 dst_regno); 3959 } else { 3960 /* Variable offset stack reads need more conservative handling 3961 * than fixed offset ones. Note that dst_regno >= 0 on this 3962 * branch. 3963 */ 3964 err = check_stack_read_var_off(env, reg, ptr_argno, off, size, 3965 dst_regno); 3966 } 3967 return err; 3968 } 3969 3970 3971 /* check_stack_write dispatches to check_stack_write_fixed_off or 3972 * check_stack_write_var_off. 3973 * 3974 * 'reg' is the register used as a pointer into the stack. 3975 * 'value_regno' is the register whose value we're writing to the stack. It can 3976 * be -1, meaning that we're not writing from a register. 3977 * 3978 * The caller must ensure that the offset falls within the maximum stack size. 3979 */ 3980 static int check_stack_write(struct bpf_verifier_env *env, 3981 struct bpf_reg_state *reg, int off, int size, 3982 int value_regno, int insn_idx) 3983 { 3984 struct bpf_func_state *state = bpf_func(env, reg); 3985 int err; 3986 3987 if (tnum_is_const(reg->var_off)) { 3988 off += reg->var_off.value; 3989 err = check_stack_write_fixed_off(env, state, off, size, 3990 value_regno, insn_idx); 3991 } else { 3992 /* Variable offset stack reads need more conservative handling 3993 * than fixed offset ones. 3994 */ 3995 err = check_stack_write_var_off(env, state, 3996 reg, off, size, 3997 value_regno, insn_idx); 3998 } 3999 return err; 4000 } 4001 4002 /* 4003 * Write a value to the outgoing stack arg area. 4004 * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7). 4005 */ 4006 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state, 4007 int off, struct bpf_reg_state *value_reg) 4008 { 4009 int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS; 4010 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4011 int spi = -off / BPF_REG_SIZE - 1; 4012 struct bpf_reg_state *arg; 4013 int err; 4014 4015 if (spi >= max_stack_arg_regs) { 4016 verbose(env, "stack arg write offset %d exceeds max %d stack args\n", 4017 off, max_stack_arg_regs); 4018 return -EINVAL; 4019 } 4020 4021 err = grow_stack_arg_slots(env, state, spi + 1); 4022 if (err) 4023 return err; 4024 4025 /* Track the max outgoing stack arg slot count. */ 4026 if (spi + 1 > subprog->max_out_stack_arg_cnt) 4027 subprog->max_out_stack_arg_cnt = spi + 1; 4028 4029 if (value_reg) { 4030 state->stack_arg_regs[spi] = *value_reg; 4031 } else { 4032 /* BPF_ST: store immediate, treat as scalar */ 4033 arg = &state->stack_arg_regs[spi]; 4034 arg->type = SCALAR_VALUE; 4035 __mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm); 4036 } 4037 state->no_stack_arg_load = true; 4038 return bpf_push_jmp_history(env, env->cur_state, 4039 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4040 } 4041 4042 /* 4043 * Read a value from the incoming stack arg area. 4044 * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7). 4045 */ 4046 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state, 4047 int off, int dst_regno) 4048 { 4049 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4050 struct bpf_verifier_state *vstate = env->cur_state; 4051 int spi = off / BPF_REG_SIZE - 1; 4052 struct bpf_func_state *caller, *cur; 4053 struct bpf_reg_state *arg; 4054 4055 if (state->no_stack_arg_load) { 4056 verbose(env, "r11 load must be before any r11 store or call insn\n"); 4057 return -EINVAL; 4058 } 4059 4060 if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) { 4061 verbose(env, "invalid read from stack arg off %d depth %d\n", 4062 off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE); 4063 return -EACCES; 4064 } 4065 4066 caller = vstate->frame[vstate->curframe - 1]; 4067 arg = &caller->stack_arg_regs[spi]; 4068 cur = vstate->frame[vstate->curframe]; 4069 cur->regs[dst_regno] = *arg; 4070 return bpf_push_jmp_history(env, env->cur_state, 4071 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4072 } 4073 4074 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx) 4075 { 4076 struct bpf_func_state *caller = cur_func(env); 4077 int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS; 4078 4079 bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi); 4080 return mark_chain_precision_batch(env, env->cur_state); 4081 } 4082 4083 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller, 4084 int nargs) 4085 { 4086 int i, spi; 4087 4088 for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) { 4089 spi = i - MAX_BPF_FUNC_REG_ARGS; 4090 if (spi >= caller->out_stack_arg_cnt || 4091 caller->stack_arg_regs[spi].type == NOT_INIT) { 4092 verbose(env, "callee expects %d args, stack arg%d is not initialized\n", 4093 nargs, spi + 1); 4094 return -EFAULT; 4095 } 4096 } 4097 4098 return 0; 4099 } 4100 4101 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller, 4102 struct bpf_reg_state *regs, int arg) 4103 { 4104 if (arg < MAX_BPF_FUNC_REG_ARGS) 4105 return ®s[arg + 1]; 4106 4107 return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS]; 4108 } 4109 4110 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4111 int off, int size, enum bpf_access_type type) 4112 { 4113 struct bpf_map *map = reg->map_ptr; 4114 u32 cap = bpf_map_flags_to_cap(map); 4115 4116 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4117 verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n", 4118 map->value_size, reg_smin(reg) + off, size); 4119 return -EACCES; 4120 } 4121 4122 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4123 verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n", 4124 map->value_size, reg_smin(reg) + off, size); 4125 return -EACCES; 4126 } 4127 4128 return 0; 4129 } 4130 4131 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4132 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4133 int off, int size, u32 mem_size, 4134 bool zero_size_allowed) 4135 { 4136 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4137 4138 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4139 return 0; 4140 4141 switch (reg->type) { 4142 case PTR_TO_MAP_KEY: 4143 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4144 mem_size, off, size); 4145 break; 4146 case PTR_TO_MAP_VALUE: 4147 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4148 mem_size, off, size); 4149 break; 4150 case PTR_TO_PACKET: 4151 case PTR_TO_PACKET_META: 4152 case PTR_TO_PACKET_END: 4153 verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n", 4154 off, size, reg_arg_name(env, argno), reg->id, off, mem_size); 4155 break; 4156 case PTR_TO_CTX: 4157 verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n", 4158 mem_size, off, size); 4159 break; 4160 case PTR_TO_MEM: 4161 default: 4162 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4163 mem_size, off, size); 4164 } 4165 4166 return -EACCES; 4167 } 4168 4169 /* check read/write into a memory region with possible variable offset */ 4170 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4171 int off, int size, u32 mem_size, 4172 bool zero_size_allowed) 4173 { 4174 int err; 4175 4176 /* We may have adjusted the register pointing to memory region, so we 4177 * need to try adding each of min_value and max_value to off 4178 * to make sure our theoretical access will be safe. 4179 * 4180 * The minimum value is only important with signed 4181 * comparisons where we can't assume the floor of a 4182 * value is 0. If we are using signed variables for our 4183 * index'es we need to make sure that whatever we use 4184 * will have a set floor within our range. 4185 */ 4186 if (reg_smin(reg) < 0 && 4187 (reg_smin(reg) == S64_MIN || 4188 (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) || 4189 reg_smin(reg) + off < 0)) { 4190 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4191 reg_arg_name(env, argno)); 4192 return -EACCES; 4193 } 4194 err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size, 4195 mem_size, zero_size_allowed); 4196 if (err) { 4197 verbose(env, "%s min value is outside of the allowed memory range\n", 4198 reg_arg_name(env, argno)); 4199 return err; 4200 } 4201 4202 /* If we haven't set a max value then we need to bail since we can't be 4203 * sure we won't do bad things. 4204 * If reg_umax(reg) + off could overflow, treat that as unbounded too. 4205 */ 4206 if (reg_umax(reg) >= BPF_MAX_VAR_OFF) { 4207 verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n", 4208 reg_arg_name(env, argno)); 4209 return -EACCES; 4210 } 4211 err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size, 4212 mem_size, zero_size_allowed); 4213 if (err) { 4214 verbose(env, "%s max value is outside of the allowed memory range\n", 4215 reg_arg_name(env, argno)); 4216 return err; 4217 } 4218 4219 return 0; 4220 } 4221 4222 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4223 const struct bpf_reg_state *reg, argno_t argno, 4224 bool fixed_off_ok) 4225 { 4226 /* Access to this pointer-typed register or passing it to a helper 4227 * is only allowed in its original, unmodified form. 4228 */ 4229 4230 if (!tnum_is_const(reg->var_off)) { 4231 char tn_buf[48]; 4232 4233 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4234 verbose(env, "variable %s access var_off=%s disallowed\n", 4235 reg_type_str(env, reg->type), tn_buf); 4236 return -EACCES; 4237 } 4238 4239 if (reg_smin(reg) < 0) { 4240 verbose(env, "negative offset %s ptr %s off=%lld disallowed\n", 4241 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4242 return -EACCES; 4243 } 4244 4245 if (!fixed_off_ok && reg->var_off.value != 0) { 4246 verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n", 4247 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4248 return -EACCES; 4249 } 4250 4251 return 0; 4252 } 4253 4254 static int check_ptr_off_reg(struct bpf_verifier_env *env, 4255 const struct bpf_reg_state *reg, int regno) 4256 { 4257 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 4258 } 4259 4260 static int map_kptr_match_type(struct bpf_verifier_env *env, 4261 struct btf_field *kptr_field, 4262 struct bpf_reg_state *reg, u32 regno) 4263 { 4264 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4265 int perm_flags; 4266 const char *reg_name = ""; 4267 4268 if (base_type(reg->type) != PTR_TO_BTF_ID) 4269 goto bad_type; 4270 4271 if (btf_is_kernel(reg->btf)) { 4272 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 4273 4274 /* Only unreferenced case accepts untrusted pointers */ 4275 if (kptr_field->type == BPF_KPTR_UNREF) 4276 perm_flags |= PTR_UNTRUSTED; 4277 } else { 4278 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 4279 if (kptr_field->type == BPF_KPTR_PERCPU) 4280 perm_flags |= MEM_PERCPU; 4281 } 4282 4283 if (type_flag(reg->type) & ~perm_flags) 4284 goto bad_type; 4285 4286 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4287 reg_name = btf_type_name(reg->btf, reg->btf_id); 4288 4289 /* For ref_ptr case, release function check should ensure we get one 4290 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4291 * normal store of unreferenced kptr, we must ensure var_off is zero. 4292 * Since ref_ptr cannot be accessed directly by BPF insns, check for 4293 * reg->id is not needed here. 4294 */ 4295 if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true)) 4296 return -EACCES; 4297 4298 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 4299 * we also need to take into account the reg->var_off. 4300 * 4301 * We want to support cases like: 4302 * 4303 * struct foo { 4304 * struct bar br; 4305 * struct baz bz; 4306 * }; 4307 * 4308 * struct foo *v; 4309 * v = func(); // PTR_TO_BTF_ID 4310 * val->foo = v; // reg->var_off is zero, btf and btf_id match type 4311 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with 4312 * // first member type of struct after comparison fails 4313 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked 4314 * // to match type 4315 * 4316 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off 4317 * is zero. We must also ensure that btf_struct_ids_match does not walk 4318 * the struct to match type against first member of struct, i.e. reject 4319 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4320 * strict mode to true for type match. 4321 */ 4322 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value, 4323 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4324 kptr_field->type != BPF_KPTR_UNREF, 4325 !type_is_alloc(reg->type))) 4326 goto bad_type; 4327 return 0; 4328 bad_type: 4329 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4330 reg_type_str(env, reg->type), reg_name); 4331 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4332 if (kptr_field->type == BPF_KPTR_UNREF) 4333 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4334 targ_name); 4335 else 4336 verbose(env, "\n"); 4337 return -EINVAL; 4338 } 4339 4340 static bool in_sleepable(struct bpf_verifier_env *env) 4341 { 4342 return env->cur_state->in_sleepable; 4343 } 4344 4345 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 4346 * can dereference RCU protected pointers and result is PTR_TRUSTED. 4347 */ 4348 static bool in_rcu_cs(struct bpf_verifier_env *env) 4349 { 4350 return env->cur_state->active_rcu_locks || 4351 env->cur_state->active_preempt_locks || 4352 env->cur_state->active_locks || 4353 env->cur_state->active_irq_id || 4354 !in_sleepable(env); 4355 } 4356 4357 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 4358 BTF_SET_START(rcu_protected_types) 4359 #ifdef CONFIG_NET 4360 BTF_ID(struct, prog_test_ref_kfunc) 4361 #endif 4362 #ifdef CONFIG_CGROUPS 4363 BTF_ID(struct, cgroup) 4364 #endif 4365 #ifdef CONFIG_BPF_JIT 4366 BTF_ID(struct, bpf_cpumask) 4367 #endif 4368 BTF_ID(struct, task_struct) 4369 #ifdef CONFIG_CRYPTO 4370 BTF_ID(struct, bpf_crypto_ctx) 4371 #endif 4372 BTF_SET_END(rcu_protected_types) 4373 4374 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 4375 { 4376 if (!btf_is_kernel(btf)) 4377 return true; 4378 return btf_id_set_contains(&rcu_protected_types, btf_id); 4379 } 4380 4381 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 4382 { 4383 struct btf_struct_meta *meta; 4384 4385 if (btf_is_kernel(kptr_field->kptr.btf)) 4386 return NULL; 4387 4388 meta = btf_find_struct_meta(kptr_field->kptr.btf, 4389 kptr_field->kptr.btf_id); 4390 4391 return meta ? meta->record : NULL; 4392 } 4393 4394 static bool rcu_safe_kptr(const struct btf_field *field) 4395 { 4396 const struct btf_field_kptr *kptr = &field->kptr; 4397 4398 return field->type == BPF_KPTR_PERCPU || 4399 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 4400 } 4401 4402 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 4403 { 4404 struct btf_record *rec; 4405 u32 ret; 4406 4407 ret = PTR_MAYBE_NULL; 4408 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 4409 ret |= MEM_RCU; 4410 if (kptr_field->type == BPF_KPTR_PERCPU) 4411 ret |= MEM_PERCPU; 4412 else if (!btf_is_kernel(kptr_field->kptr.btf)) 4413 ret |= MEM_ALLOC; 4414 4415 rec = kptr_pointee_btf_record(kptr_field); 4416 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 4417 ret |= NON_OWN_REF; 4418 } else { 4419 ret |= PTR_UNTRUSTED; 4420 } 4421 4422 return ret; 4423 } 4424 4425 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 4426 struct btf_field *field) 4427 { 4428 struct bpf_reg_state *reg; 4429 const struct btf_type *t; 4430 4431 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 4432 mark_reg_known_zero(env, cur_regs(env), regno); 4433 reg = reg_state(env, regno); 4434 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 4435 reg->mem_size = t->size; 4436 reg->id = ++env->id_gen; 4437 4438 return 0; 4439 } 4440 4441 static int check_map_kptr_access(struct bpf_verifier_env *env, 4442 int value_regno, int insn_idx, 4443 struct btf_field *kptr_field) 4444 { 4445 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4446 int class = BPF_CLASS(insn->code); 4447 struct bpf_reg_state *val_reg; 4448 int ret; 4449 4450 /* Things we already checked for in check_map_access and caller: 4451 * - Reject cases where variable offset may touch kptr 4452 * - size of access (must be BPF_DW) 4453 * - tnum_is_const(reg->var_off) 4454 * - kptr_field->offset == off + reg->var_off.value 4455 */ 4456 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4457 if (BPF_MODE(insn->code) != BPF_MEM) { 4458 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4459 return -EACCES; 4460 } 4461 4462 /* We only allow loading referenced kptr, since it will be marked as 4463 * untrusted, similar to unreferenced kptr. 4464 */ 4465 if (class != BPF_LDX && 4466 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 4467 verbose(env, "store to referenced kptr disallowed\n"); 4468 return -EACCES; 4469 } 4470 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 4471 verbose(env, "store to uptr disallowed\n"); 4472 return -EACCES; 4473 } 4474 4475 if (class == BPF_LDX) { 4476 if (kptr_field->type == BPF_UPTR) 4477 return mark_uptr_ld_reg(env, value_regno, kptr_field); 4478 4479 /* We can simply mark the value_regno receiving the pointer 4480 * value from map as PTR_TO_BTF_ID, with the correct type. 4481 */ 4482 ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, 4483 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4484 btf_ld_kptr_type(env, kptr_field)); 4485 if (ret < 0) 4486 return ret; 4487 } else if (class == BPF_STX) { 4488 val_reg = reg_state(env, value_regno); 4489 if (!bpf_register_is_null(val_reg) && 4490 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4491 return -EACCES; 4492 } else if (class == BPF_ST) { 4493 if (insn->imm) { 4494 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4495 kptr_field->offset); 4496 return -EACCES; 4497 } 4498 } else { 4499 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4500 return -EACCES; 4501 } 4502 return 0; 4503 } 4504 4505 /* 4506 * Return the size of the memory region accessible from a pointer to map value. 4507 * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible. 4508 */ 4509 static u32 map_mem_size(const struct bpf_map *map) 4510 { 4511 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) 4512 return map->max_entries * sizeof(long); 4513 4514 return map->value_size; 4515 } 4516 4517 /* check read/write into a map element with possible variable offset */ 4518 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4519 int off, int size, bool zero_size_allowed, 4520 enum bpf_access_src src) 4521 { 4522 struct bpf_map *map = reg->map_ptr; 4523 u32 mem_size = map_mem_size(map); 4524 struct btf_record *rec; 4525 int err, i; 4526 4527 err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed); 4528 if (err) 4529 return err; 4530 4531 if (IS_ERR_OR_NULL(map->record)) 4532 return 0; 4533 rec = map->record; 4534 for (i = 0; i < rec->cnt; i++) { 4535 struct btf_field *field = &rec->fields[i]; 4536 u32 p = field->offset; 4537 4538 /* If any part of a field can be touched by load/store, reject 4539 * this program. To check that [x1, x2) overlaps with [y1, y2), 4540 * it is sufficient to check x1 < y2 && y1 < x2. 4541 */ 4542 if (reg_smin(reg) + off < p + field->size && 4543 p < reg_umax(reg) + off + size) { 4544 switch (field->type) { 4545 case BPF_KPTR_UNREF: 4546 case BPF_KPTR_REF: 4547 case BPF_KPTR_PERCPU: 4548 case BPF_UPTR: 4549 if (src != ACCESS_DIRECT) { 4550 verbose(env, "%s cannot be accessed indirectly by helper\n", 4551 btf_field_type_name(field->type)); 4552 return -EACCES; 4553 } 4554 if (!tnum_is_const(reg->var_off)) { 4555 verbose(env, "%s access cannot have variable offset\n", 4556 btf_field_type_name(field->type)); 4557 return -EACCES; 4558 } 4559 if (p != off + reg->var_off.value) { 4560 verbose(env, "%s access misaligned expected=%u off=%llu\n", 4561 btf_field_type_name(field->type), 4562 p, off + reg->var_off.value); 4563 return -EACCES; 4564 } 4565 if (size != bpf_size_to_bytes(BPF_DW)) { 4566 verbose(env, "%s access size must be BPF_DW\n", 4567 btf_field_type_name(field->type)); 4568 return -EACCES; 4569 } 4570 break; 4571 default: 4572 verbose(env, "%s cannot be accessed directly by load/store\n", 4573 btf_field_type_name(field->type)); 4574 return -EACCES; 4575 } 4576 } 4577 } 4578 return 0; 4579 } 4580 4581 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4582 const struct bpf_func_proto *fn, 4583 enum bpf_access_type t) 4584 { 4585 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4586 4587 switch (prog_type) { 4588 /* Program types only with direct read access go here! */ 4589 case BPF_PROG_TYPE_LWT_IN: 4590 case BPF_PROG_TYPE_LWT_OUT: 4591 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4592 case BPF_PROG_TYPE_SK_REUSEPORT: 4593 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4594 case BPF_PROG_TYPE_CGROUP_SKB: 4595 if (t == BPF_WRITE) 4596 return false; 4597 fallthrough; 4598 4599 /* Program types with direct read + write access go here! */ 4600 case BPF_PROG_TYPE_SCHED_CLS: 4601 case BPF_PROG_TYPE_SCHED_ACT: 4602 case BPF_PROG_TYPE_XDP: 4603 case BPF_PROG_TYPE_LWT_XMIT: 4604 case BPF_PROG_TYPE_SK_SKB: 4605 case BPF_PROG_TYPE_SK_MSG: 4606 if (fn) 4607 return fn->pkt_access; 4608 4609 env->seen_direct_write = true; 4610 return true; 4611 4612 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4613 if (t == BPF_WRITE) 4614 env->seen_direct_write = true; 4615 4616 return true; 4617 4618 default: 4619 return false; 4620 } 4621 } 4622 4623 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 4624 int size, bool zero_size_allowed) 4625 { 4626 int err; 4627 4628 if (reg->range < 0) { 4629 verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno)); 4630 return -EINVAL; 4631 } 4632 4633 err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed); 4634 if (err) 4635 return err; 4636 4637 /* __check_mem_access has made sure "off + size - 1" is within u16. 4638 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff, 4639 * otherwise find_good_pkt_pointers would have refused to set range info 4640 * that __check_mem_access would have rejected this pkt access. 4641 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32. 4642 */ 4643 env->prog->aux->max_pkt_offset = 4644 max_t(u32, env->prog->aux->max_pkt_offset, 4645 off + reg_umax(reg) + size - 1); 4646 4647 return 0; 4648 } 4649 4650 static bool is_var_ctx_off_allowed(struct bpf_prog *prog) 4651 { 4652 return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL; 4653 } 4654 4655 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 4656 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 4657 enum bpf_access_type t, struct bpf_insn_access_aux *info) 4658 { 4659 if (env->ops->is_valid_access && 4660 env->ops->is_valid_access(off, size, t, env->prog, info)) { 4661 /* A non zero info.ctx_field_size indicates that this field is a 4662 * candidate for later verifier transformation to load the whole 4663 * field and then apply a mask when accessed with a narrower 4664 * access than actual ctx access size. A zero info.ctx_field_size 4665 * will only allow for whole field access and rejects any other 4666 * type of narrower access. 4667 */ 4668 if (base_type(info->reg_type) == PTR_TO_BTF_ID) { 4669 if (info->ref_id && 4670 !find_reference_state(env->cur_state, info->ref_id)) { 4671 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n", 4672 off); 4673 return -EACCES; 4674 } 4675 } else { 4676 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size; 4677 } 4678 /* remember the offset of last byte accessed in ctx */ 4679 if (env->prog->aux->max_ctx_offset < off + size) 4680 env->prog->aux->max_ctx_offset = off + size; 4681 return 0; 4682 } 4683 4684 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 4685 return -EACCES; 4686 } 4687 4688 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 4689 int off, int access_size, enum bpf_access_type t, 4690 struct bpf_insn_access_aux *info) 4691 { 4692 /* 4693 * Program types that don't rewrite ctx accesses can safely 4694 * dereference ctx pointers with fixed offsets. 4695 */ 4696 bool var_off_ok = is_var_ctx_off_allowed(env->prog); 4697 bool fixed_off_ok = !env->ops->convert_ctx_access; 4698 int err; 4699 4700 if (var_off_ok) 4701 err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false); 4702 else 4703 err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok); 4704 if (err) 4705 return err; 4706 off += reg_umax(reg); 4707 4708 err = __check_ctx_access(env, insn_idx, off, access_size, t, info); 4709 if (err) 4710 verbose_linfo(env, insn_idx, "; "); 4711 return err; 4712 } 4713 4714 static int check_flow_keys_access(struct bpf_verifier_env *env, 4715 struct bpf_reg_state *reg, argno_t argno, 4716 int off, int size) 4717 { 4718 /* Only a constant offset is allowed here; fold it into off. */ 4719 if (!tnum_is_const(reg->var_off)) { 4720 char tn_buf[48]; 4721 4722 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4723 verbose(env, "%s invalid variable offset to flow keys: off=%d, var_off=%s\n", 4724 reg_arg_name(env, argno), off, tn_buf); 4725 return -EACCES; 4726 } 4727 off += reg->var_off.value; 4728 4729 if (size < 0 || off < 0 || 4730 (u64)off + size > sizeof(struct bpf_flow_keys)) { 4731 verbose(env, "invalid access to flow keys off=%d size=%d\n", 4732 off, size); 4733 return -EACCES; 4734 } 4735 return 0; 4736 } 4737 4738 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 4739 struct bpf_reg_state *reg, argno_t argno, int off, int size, 4740 enum bpf_access_type t) 4741 { 4742 struct bpf_insn_access_aux info = {}; 4743 bool valid; 4744 4745 if (reg_smin(reg) < 0) { 4746 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4747 reg_arg_name(env, argno)); 4748 return -EACCES; 4749 } 4750 4751 switch (reg->type) { 4752 case PTR_TO_SOCK_COMMON: 4753 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 4754 break; 4755 case PTR_TO_SOCKET: 4756 valid = bpf_sock_is_valid_access(off, size, t, &info); 4757 break; 4758 case PTR_TO_TCP_SOCK: 4759 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 4760 break; 4761 case PTR_TO_XDP_SOCK: 4762 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 4763 break; 4764 default: 4765 valid = false; 4766 } 4767 4768 4769 if (valid) { 4770 env->insn_aux_data[insn_idx].ctx_field_size = 4771 info.ctx_field_size; 4772 return 0; 4773 } 4774 4775 verbose(env, "%s invalid %s access off=%d size=%d\n", 4776 reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size); 4777 4778 return -EACCES; 4779 } 4780 4781 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 4782 { 4783 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 4784 } 4785 4786 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 4787 { 4788 const struct bpf_reg_state *reg = reg_state(env, regno); 4789 4790 return reg->type == PTR_TO_CTX; 4791 } 4792 4793 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 4794 { 4795 const struct bpf_reg_state *reg = reg_state(env, regno); 4796 4797 return type_is_sk_pointer(reg->type); 4798 } 4799 4800 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 4801 { 4802 const struct bpf_reg_state *reg = reg_state(env, regno); 4803 4804 return type_is_pkt_pointer(reg->type); 4805 } 4806 4807 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 4808 { 4809 const struct bpf_reg_state *reg = reg_state(env, regno); 4810 4811 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 4812 return reg->type == PTR_TO_FLOW_KEYS; 4813 } 4814 4815 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 4816 { 4817 const struct bpf_reg_state *reg = reg_state(env, regno); 4818 4819 return reg->type == PTR_TO_ARENA; 4820 } 4821 4822 static bool is_load_acq_unsafe(struct bpf_verifier_env *env, int regno, 4823 struct bpf_insn *insn) 4824 { 4825 const struct bpf_reg_state *reg = reg_state(env, regno); 4826 4827 /* 4828 * A BPF_LOAD_ACQ is not rewritten to a BPF_PROBE_MEM load by the 4829 * verifier, unlike a regular BPF_LDX. The JIT would emit a plain load 4830 * with no exception table entry, so a fault (e.g. NULL deref) crashes 4831 * the kernel instead of being handled. 4832 * 4833 * Reject the source pointer types that a BPF_LDX would have had that 4834 * fault protection applied to, i.e. the ones bpf_convert_ctx_accesses() 4835 * turns into BPF_PROBE_MEM: a bare PTR_TO_BTF_ID and any PTR_UNTRUSTED 4836 * pointer (untrusted btf ids, untrusted MEM_ALLOC, rdonly untrusted 4837 * memory). A PTR_TRUSTED pointer is not among them, is not converted, 4838 * and stays allowed. Same for the other flagged PTR_TO_BTF_ID variants 4839 * (MEM_ALLOC, MEM_RCU, ...), hence the exact match on the base type. 4840 */ 4841 return insn->imm == BPF_LOAD_ACQ && 4842 (reg->type == PTR_TO_BTF_ID || 4843 (type_flag(reg->type) & PTR_UNTRUSTED)); 4844 } 4845 4846 /* Return false if @regno contains a pointer whose type isn't supported for 4847 * atomic instruction @insn. 4848 */ 4849 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno, 4850 struct bpf_insn *insn) 4851 { 4852 if (is_ctx_reg(env, regno)) 4853 return false; 4854 if (is_pkt_reg(env, regno)) 4855 return false; 4856 if (is_flow_key_reg(env, regno)) 4857 return false; 4858 if (is_sk_reg(env, regno)) 4859 return false; 4860 if (is_arena_reg(env, regno)) 4861 return bpf_jit_supports_insn(insn, true); 4862 if (is_load_acq_unsafe(env, regno, insn)) 4863 return false; 4864 return true; 4865 } 4866 4867 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 4868 #ifdef CONFIG_NET 4869 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 4870 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 4871 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 4872 #endif 4873 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 4874 }; 4875 4876 static enum bpf_reg_type lookup_reg2btf_ids(u32 ref_id) 4877 { 4878 enum bpf_reg_type type; 4879 4880 for (type = 0; type < __BPF_REG_TYPE_MAX; type++) { 4881 if (reg2btf_ids[type] && *reg2btf_ids[type] == ref_id) 4882 return type; 4883 } 4884 4885 return NOT_INIT; 4886 } 4887 4888 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 4889 { 4890 /* A referenced register is always trusted. */ 4891 if (reg_is_referenced(env, reg)) 4892 return true; 4893 4894 /* Types listed in the reg2btf_ids are always trusted */ 4895 if (reg2btf_ids[base_type(reg->type)] && 4896 !bpf_type_has_unsafe_modifiers(reg->type)) 4897 return true; 4898 4899 /* If a register is not referenced, it is trusted if it has the 4900 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 4901 * other type modifiers may be safe, but we elect to take an opt-in 4902 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 4903 * not. 4904 * 4905 * Eventually, we should make PTR_TRUSTED the single source of truth 4906 * for whether a register is trusted. 4907 */ 4908 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 4909 !bpf_type_has_unsafe_modifiers(reg->type); 4910 } 4911 4912 static bool is_rcu_reg(const struct bpf_reg_state *reg) 4913 { 4914 return reg->type & MEM_RCU; 4915 } 4916 4917 static void clear_trusted_flags(enum bpf_type_flag *flag) 4918 { 4919 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 4920 } 4921 4922 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 4923 const struct bpf_reg_state *reg, 4924 int off, int size, bool strict) 4925 { 4926 struct tnum reg_off; 4927 int ip_align; 4928 4929 /* Byte size accesses are always allowed. */ 4930 if (!strict || size == 1) 4931 return 0; 4932 4933 /* For platforms that do not have a Kconfig enabling 4934 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 4935 * NET_IP_ALIGN is universally set to '2'. And on platforms 4936 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 4937 * to this code only in strict mode where we want to emulate 4938 * the NET_IP_ALIGN==2 checking. Therefore use an 4939 * unconditional IP align value of '2'. 4940 */ 4941 ip_align = 2; 4942 4943 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off)); 4944 if (!tnum_is_aligned(reg_off, size)) { 4945 char tn_buf[48]; 4946 4947 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4948 verbose(env, 4949 "misaligned packet access off %d+%s+%d size %d\n", 4950 ip_align, tn_buf, off, size); 4951 return -EACCES; 4952 } 4953 4954 return 0; 4955 } 4956 4957 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 4958 const struct bpf_reg_state *reg, 4959 const char *pointer_desc, 4960 int off, int size, bool strict) 4961 { 4962 struct tnum reg_off; 4963 4964 /* Byte size accesses are always allowed. */ 4965 if (!strict || size == 1) 4966 return 0; 4967 4968 reg_off = tnum_add(reg->var_off, tnum_const(off)); 4969 if (!tnum_is_aligned(reg_off, size)) { 4970 char tn_buf[48]; 4971 4972 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4973 verbose(env, "misaligned %saccess off %s+%d size %d\n", 4974 pointer_desc, tn_buf, off, size); 4975 return -EACCES; 4976 } 4977 4978 return 0; 4979 } 4980 4981 static int check_ptr_alignment(struct bpf_verifier_env *env, 4982 const struct bpf_reg_state *reg, int off, 4983 int size, bool strict_alignment_once) 4984 { 4985 bool strict = env->strict_alignment || strict_alignment_once; 4986 const char *pointer_desc = ""; 4987 4988 switch (reg->type) { 4989 case PTR_TO_PACKET: 4990 case PTR_TO_PACKET_META: 4991 /* Special case, because of NET_IP_ALIGN. Given metadata sits 4992 * right in front, treat it the very same way. 4993 */ 4994 return check_pkt_ptr_alignment(env, reg, off, size, strict); 4995 case PTR_TO_FLOW_KEYS: 4996 pointer_desc = "flow keys "; 4997 break; 4998 case PTR_TO_MAP_KEY: 4999 pointer_desc = "key "; 5000 break; 5001 case PTR_TO_MAP_VALUE: 5002 pointer_desc = "value "; 5003 if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY) 5004 strict = true; 5005 break; 5006 case PTR_TO_CTX: 5007 pointer_desc = "context "; 5008 break; 5009 case PTR_TO_STACK: 5010 pointer_desc = "stack "; 5011 /* The stack spill tracking logic in check_stack_write_fixed_off() 5012 * and check_stack_read_fixed_off() relies on stack accesses being 5013 * aligned. 5014 */ 5015 strict = true; 5016 break; 5017 case PTR_TO_SOCKET: 5018 pointer_desc = "sock "; 5019 break; 5020 case PTR_TO_SOCK_COMMON: 5021 pointer_desc = "sock_common "; 5022 break; 5023 case PTR_TO_TCP_SOCK: 5024 pointer_desc = "tcp_sock "; 5025 break; 5026 case PTR_TO_XDP_SOCK: 5027 pointer_desc = "xdp_sock "; 5028 break; 5029 case PTR_TO_ARENA: 5030 return 0; 5031 default: 5032 break; 5033 } 5034 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5035 strict); 5036 } 5037 5038 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 5039 { 5040 if (!bpf_jit_supports_private_stack()) 5041 return NO_PRIV_STACK; 5042 5043 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 5044 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 5045 * explicitly. 5046 */ 5047 switch (prog->type) { 5048 case BPF_PROG_TYPE_KPROBE: 5049 case BPF_PROG_TYPE_TRACEPOINT: 5050 case BPF_PROG_TYPE_PERF_EVENT: 5051 case BPF_PROG_TYPE_RAW_TRACEPOINT: 5052 return PRIV_STACK_ADAPTIVE; 5053 case BPF_PROG_TYPE_TRACING: 5054 case BPF_PROG_TYPE_LSM: 5055 case BPF_PROG_TYPE_STRUCT_OPS: 5056 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 5057 return PRIV_STACK_ADAPTIVE; 5058 fallthrough; 5059 default: 5060 break; 5061 } 5062 5063 return NO_PRIV_STACK; 5064 } 5065 5066 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5067 { 5068 if (env->prog->jit_requested) 5069 return round_up(stack_depth, 16); 5070 5071 /* round up to 32-bytes, since this is granularity 5072 * of interpreter stack size 5073 */ 5074 return round_up(max_t(u32, stack_depth, 1), 32); 5075 } 5076 5077 /* temporary state used for call frame depth calculation */ 5078 struct bpf_subprog_call_depth_info { 5079 int ret_insn; /* caller instruction where we return to. */ 5080 int caller; /* caller subprogram idx */ 5081 int frame; /* # of consecutive static call stack frames on top of stack */ 5082 }; 5083 5084 /* starting from main bpf function walk all instructions of the function 5085 * and recursively walk all callees that given function can call. 5086 * Ignore jump and exit insns. 5087 */ 5088 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 5089 struct bpf_subprog_call_depth_info *dinfo, 5090 bool priv_stack_supported) 5091 { 5092 struct bpf_subprog_info *subprog = env->subprog_info; 5093 struct bpf_insn *insn = env->prog->insnsi; 5094 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 5095 bool tail_call_reachable = false; 5096 int total; 5097 int tmp; 5098 5099 /* no caller idx */ 5100 dinfo[idx].caller = -1; 5101 5102 i = subprog[idx].start; 5103 if (!priv_stack_supported) 5104 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5105 process_func: 5106 /* protect against potential stack overflow that might happen when 5107 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5108 * depth for such case down to 256 so that the worst case scenario 5109 * would result in 8k stack size (32 which is tailcall limit * 256 = 5110 * 8k). 5111 * 5112 * To get the idea what might happen, see an example: 5113 * func1 -> sub rsp, 128 5114 * subfunc1 -> sub rsp, 256 5115 * tailcall1 -> add rsp, 256 5116 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5117 * subfunc2 -> sub rsp, 64 5118 * subfunc22 -> sub rsp, 128 5119 * tailcall2 -> add rsp, 128 5120 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5121 * 5122 * tailcall will unwind the current stack frame but it will not get rid 5123 * of caller's stack as shown on the example above. 5124 */ 5125 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5126 verbose(env, 5127 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5128 depth); 5129 return -EACCES; 5130 } 5131 5132 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 5133 if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) { 5134 /* x86-64 uses R9 for both private stack frame pointer and arg6. */ 5135 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5136 } else if (priv_stack_supported) { 5137 /* Request private stack support only if the subprog stack 5138 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 5139 * avoid jit penalty if the stack usage is small. 5140 */ 5141 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 5142 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 5143 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 5144 } 5145 5146 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5147 if (subprog_depth > env->max_stack_depth) 5148 env->max_stack_depth = subprog_depth; 5149 if (subprog_depth > MAX_BPF_STACK) { 5150 verbose(env, "stack size of subprog %d is %d. Too large\n", 5151 idx, subprog_depth); 5152 return -EACCES; 5153 } 5154 } else { 5155 depth += subprog_depth; 5156 if (depth > env->max_stack_depth) 5157 env->max_stack_depth = depth; 5158 if (depth > MAX_BPF_STACK) { 5159 total = 0; 5160 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) 5161 total++; 5162 5163 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5164 total, depth); 5165 return -EACCES; 5166 } 5167 } 5168 continue_func: 5169 subprog_end = subprog[idx + 1].start; 5170 for (; i < subprog_end; i++) { 5171 int next_insn, sidx; 5172 5173 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5174 bool err = false; 5175 5176 if (!bpf_is_throw_kfunc(insn + i)) 5177 continue; 5178 for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) { 5179 if (subprog[tmp].is_cb) { 5180 err = true; 5181 break; 5182 } 5183 } 5184 if (!err) 5185 continue; 5186 verbose(env, 5187 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5188 i, idx); 5189 return -EINVAL; 5190 } 5191 5192 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5193 continue; 5194 /* remember insn and function to return to */ 5195 5196 /* find the callee */ 5197 next_insn = i + insn[i].imm + 1; 5198 sidx = bpf_find_subprog(env, next_insn); 5199 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn)) 5200 return -EFAULT; 5201 if (subprog[sidx].is_async_cb) { 5202 /* async callbacks don't increase bpf prog stack size unless called directly */ 5203 if (!bpf_pseudo_call(insn + i)) 5204 continue; 5205 if (subprog[sidx].is_exception_cb) { 5206 verbose(env, "insn %d cannot call exception cb directly", i); 5207 return -EINVAL; 5208 } 5209 } 5210 5211 /* store caller info for after we return from callee */ 5212 dinfo[idx].frame = frame; 5213 dinfo[idx].ret_insn = i + 1; 5214 5215 /* push caller idx into callee's dinfo */ 5216 dinfo[sidx].caller = idx; 5217 5218 i = next_insn; 5219 5220 idx = sidx; 5221 if (!priv_stack_supported) 5222 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5223 5224 /* sync tail_call_reachable with callee state on entry */ 5225 tail_call_reachable = subprog[idx].has_tail_call; 5226 5227 frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1; 5228 if (frame >= MAX_CALL_FRAMES) { 5229 verbose(env, "the call stack of %d frames is too deep !\n", 5230 frame); 5231 return -E2BIG; 5232 } 5233 goto process_func; 5234 } 5235 /* if tail call got detected across bpf2bpf calls then mark each of the 5236 * currently present subprog frames as tail call reachable subprogs; 5237 * this info will be utilized by JIT so that we will be preserving the 5238 * tail call counter throughout bpf2bpf calls combined with tailcalls 5239 */ 5240 if (tail_call_reachable) { 5241 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) { 5242 if (subprog[tmp].is_cb) { 5243 verbose(env, "cannot tail call within callback\n"); 5244 return -EINVAL; 5245 } 5246 if (subprog[tmp].stack_arg_cnt) { 5247 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5248 return -EINVAL; 5249 } 5250 subprog[tmp].tail_call_reachable = true; 5251 } 5252 } else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) { 5253 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5254 return -EINVAL; 5255 } 5256 5257 if (subprog[0].tail_call_reachable) 5258 env->prog->aux->tail_call_reachable = true; 5259 5260 /* end of for() loop means the last insn of the 'subprog' 5261 * was reached. Doesn't matter whether it was JA or EXIT 5262 */ 5263 if (frame == 0 && dinfo[idx].caller < 0) 5264 return 0; 5265 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 5266 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 5267 5268 /* pop caller idx from callee */ 5269 idx = dinfo[idx].caller; 5270 5271 /* retrieve caller state from its frame */ 5272 frame = dinfo[idx].frame; 5273 i = dinfo[idx].ret_insn; 5274 5275 /* reset tail_call_reachable to the parent's actual state */ 5276 tail_call_reachable = subprog[idx].tail_call_reachable; 5277 5278 goto continue_func; 5279 } 5280 5281 static int check_max_stack_depth(struct bpf_verifier_env *env) 5282 { 5283 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 5284 struct bpf_subprog_call_depth_info *dinfo; 5285 struct bpf_subprog_info *si = env->subprog_info; 5286 bool priv_stack_supported; 5287 int ret; 5288 5289 dinfo = kvcalloc(env->subprog_cnt, sizeof(*dinfo), GFP_KERNEL_ACCOUNT); 5290 if (!dinfo) 5291 return -ENOMEM; 5292 5293 for (int i = 0; i < env->subprog_cnt; i++) { 5294 if (si[i].has_tail_call) { 5295 priv_stack_mode = NO_PRIV_STACK; 5296 break; 5297 } 5298 } 5299 5300 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 5301 priv_stack_mode = bpf_enable_priv_stack(env->prog); 5302 5303 /* All async_cb subprogs use normal kernel stack. If a particular 5304 * subprog appears in both main prog and async_cb subtree, that 5305 * subprog will use normal kernel stack to avoid potential nesting. 5306 * The reverse subprog traversal ensures when main prog subtree is 5307 * checked, the subprogs appearing in async_cb subtrees are already 5308 * marked as using normal kernel stack, so stack size checking can 5309 * be done properly. 5310 */ 5311 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 5312 if (!i || si[i].is_async_cb) { 5313 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 5314 ret = check_max_stack_depth_subprog(env, i, dinfo, 5315 priv_stack_supported); 5316 if (ret < 0) { 5317 kvfree(dinfo); 5318 return ret; 5319 } 5320 } 5321 } 5322 5323 for (int i = 0; i < env->subprog_cnt; i++) { 5324 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5325 env->prog->aux->jits_use_priv_stack = true; 5326 break; 5327 } 5328 } 5329 5330 kvfree(dinfo); 5331 5332 return 0; 5333 } 5334 5335 static int __check_buffer_access(struct bpf_verifier_env *env, 5336 const char *buf_info, 5337 const struct bpf_reg_state *reg, 5338 argno_t argno, int off, int size, 5339 u32 *access_end) 5340 { 5341 s64 start; 5342 5343 if (!tnum_is_const(reg->var_off)) { 5344 char tn_buf[48]; 5345 5346 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5347 verbose(env, 5348 "%s invalid variable buffer offset: off=%d, var_off=%s\n", 5349 reg_arg_name(env, argno), off, tn_buf); 5350 return -EACCES; 5351 } 5352 5353 start = (s64)reg->var_off.value + off; 5354 if (start < 0) { 5355 verbose(env, 5356 "%s invalid negative %s buffer offset: off=%d, var_off=%lld\n", 5357 reg_arg_name(env, argno), buf_info, off, (s64)reg->var_off.value); 5358 return -EACCES; 5359 } 5360 5361 *access_end = start + size; 5362 return 0; 5363 } 5364 5365 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5366 const struct bpf_reg_state *reg, 5367 argno_t argno, int off, int size) 5368 { 5369 u32 access_end; 5370 int err; 5371 5372 err = __check_buffer_access(env, "tracepoint", reg, argno, off, size, &access_end); 5373 if (err) 5374 return err; 5375 5376 env->prog->aux->max_tp_access = max(access_end, env->prog->aux->max_tp_access); 5377 5378 return 0; 5379 } 5380 5381 static int check_buffer_access(struct bpf_verifier_env *env, 5382 const struct bpf_reg_state *reg, 5383 argno_t argno, int off, int size, 5384 bool zero_size_allowed, 5385 u32 *max_access) 5386 { 5387 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5388 u32 access_end; 5389 int err; 5390 5391 err = __check_buffer_access(env, buf_info, reg, argno, off, size, &access_end); 5392 if (err) 5393 return err; 5394 5395 *max_access = max(access_end, *max_access); 5396 5397 return 0; 5398 } 5399 5400 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5401 static void zext_32_to_64(struct bpf_reg_state *reg) 5402 { 5403 reg->var_off = tnum_subreg(reg->var_off); 5404 reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg)); 5405 } 5406 5407 /* truncate register to smaller size (in bytes) 5408 * must be called with size < BPF_REG_SIZE 5409 */ 5410 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5411 { 5412 u64 mask; 5413 5414 /* clear high bits in bit representation */ 5415 reg->var_off = tnum_cast(reg->var_off, size); 5416 5417 /* fix arithmetic bounds */ 5418 mask = ((u64)1 << (size * 8)) - 1; 5419 if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask)) 5420 reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask); 5421 else 5422 reg_set_urange64(reg, 0, mask); 5423 5424 /* If size is smaller than 32bit register the 32bit register 5425 * values are also truncated so we push 64-bit bounds into 5426 * 32-bit bounds. Above were truncated < 32-bits already. 5427 */ 5428 if (size < 4) 5429 __mark_reg32_unbounded(reg); 5430 5431 reg_bounds_sync(reg); 5432 } 5433 5434 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 5435 { 5436 if (size == 1) { 5437 reg_set_srange64(reg, S8_MIN, S8_MAX); 5438 reg_set_srange32(reg, S8_MIN, S8_MAX); 5439 } else if (size == 2) { 5440 reg_set_srange64(reg, S16_MIN, S16_MAX); 5441 reg_set_srange32(reg, S16_MIN, S16_MAX); 5442 } else { 5443 /* size == 4 */ 5444 reg_set_srange64(reg, S32_MIN, S32_MAX); 5445 reg_set_srange32(reg, S32_MIN, S32_MAX); 5446 } 5447 reg->var_off = tnum_unknown; 5448 } 5449 5450 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 5451 { 5452 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 5453 u64 top_smax_value, top_smin_value; 5454 u64 num_bits = size * 8; 5455 5456 if (tnum_is_const(reg->var_off)) { 5457 u64_cval = reg->var_off.value; 5458 if (size == 1) 5459 reg->var_off = tnum_const((s8)u64_cval); 5460 else if (size == 2) 5461 reg->var_off = tnum_const((s16)u64_cval); 5462 else 5463 /* size == 4 */ 5464 reg->var_off = tnum_const((s32)u64_cval); 5465 5466 u64_cval = reg->var_off.value; 5467 reg->r64 = cnum64_from_urange(u64_cval, u64_cval); 5468 reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval); 5469 return; 5470 } 5471 5472 top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits; 5473 top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits; 5474 5475 if (top_smax_value != top_smin_value) 5476 goto out; 5477 5478 /* find the s64_min and s64_min after sign extension */ 5479 if (size == 1) { 5480 init_s64_max = (s8)reg_smax(reg); 5481 init_s64_min = (s8)reg_smin(reg); 5482 } else if (size == 2) { 5483 init_s64_max = (s16)reg_smax(reg); 5484 init_s64_min = (s16)reg_smin(reg); 5485 } else { 5486 init_s64_max = (s32)reg_smax(reg); 5487 init_s64_min = (s32)reg_smin(reg); 5488 } 5489 5490 s64_max = max(init_s64_max, init_s64_min); 5491 s64_min = min(init_s64_max, init_s64_min); 5492 5493 /* both of s64_max/s64_min positive or negative */ 5494 if ((s64_max >= 0) == (s64_min >= 0)) { 5495 reg_set_srange64(reg, s64_min, s64_max); 5496 reg_set_srange32(reg, s64_min, s64_max); 5497 reg->var_off = tnum_range(s64_min, s64_max); 5498 return; 5499 } 5500 5501 out: 5502 set_sext64_default_val(reg, size); 5503 } 5504 5505 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 5506 { 5507 if (size == 1) 5508 reg_set_srange32(reg, S8_MIN, S8_MAX); 5509 else 5510 /* size == 2 */ 5511 reg_set_srange32(reg, S16_MIN, S16_MAX); 5512 reg->var_off = tnum_subreg(tnum_unknown); 5513 } 5514 5515 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 5516 { 5517 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 5518 u32 top_smax_value, top_smin_value; 5519 u32 num_bits = size * 8; 5520 5521 if (tnum_is_const(reg->var_off)) { 5522 u32_val = reg->var_off.value; 5523 if (size == 1) 5524 reg->var_off = tnum_const((s8)u32_val); 5525 else 5526 reg->var_off = tnum_const((s16)u32_val); 5527 5528 u32_val = reg->var_off.value; 5529 reg_set_srange32(reg, u32_val, u32_val); 5530 return; 5531 } 5532 5533 top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits; 5534 top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits; 5535 5536 if (top_smax_value != top_smin_value) 5537 goto out; 5538 5539 /* find the s32_min and s32_min after sign extension */ 5540 if (size == 1) { 5541 init_s32_max = (s8)reg_s32_max(reg); 5542 init_s32_min = (s8)reg_s32_min(reg); 5543 } else { 5544 /* size == 2 */ 5545 init_s32_max = (s16)reg_s32_max(reg); 5546 init_s32_min = (s16)reg_s32_min(reg); 5547 } 5548 s32_max = max(init_s32_max, init_s32_min); 5549 s32_min = min(init_s32_max, init_s32_min); 5550 5551 if ((s32_min >= 0) == (s32_max >= 0)) { 5552 reg_set_srange32(reg, s32_min, s32_max); 5553 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 5554 return; 5555 } 5556 5557 out: 5558 set_sext32_default_val(reg, size); 5559 } 5560 5561 bool bpf_map_is_rdonly(const struct bpf_map *map) 5562 { 5563 /* A map is considered read-only if the following condition are true: 5564 * 5565 * 1) BPF program side cannot change any of the map content. The 5566 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 5567 * and was set at map creation time. 5568 * 2) The map value(s) have been initialized from user space by a 5569 * loader and then "frozen", such that no new map update/delete 5570 * operations from syscall side are possible for the rest of 5571 * the map's lifetime from that point onwards. 5572 * 3) Any parallel/pending map update/delete operations from syscall 5573 * side have been completed. Only after that point, it's safe to 5574 * assume that map value(s) are immutable. 5575 */ 5576 return (map->map_flags & BPF_F_RDONLY_PROG) && 5577 READ_ONCE(map->frozen) && 5578 !bpf_map_write_active(map); 5579 } 5580 5581 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 5582 bool is_ldsx) 5583 { 5584 void *ptr; 5585 u64 addr; 5586 int err; 5587 5588 err = map->ops->map_direct_value_addr(map, &addr, off); 5589 if (err) 5590 return err; 5591 ptr = (void *)(long)addr + off; 5592 5593 switch (size) { 5594 case sizeof(u8): 5595 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 5596 break; 5597 case sizeof(u16): 5598 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 5599 break; 5600 case sizeof(u32): 5601 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 5602 break; 5603 case sizeof(u64): 5604 *val = *(u64 *)ptr; 5605 break; 5606 default: 5607 return -EINVAL; 5608 } 5609 return 0; 5610 } 5611 5612 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 5613 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 5614 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 5615 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 5616 5617 /* 5618 * Allow list few fields as RCU trusted or full trusted. 5619 * This logic doesn't allow mix tagging and will be removed once GCC supports 5620 * btf_type_tag. 5621 */ 5622 5623 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 5624 BTF_TYPE_SAFE_RCU(struct task_struct) { 5625 const cpumask_t *cpus_ptr; 5626 struct css_set __rcu *cgroups; 5627 struct task_struct __rcu *real_parent; 5628 struct task_struct *group_leader; 5629 }; 5630 5631 BTF_TYPE_SAFE_RCU(struct cgroup) { 5632 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 5633 struct kernfs_node *kn; 5634 }; 5635 5636 BTF_TYPE_SAFE_RCU(struct css_set) { 5637 struct cgroup *dfl_cgrp; 5638 }; 5639 5640 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) { 5641 struct cgroup *cgroup; 5642 }; 5643 5644 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 5645 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 5646 struct file __rcu *exe_file; 5647 #ifdef CONFIG_MEMCG 5648 struct task_struct __rcu *owner; 5649 #endif 5650 }; 5651 5652 /* skb->sk, req->sk are not RCU protected, but we mark them as such 5653 * because bpf prog accessible sockets are SOCK_RCU_FREE. 5654 */ 5655 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 5656 struct sock *sk; 5657 }; 5658 5659 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 5660 struct sock *sk; 5661 }; 5662 5663 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 5664 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 5665 struct seq_file *seq; 5666 }; 5667 5668 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 5669 struct bpf_iter_meta *meta; 5670 struct task_struct *task; 5671 }; 5672 5673 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 5674 struct file *file; 5675 }; 5676 5677 BTF_TYPE_SAFE_TRUSTED(struct file) { 5678 struct inode *f_inode; 5679 }; 5680 5681 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) { 5682 struct inode *d_inode; 5683 }; 5684 5685 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 5686 struct sock *sk; 5687 }; 5688 5689 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) { 5690 struct mm_struct *vm_mm; 5691 struct file *vm_file; 5692 }; 5693 5694 static bool type_is_rcu(struct bpf_verifier_env *env, 5695 struct bpf_reg_state *reg, 5696 const char *field_name, u32 btf_id) 5697 { 5698 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 5699 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 5700 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 5701 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)); 5702 5703 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 5704 } 5705 5706 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 5707 struct bpf_reg_state *reg, 5708 const char *field_name, u32 btf_id) 5709 { 5710 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 5711 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 5712 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 5713 5714 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 5715 } 5716 5717 static bool type_is_trusted(struct bpf_verifier_env *env, 5718 struct bpf_reg_state *reg, 5719 const char *field_name, u32 btf_id) 5720 { 5721 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 5722 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 5723 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 5724 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 5725 5726 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 5727 } 5728 5729 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 5730 struct bpf_reg_state *reg, 5731 const char *field_name, u32 btf_id) 5732 { 5733 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 5734 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)); 5735 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct)); 5736 5737 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 5738 "__safe_trusted_or_null"); 5739 } 5740 5741 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 5742 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5743 argno_t argno, int off, int size, 5744 enum bpf_access_type atype, 5745 int value_regno) 5746 { 5747 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 5748 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 5749 const char *field_name = NULL; 5750 enum bpf_type_flag flag = 0; 5751 u32 btf_id = 0; 5752 int ret; 5753 5754 if (!env->allow_ptr_leaks) { 5755 verbose(env, 5756 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5757 tname); 5758 return -EPERM; 5759 } 5760 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 5761 verbose(env, 5762 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 5763 tname); 5764 return -EINVAL; 5765 } 5766 5767 if (!tnum_is_const(reg->var_off)) { 5768 char tn_buf[48]; 5769 5770 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5771 verbose(env, 5772 "%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 5773 reg_arg_name(env, argno), tname, off, tn_buf); 5774 return -EACCES; 5775 } 5776 5777 off += reg->var_off.value; 5778 5779 if (off < 0) { 5780 verbose(env, 5781 "%s is ptr_%s invalid negative access: off=%d\n", 5782 reg_arg_name(env, argno), tname, off); 5783 return -EACCES; 5784 } 5785 5786 if (reg->type & MEM_USER) { 5787 verbose(env, 5788 "%s is ptr_%s access user memory: off=%d\n", 5789 reg_arg_name(env, argno), tname, off); 5790 return -EACCES; 5791 } 5792 5793 if (reg->type & MEM_PERCPU) { 5794 verbose(env, 5795 "%s is ptr_%s access percpu memory: off=%d\n", 5796 reg_arg_name(env, argno), tname, off); 5797 return -EACCES; 5798 } 5799 5800 if (atype != BPF_READ && (type_flag(reg->type) & PTR_UNTRUSTED)) { 5801 verbose(env, "only read is supported\n"); 5802 return -EACCES; 5803 } 5804 5805 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 5806 if (!btf_is_kernel(reg->btf)) { 5807 verifier_bug(env, "reg->btf must be kernel btf"); 5808 return -EFAULT; 5809 } 5810 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 5811 if (ret < 0) 5812 verbose(env, 5813 "%s cannot write into ptr_%s at off=%d size=%d\n", 5814 reg_arg_name(env, argno), tname, off, size); 5815 } else { 5816 /* Writes are permitted with default btf_struct_access for 5817 * program allocated objects (which always have id > 0). 5818 */ 5819 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 5820 verbose(env, "only read is supported\n"); 5821 return -EACCES; 5822 } 5823 5824 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 5825 !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) { 5826 verifier_bug(env, "allocated object must have a referenced id"); 5827 return -EFAULT; 5828 } 5829 5830 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 5831 } 5832 5833 if (ret < 0) 5834 return ret; 5835 5836 if (ret != PTR_TO_BTF_ID) { 5837 /* just mark; */ 5838 5839 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 5840 /* If this is an untrusted pointer, all pointers formed by walking it 5841 * also inherit the untrusted flag. 5842 */ 5843 flag = PTR_UNTRUSTED; 5844 5845 } else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) { 5846 /* By default any pointer obtained from walking a trusted pointer is no 5847 * longer trusted, unless the field being accessed has explicitly been 5848 * marked as inheriting its parent's state of trust (either full or RCU). 5849 * For example: 5850 * 'cgroups' pointer is untrusted if task->cgroups dereference 5851 * happened in a sleepable program outside of bpf_rcu_read_lock() 5852 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 5853 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 5854 * 5855 * A regular RCU-protected pointer with __rcu tag can also be deemed 5856 * trusted if we are in an RCU CS. Such pointer can be NULL. 5857 */ 5858 if (type_is_trusted(env, reg, field_name, btf_id)) { 5859 flag |= PTR_TRUSTED; 5860 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 5861 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 5862 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 5863 if (type_is_rcu(env, reg, field_name, btf_id)) { 5864 /* ignore __rcu tag and mark it MEM_RCU */ 5865 flag |= MEM_RCU; 5866 } else if (flag & MEM_RCU || 5867 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 5868 /* __rcu tagged pointers can be NULL */ 5869 flag |= MEM_RCU | PTR_MAYBE_NULL; 5870 5871 /* We always trust them */ 5872 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 5873 flag & PTR_UNTRUSTED) 5874 flag &= ~PTR_UNTRUSTED; 5875 } else if (flag & (MEM_PERCPU | MEM_USER)) { 5876 /* keep as-is */ 5877 } else { 5878 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 5879 clear_trusted_flags(&flag); 5880 } 5881 } else { 5882 /* 5883 * If not in RCU CS or MEM_RCU pointer can be NULL then 5884 * aggressively mark as untrusted otherwise such 5885 * pointers will be plain PTR_TO_BTF_ID without flags 5886 * and will be allowed to be passed into helpers for 5887 * compat reasons. 5888 */ 5889 flag = PTR_UNTRUSTED; 5890 } 5891 } else { 5892 /* Old compat. Deprecated */ 5893 clear_trusted_flags(&flag); 5894 } 5895 5896 if (atype == BPF_READ && value_regno >= 0) { 5897 ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5898 if (ret < 0) 5899 return ret; 5900 } 5901 5902 return 0; 5903 } 5904 5905 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5906 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5907 argno_t argno, int off, int size, 5908 enum bpf_access_type atype, 5909 int value_regno) 5910 { 5911 struct bpf_map *map = reg->map_ptr; 5912 struct bpf_reg_state map_reg; 5913 enum bpf_type_flag flag = 0; 5914 const struct btf_type *t; 5915 const char *tname; 5916 u32 btf_id; 5917 int ret; 5918 5919 if (!btf_vmlinux) { 5920 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5921 return -ENOTSUPP; 5922 } 5923 5924 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5925 verbose(env, "map_ptr access not supported for map type %d\n", 5926 map->map_type); 5927 return -ENOTSUPP; 5928 } 5929 5930 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5931 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5932 5933 if (!env->allow_ptr_leaks) { 5934 verbose(env, 5935 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5936 tname); 5937 return -EPERM; 5938 } 5939 5940 if (off < 0) { 5941 verbose(env, "%s is %s invalid negative access: off=%d\n", 5942 reg_arg_name(env, argno), tname, off); 5943 return -EACCES; 5944 } 5945 5946 if (atype != BPF_READ) { 5947 verbose(env, "only read from %s is supported\n", tname); 5948 return -EACCES; 5949 } 5950 5951 /* Simulate access to a PTR_TO_BTF_ID */ 5952 memset(&map_reg, 0, sizeof(map_reg)); 5953 ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, 5954 btf_vmlinux, *map->ops->map_btf_id, 0); 5955 if (ret < 0) 5956 return ret; 5957 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 5958 if (ret < 0) 5959 return ret; 5960 5961 if (value_regno >= 0) { 5962 ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 5963 if (ret < 0) 5964 return ret; 5965 } 5966 5967 return 0; 5968 } 5969 5970 /* Check that the stack access at the given offset is within bounds. The 5971 * maximum valid offset is -1. 5972 * 5973 * The minimum valid offset is -MAX_BPF_STACK for writes, and 5974 * -state->allocated_stack for reads. 5975 */ 5976 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 5977 s64 off, 5978 struct bpf_func_state *state, 5979 enum bpf_access_type t) 5980 { 5981 int min_valid_off; 5982 5983 if (t == BPF_WRITE || env->allow_uninit_stack) 5984 min_valid_off = -MAX_BPF_STACK; 5985 else 5986 min_valid_off = -state->allocated_stack; 5987 5988 if (off < min_valid_off || off > -1) 5989 return -EACCES; 5990 return 0; 5991 } 5992 5993 /* Check that the stack access at 'regno + off' falls within the maximum stack 5994 * bounds. 5995 * 5996 * 'off' includes `regno->offset`, but not its dynamic part (if any). 5997 */ 5998 static int check_stack_access_within_bounds( 5999 struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6000 argno_t argno, int off, int access_size, 6001 enum bpf_access_type type) 6002 { 6003 struct bpf_func_state *state = bpf_func(env, reg); 6004 s64 min_off, max_off; 6005 int err; 6006 char *err_extra; 6007 6008 if (type == BPF_READ) 6009 err_extra = " read from"; 6010 else 6011 err_extra = " write to"; 6012 6013 if (tnum_is_const(reg->var_off)) { 6014 min_off = (s64)reg->var_off.value + off; 6015 max_off = min_off + access_size; 6016 } else { 6017 if (reg_smax(reg) >= BPF_MAX_VAR_OFF || 6018 reg_smin(reg) <= -BPF_MAX_VAR_OFF) { 6019 verbose(env, "invalid unbounded variable-offset%s stack %s\n", 6020 err_extra, reg_arg_name(env, argno)); 6021 return -EACCES; 6022 } 6023 min_off = reg_smin(reg) + off; 6024 max_off = reg_smax(reg) + off + access_size; 6025 } 6026 6027 err = check_stack_slot_within_bounds(env, min_off, state, type); 6028 if (!err && max_off > 0) 6029 err = -EINVAL; /* out of stack access into non-negative offsets */ 6030 if (!err && access_size < 0) 6031 /* access_size should not be negative (or overflow an int); others checks 6032 * along the way should have prevented such an access. 6033 */ 6034 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6035 6036 if (err) { 6037 if (tnum_is_const(reg->var_off)) { 6038 verbose(env, "invalid%s stack %s off=%lld size=%d\n", 6039 err_extra, reg_arg_name(env, argno), min_off, access_size); 6040 } else { 6041 char tn_buf[48]; 6042 6043 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6044 verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n", 6045 err_extra, reg_arg_name(env, argno), tn_buf, off, access_size); 6046 } 6047 return err; 6048 } 6049 6050 /* Note that there is no stack access with offset zero, so the needed stack 6051 * size is -min_off, not -min_off+1. 6052 */ 6053 return grow_stack_state(env, state, -min_off /* size */); 6054 } 6055 6056 static bool get_func_retval_range(struct bpf_prog *prog, 6057 struct bpf_retval_range *range) 6058 { 6059 if (prog->type == BPF_PROG_TYPE_LSM && 6060 prog->expected_attach_type == BPF_LSM_MAC && 6061 !bpf_lsm_get_retval_range(prog, range)) { 6062 return true; 6063 } 6064 return false; 6065 } 6066 6067 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val) 6068 { 6069 struct bpf_reg_state fake_reg; 6070 6071 if (!val) 6072 return; 6073 6074 fake_reg.type = SCALAR_VALUE; 6075 __mark_reg_known(&fake_reg, val); 6076 6077 scalar32_min_max_add(dst_reg, &fake_reg); 6078 scalar_min_max_add(dst_reg, &fake_reg); 6079 dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off); 6080 6081 reg_bounds_sync(dst_reg); 6082 } 6083 6084 /* check whether memory at (regno + off) is accessible for t = (read | write) 6085 * if t==write, value_regno is a register which value is stored into memory 6086 * if t==read, value_regno is a register which will receive the value from memory 6087 * if t==write && value_regno==-1, some unknown value is stored into memory 6088 * if t==read && value_regno==-1, don't care what we read from memory 6089 */ 6090 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 6091 int off, int bpf_size, enum bpf_access_type t, 6092 int value_regno, bool strict_alignment_once, bool is_ldsx) 6093 { 6094 struct bpf_reg_state *regs = cur_regs(env); 6095 int size, err = 0; 6096 6097 size = bpf_size_to_bytes(bpf_size); 6098 if (size < 0) 6099 return size; 6100 6101 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6102 if (err) 6103 return err; 6104 6105 if (reg->type == PTR_TO_MAP_KEY) { 6106 if (t == BPF_WRITE) { 6107 verbose(env, "write to change key %s not allowed\n", 6108 reg_arg_name(env, argno)); 6109 return -EACCES; 6110 } 6111 6112 err = check_mem_region_access(env, reg, argno, off, size, 6113 reg->map_ptr->key_size, false); 6114 if (err) 6115 return err; 6116 if (value_regno >= 0) 6117 mark_reg_unknown(env, regs, value_regno); 6118 } else if (reg->type == PTR_TO_MAP_VALUE) { 6119 struct btf_field *kptr_field = NULL; 6120 6121 if (t == BPF_WRITE && value_regno >= 0 && 6122 is_pointer_value(env, value_regno)) { 6123 verbose(env, "R%d leaks addr into map\n", value_regno); 6124 return -EACCES; 6125 } 6126 err = check_map_access_type(env, reg, off, size, t); 6127 if (err) 6128 return err; 6129 err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT); 6130 if (err) 6131 return err; 6132 if (tnum_is_const(reg->var_off)) 6133 kptr_field = btf_record_find(reg->map_ptr->record, 6134 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 6135 if (kptr_field) { 6136 err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field); 6137 } else if (t == BPF_READ && value_regno >= 0) { 6138 struct bpf_map *map = reg->map_ptr; 6139 6140 /* 6141 * If map is read-only, track its contents as scalars, 6142 * unless it is an insn array (see the special case below) 6143 */ 6144 if (tnum_is_const(reg->var_off) && 6145 bpf_map_is_rdonly(map) && 6146 map->ops->map_direct_value_addr && 6147 map->map_type != BPF_MAP_TYPE_INSN_ARRAY) { 6148 int map_off = off + reg->var_off.value; 6149 u64 val = 0; 6150 6151 err = bpf_map_direct_read(map, map_off, size, 6152 &val, is_ldsx); 6153 if (err) 6154 return err; 6155 6156 regs[value_regno].type = SCALAR_VALUE; 6157 __mark_reg_known(®s[value_regno], val); 6158 } else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 6159 if (bpf_size != BPF_DW) { 6160 verbose(env, "Invalid read of %d bytes from insn_array\n", 6161 size); 6162 return -EACCES; 6163 } 6164 regs[value_regno] = *reg; 6165 add_scalar_to_reg(®s[value_regno], off); 6166 regs[value_regno].type = PTR_TO_INSN; 6167 } else { 6168 mark_reg_unknown(env, regs, value_regno); 6169 } 6170 } 6171 } else if (base_type(reg->type) == PTR_TO_MEM) { 6172 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6173 bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED); 6174 6175 if (type_may_be_null(reg->type)) { 6176 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6177 reg_type_str(env, reg->type)); 6178 return -EACCES; 6179 } 6180 6181 if (t == BPF_WRITE && rdonly_mem) { 6182 verbose(env, "%s cannot write into %s\n", 6183 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6184 return -EACCES; 6185 } 6186 6187 if (t == BPF_WRITE && value_regno >= 0 && 6188 is_pointer_value(env, value_regno)) { 6189 verbose(env, "R%d leaks addr into mem\n", value_regno); 6190 return -EACCES; 6191 } 6192 6193 /* 6194 * Accesses to untrusted PTR_TO_MEM are done through probe 6195 * instructions, hence no need to check bounds in that case. 6196 */ 6197 if (!rdonly_untrusted) 6198 err = check_mem_region_access(env, reg, argno, off, size, 6199 reg->mem_size, false); 6200 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6201 mark_reg_unknown(env, regs, value_regno); 6202 } else if (reg->type == PTR_TO_CTX) { 6203 struct bpf_insn_access_aux info = { 6204 .reg_type = SCALAR_VALUE, 6205 .is_ldsx = is_ldsx, 6206 .log = &env->log, 6207 }; 6208 struct bpf_retval_range range; 6209 6210 if (t == BPF_WRITE && value_regno >= 0 && 6211 is_pointer_value(env, value_regno)) { 6212 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6213 return -EACCES; 6214 } 6215 6216 err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info); 6217 if (!err && t == BPF_READ && value_regno >= 0) { 6218 /* ctx access returns either a scalar, or a 6219 * PTR_TO_PACKET[_META,_END]. In the latter 6220 * case, we know the offset is zero. 6221 */ 6222 if (info.reg_type == SCALAR_VALUE) { 6223 if (info.is_retval && get_func_retval_range(env->prog, &range)) { 6224 mark_reg_unknown(env, regs, value_regno); 6225 err = __mark_reg_s32_range(env, regs, value_regno, 6226 range.minval, range.maxval); 6227 if (err) 6228 return err; 6229 } else { 6230 mark_reg_unknown(env, regs, value_regno); 6231 } 6232 } else { 6233 mark_reg_known_zero(env, regs, 6234 value_regno); 6235 if (base_type(info.reg_type) == PTR_TO_BTF_ID) { 6236 regs[value_regno].btf = info.btf; 6237 regs[value_regno].btf_id = info.btf_id; 6238 regs[value_regno].id = info.ref_id; 6239 } 6240 if (type_may_be_null(info.reg_type) && !regs[value_regno].id) 6241 regs[value_regno].id = ++env->id_gen; 6242 } 6243 regs[value_regno].type = info.reg_type; 6244 } 6245 6246 } else if (reg->type == PTR_TO_STACK) { 6247 /* Basic bounds checks. */ 6248 err = check_stack_access_within_bounds(env, reg, argno, off, size, t); 6249 if (err) 6250 return err; 6251 6252 if (t == BPF_READ) 6253 err = check_stack_read(env, reg, argno, off, size, 6254 value_regno); 6255 else 6256 err = check_stack_write(env, reg, off, size, 6257 value_regno, insn_idx); 6258 } else if (reg_is_pkt_pointer(reg)) { 6259 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6260 verbose(env, "cannot write into packet\n"); 6261 return -EACCES; 6262 } 6263 if (t == BPF_WRITE && value_regno >= 0 && 6264 is_pointer_value(env, value_regno)) { 6265 verbose(env, "R%d leaks addr into packet\n", 6266 value_regno); 6267 return -EACCES; 6268 } 6269 err = check_packet_access(env, reg, argno, off, size, false); 6270 if (!err && t == BPF_READ && value_regno >= 0) 6271 mark_reg_unknown(env, regs, value_regno); 6272 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6273 if (t == BPF_WRITE && value_regno >= 0 && 6274 is_pointer_value(env, value_regno)) { 6275 verbose(env, "R%d leaks addr into flow keys\n", 6276 value_regno); 6277 return -EACCES; 6278 } 6279 6280 err = check_flow_keys_access(env, reg, argno, off, size); 6281 if (!err && t == BPF_READ && value_regno >= 0) 6282 mark_reg_unknown(env, regs, value_regno); 6283 } else if (type_is_sk_pointer(reg->type)) { 6284 if (t == BPF_WRITE) { 6285 verbose(env, "%s cannot write into %s\n", 6286 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6287 return -EACCES; 6288 } 6289 err = check_sock_access(env, insn_idx, reg, argno, off, size, t); 6290 if (!err && value_regno >= 0) 6291 mark_reg_unknown(env, regs, value_regno); 6292 } else if (reg->type == PTR_TO_TP_BUFFER) { 6293 err = check_tp_buffer_access(env, reg, argno, off, size); 6294 if (!err && t == BPF_READ && value_regno >= 0) 6295 mark_reg_unknown(env, regs, value_regno); 6296 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6297 !type_may_be_null(reg->type)) { 6298 err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t, 6299 value_regno); 6300 } else if (reg->type == CONST_PTR_TO_MAP) { 6301 err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t, 6302 value_regno); 6303 } else if (base_type(reg->type) == PTR_TO_BUF && 6304 !type_may_be_null(reg->type)) { 6305 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6306 u32 *max_access; 6307 6308 if (rdonly_mem) { 6309 if (t == BPF_WRITE) { 6310 verbose(env, "%s cannot write into %s\n", 6311 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6312 return -EACCES; 6313 } 6314 max_access = &env->prog->aux->max_rdonly_access; 6315 } else { 6316 max_access = &env->prog->aux->max_rdwr_access; 6317 } 6318 6319 err = check_buffer_access(env, reg, argno, off, size, false, 6320 max_access); 6321 6322 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6323 mark_reg_unknown(env, regs, value_regno); 6324 } else if (reg->type == PTR_TO_ARENA) { 6325 if (t == BPF_READ && value_regno >= 0) 6326 mark_reg_unknown(env, regs, value_regno); 6327 } else { 6328 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6329 reg_type_str(env, reg->type)); 6330 return -EACCES; 6331 } 6332 6333 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6334 regs[value_regno].type == SCALAR_VALUE) { 6335 if (!is_ldsx) { 6336 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6337 coerce_reg_to_size(®s[value_regno], size); 6338 } else { 6339 /* 6340 * Sign-extension can change the register value relative 6341 * to a scalar it is linked with by id (e.g. a zero- 6342 * extending fill of the same spilled stack slot), thus 6343 * drop the shared id in that case. 6344 */ 6345 bool no_sext = reg_umax(®s[value_regno]) < 6346 (1ULL << (size * BITS_PER_BYTE - 1)); 6347 6348 coerce_reg_to_size_sx(®s[value_regno], size); 6349 if (!no_sext) 6350 clear_scalar_id(®s[value_regno]); 6351 } 6352 } 6353 return err; 6354 } 6355 6356 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 6357 bool allow_trust_mismatch); 6358 6359 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn, 6360 bool strict_alignment_once, bool is_ldsx, 6361 bool allow_trust_mismatch, const char *ctx) 6362 { 6363 struct bpf_verifier_state *vstate = env->cur_state; 6364 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6365 struct bpf_reg_state *regs = cur_regs(env); 6366 enum bpf_reg_type src_reg_type; 6367 int err; 6368 6369 /* Handle stack arg read */ 6370 if (is_stack_arg_ldx(insn)) { 6371 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6372 if (err) 6373 return err; 6374 return check_stack_arg_read(env, state, insn->off, insn->dst_reg); 6375 } 6376 6377 /* check src operand */ 6378 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6379 if (err) 6380 return err; 6381 6382 /* check dst operand */ 6383 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6384 if (err) 6385 return err; 6386 6387 src_reg_type = regs[insn->src_reg].type; 6388 6389 /* Check if (src_reg + off) is readable. The state of dst_reg will be 6390 * updated by this call. 6391 */ 6392 err = check_mem_access(env, env->insn_idx, regs + insn->src_reg, argno_from_reg(insn->src_reg), insn->off, 6393 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg, 6394 strict_alignment_once, is_ldsx); 6395 err = err ?: save_aux_ptr_type(env, src_reg_type, 6396 allow_trust_mismatch); 6397 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx); 6398 6399 return err; 6400 } 6401 6402 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn, 6403 bool strict_alignment_once) 6404 { 6405 struct bpf_verifier_state *vstate = env->cur_state; 6406 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6407 struct bpf_reg_state *regs = cur_regs(env); 6408 enum bpf_reg_type dst_reg_type; 6409 int err; 6410 6411 /* Handle stack arg write */ 6412 if (is_stack_arg_stx(insn)) { 6413 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6414 if (err) 6415 return err; 6416 return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg); 6417 } 6418 6419 /* check src1 operand */ 6420 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6421 if (err) 6422 return err; 6423 6424 /* check src2 operand */ 6425 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6426 if (err) 6427 return err; 6428 6429 dst_reg_type = regs[insn->dst_reg].type; 6430 6431 /* Check if (dst_reg + off) is writeable. */ 6432 err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6433 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg, 6434 strict_alignment_once, false); 6435 err = err ?: save_aux_ptr_type(env, dst_reg_type, false); 6436 6437 return err; 6438 } 6439 6440 static int check_atomic_rmw(struct bpf_verifier_env *env, 6441 struct bpf_insn *insn) 6442 { 6443 struct bpf_reg_state *dst_reg; 6444 int load_reg; 6445 int err; 6446 6447 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6448 verbose(env, "invalid atomic operand size\n"); 6449 return -EINVAL; 6450 } 6451 6452 /* check src1 operand */ 6453 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6454 if (err) 6455 return err; 6456 6457 /* check src2 operand */ 6458 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6459 if (err) 6460 return err; 6461 6462 if (insn->imm == BPF_CMPXCHG) { 6463 /* Check comparison of R0 with memory location */ 6464 const u32 aux_reg = BPF_REG_0; 6465 6466 err = check_reg_arg(env, aux_reg, SRC_OP); 6467 if (err) 6468 return err; 6469 6470 if (is_pointer_value(env, aux_reg)) { 6471 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6472 return -EACCES; 6473 } 6474 } 6475 6476 if (is_pointer_value(env, insn->src_reg)) { 6477 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6478 return -EACCES; 6479 } 6480 6481 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6482 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6483 insn->dst_reg, 6484 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6485 return -EACCES; 6486 } 6487 6488 if (insn->imm & BPF_FETCH) { 6489 if (insn->imm == BPF_CMPXCHG) 6490 load_reg = BPF_REG_0; 6491 else 6492 load_reg = insn->src_reg; 6493 6494 /* check and record load of old value */ 6495 err = check_reg_arg(env, load_reg, DST_OP); 6496 if (err) 6497 return err; 6498 } else { 6499 /* This instruction accesses a memory location but doesn't 6500 * actually load it into a register. 6501 */ 6502 load_reg = -1; 6503 } 6504 6505 dst_reg = cur_regs(env) + insn->dst_reg; 6506 6507 /* Check whether we can read the memory, with second call for fetch 6508 * case to simulate the register fill. 6509 */ 6510 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6511 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6512 if (!err && load_reg >= 0) 6513 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), 6514 insn->off, BPF_SIZE(insn->code), 6515 BPF_READ, load_reg, true, false); 6516 if (err) 6517 return err; 6518 6519 if (is_arena_reg(env, insn->dst_reg)) { 6520 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 6521 if (err) 6522 return err; 6523 } 6524 /* Check whether we can write into the same memory. */ 6525 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6526 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6527 if (err) 6528 return err; 6529 return 0; 6530 } 6531 6532 static int check_atomic_load(struct bpf_verifier_env *env, 6533 struct bpf_insn *insn) 6534 { 6535 int err; 6536 6537 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6538 if (err) 6539 return err; 6540 6541 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) { 6542 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n", 6543 insn->src_reg, 6544 reg_type_str(env, reg_state(env, insn->src_reg)->type)); 6545 return -EACCES; 6546 } 6547 6548 return check_load_mem(env, insn, true, false, false, "atomic_load"); 6549 } 6550 6551 static int check_atomic_store(struct bpf_verifier_env *env, 6552 struct bpf_insn *insn) 6553 { 6554 int err; 6555 6556 err = check_store_reg(env, insn, true); 6557 if (err) 6558 return err; 6559 6560 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6561 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6562 insn->dst_reg, 6563 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6564 return -EACCES; 6565 } 6566 6567 return 0; 6568 } 6569 6570 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn) 6571 { 6572 switch (insn->imm) { 6573 case BPF_ADD: 6574 case BPF_ADD | BPF_FETCH: 6575 case BPF_AND: 6576 case BPF_AND | BPF_FETCH: 6577 case BPF_OR: 6578 case BPF_OR | BPF_FETCH: 6579 case BPF_XOR: 6580 case BPF_XOR | BPF_FETCH: 6581 case BPF_XCHG: 6582 case BPF_CMPXCHG: 6583 return check_atomic_rmw(env, insn); 6584 case BPF_LOAD_ACQ: 6585 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6586 verbose(env, 6587 "64-bit load-acquires are only supported on 64-bit arches\n"); 6588 return -EOPNOTSUPP; 6589 } 6590 return check_atomic_load(env, insn); 6591 case BPF_STORE_REL: 6592 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6593 verbose(env, 6594 "64-bit store-releases are only supported on 64-bit arches\n"); 6595 return -EOPNOTSUPP; 6596 } 6597 return check_atomic_store(env, insn); 6598 default: 6599 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", 6600 insn->imm); 6601 return -EINVAL; 6602 } 6603 } 6604 6605 /* When register 'regno' is used to read the stack (either directly or through 6606 * a helper function) make sure that it's within stack boundary and, depending 6607 * on the access type and privileges, that all elements of the stack are 6608 * initialized. 6609 * 6610 * All registers that have been spilled on the stack in the slots within the 6611 * read offsets are marked as read. 6612 */ 6613 static int check_stack_range_initialized( 6614 struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 6615 int access_size, bool zero_size_allowed, 6616 enum bpf_access_type type, struct bpf_call_arg_meta *meta) 6617 { 6618 struct bpf_func_state *state = bpf_func(env, reg); 6619 int err, min_off, max_off, i, j, slot, spi; 6620 /* Some accesses can write anything into the stack, others are 6621 * read-only. 6622 */ 6623 bool clobber = type == BPF_WRITE; 6624 /* 6625 * Negative access_size signals global subprog arg check where 6626 * STACK_POISON slots are acceptable. static stack liveness 6627 * might have determined that subprog doesn't read them, 6628 * but BTF based global subprog validation isn't accurate enough. 6629 */ 6630 bool allow_poison = access_size < 0 || clobber; 6631 /* The call will initialize the memory; uninitialized stack allowed */ 6632 bool raw_mode = meta && meta->arg_raw_mem.regno == reg_from_argno(argno); 6633 6634 access_size = abs(access_size); 6635 6636 if (access_size == 0 && !zero_size_allowed) { 6637 verbose(env, "invalid zero-sized read\n"); 6638 return -EACCES; 6639 } 6640 6641 err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type); 6642 if (err) 6643 return err; 6644 6645 6646 if (tnum_is_const(reg->var_off)) { 6647 min_off = max_off = reg->var_off.value + off; 6648 } else { 6649 /* Variable offset is prohibited for unprivileged mode for 6650 * simplicity since it requires corresponding support in 6651 * Spectre masking for stack ALU. 6652 * See also retrieve_ptr_limit(). 6653 */ 6654 if (!env->bypass_spec_v1) { 6655 char tn_buf[48]; 6656 6657 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6658 verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n", 6659 reg_arg_name(env, argno), tn_buf); 6660 return -EACCES; 6661 } 6662 /* Only initialized buffer on stack is allowed to be accessed 6663 * with variable offset. With uninitialized buffer it's hard to 6664 * guarantee that whole memory is marked as initialized on 6665 * helper return since specific bounds are unknown what may 6666 * cause uninitialized stack leaking. 6667 */ 6668 raw_mode = false; 6669 6670 min_off = reg_smin(reg) + off; 6671 max_off = reg_smax(reg) + off; 6672 } 6673 6674 if (raw_mode) { 6675 meta->arg_raw_mem.size = access_size; 6676 return 0; 6677 } 6678 6679 for (i = min_off; i < max_off + access_size; i++) { 6680 u8 *stype; 6681 6682 slot = -i - 1; 6683 spi = slot / BPF_REG_SIZE; 6684 if (state->allocated_stack <= slot) { 6685 verbose(env, "allocated_stack too small\n"); 6686 return -EFAULT; 6687 } 6688 6689 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 6690 if (*stype == STACK_MISC) 6691 goto mark; 6692 if ((*stype == STACK_ZERO) || 6693 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 6694 if (clobber) { 6695 /* helper can write anything into the stack */ 6696 *stype = STACK_MISC; 6697 } 6698 goto mark; 6699 } 6700 6701 if (bpf_is_spilled_reg(&state->stack[spi]) && 6702 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 6703 env->allow_ptr_leaks)) { 6704 if (clobber) { 6705 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 6706 for (j = 0; j < BPF_REG_SIZE; j++) 6707 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 6708 } 6709 goto mark; 6710 } 6711 6712 if (*stype == STACK_POISON) { 6713 if (allow_poison) 6714 goto mark; 6715 verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n", 6716 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6717 } else if (tnum_is_const(reg->var_off)) { 6718 verbose(env, "invalid read from stack %s off %d+%d size %d\n", 6719 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6720 } else { 6721 char tn_buf[48]; 6722 6723 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6724 verbose(env, "invalid read from stack %s var_off %s+%d size %d\n", 6725 reg_arg_name(env, argno), tn_buf, i - min_off, access_size); 6726 } 6727 return -EACCES; 6728 mark: 6729 ; 6730 } 6731 return 0; 6732 } 6733 6734 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 6735 int access_size, enum bpf_access_type access_type, 6736 bool zero_size_allowed, 6737 struct bpf_call_arg_meta *meta) 6738 { 6739 struct bpf_reg_state *regs = cur_regs(env); 6740 u32 *max_access; 6741 6742 switch (base_type(reg->type)) { 6743 case PTR_TO_PACKET: 6744 case PTR_TO_PACKET_META: 6745 return check_packet_access(env, reg, argno, 0, access_size, 6746 zero_size_allowed); 6747 case PTR_TO_MAP_KEY: 6748 if (access_type == BPF_WRITE) { 6749 verbose(env, "%s cannot write into %s\n", 6750 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6751 return -EACCES; 6752 } 6753 return check_mem_region_access(env, reg, argno, 0, access_size, 6754 reg->map_ptr->key_size, false); 6755 case PTR_TO_MAP_VALUE: 6756 if (check_map_access_type(env, reg, 0, access_size, access_type)) 6757 return -EACCES; 6758 return check_map_access(env, reg, argno, 0, access_size, 6759 zero_size_allowed, ACCESS_HELPER); 6760 case PTR_TO_MEM: 6761 if (type_is_rdonly_mem(reg->type)) { 6762 if (access_type == BPF_WRITE) { 6763 verbose(env, "%s cannot write into %s\n", 6764 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6765 return -EACCES; 6766 } 6767 } 6768 return check_mem_region_access(env, reg, argno, 0, 6769 access_size, reg->mem_size, 6770 zero_size_allowed); 6771 case PTR_TO_BUF: 6772 if (type_is_rdonly_mem(reg->type)) { 6773 if (access_type == BPF_WRITE) { 6774 verbose(env, "%s cannot write into %s\n", 6775 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6776 return -EACCES; 6777 } 6778 6779 max_access = &env->prog->aux->max_rdonly_access; 6780 } else { 6781 max_access = &env->prog->aux->max_rdwr_access; 6782 } 6783 return check_buffer_access(env, reg, argno, 0, 6784 access_size, zero_size_allowed, 6785 max_access); 6786 case PTR_TO_STACK: 6787 return check_stack_range_initialized( 6788 env, reg, 6789 argno, 0, access_size, 6790 zero_size_allowed, access_type, meta); 6791 case PTR_TO_BTF_ID: 6792 return check_ptr_to_btf_access(env, regs, reg, argno, 0, 6793 access_size, access_type, -1); 6794 case PTR_TO_CTX: 6795 /* Only permit reading or writing syscall context using helper calls. */ 6796 if (is_var_ctx_off_allowed(env->prog)) { 6797 int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX, 6798 zero_size_allowed); 6799 if (err) 6800 return err; 6801 if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size) 6802 env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size; 6803 return 0; 6804 } 6805 fallthrough; 6806 default: /* scalar_value or invalid ptr */ 6807 /* Allow zero-byte read from NULL, regardless of pointer type */ 6808 if (zero_size_allowed && access_size == 0 && 6809 bpf_register_is_null(reg)) 6810 return 0; 6811 6812 verbose(env, "%s type=%s ", reg_arg_name(env, argno), 6813 reg_type_str(env, reg->type)); 6814 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 6815 return -EACCES; 6816 } 6817 } 6818 6819 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 6820 * size. 6821 * 6822 * @mem_reg contains the pointer, @size_reg contains the access size. 6823 */ 6824 static int check_mem_size_reg(struct bpf_verifier_env *env, 6825 struct bpf_reg_state *mem_reg, 6826 struct bpf_reg_state *size_reg, argno_t mem_argno, 6827 argno_t size_argno, u32 access_type, 6828 bool zero_size_allowed, 6829 struct bpf_call_arg_meta *meta) 6830 { 6831 int err = 0; 6832 6833 /* This is used to refine r0 return value bounds for helpers 6834 * that enforce this value as an upper bound on return values. 6835 * See do_refine_retval_range() for helpers that can refine 6836 * the return value. C type of helper is u32 so we pull register 6837 * bound from umax_value however, if negative verifier errors 6838 * out. Only upper bounds can be learned because retval is an 6839 * int type and negative retvals are allowed. 6840 */ 6841 meta->msize_max_value = reg_umax(size_reg); 6842 6843 /* The register is SCALAR_VALUE; the access check happens using 6844 * its boundaries. For unprivileged variable accesses, disable 6845 * raw mode so that the program is required to initialize all 6846 * the memory that the helper could just partially fill up. 6847 */ 6848 if (!tnum_is_const(size_reg->var_off)) 6849 meta = NULL; 6850 6851 if (reg_smin(size_reg) < 0) { 6852 verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n", 6853 reg_arg_name(env, size_argno)); 6854 return -EACCES; 6855 } 6856 6857 if (reg_umin(size_reg) == 0 && !zero_size_allowed) { 6858 verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n", 6859 reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg)); 6860 return -EACCES; 6861 } 6862 6863 if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) { 6864 verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 6865 reg_arg_name(env, size_argno)); 6866 return -EACCES; 6867 } 6868 6869 if (access_type & BPF_READ) 6870 err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg), 6871 BPF_READ, zero_size_allowed, meta); 6872 if (!err && access_type & BPF_WRITE) 6873 err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg), 6874 BPF_WRITE, zero_size_allowed, meta); 6875 6876 if (!err) { 6877 int regno = reg_from_argno(size_argno); 6878 6879 if (regno >= 0) 6880 err = mark_chain_precision(env, regno); 6881 else 6882 err = mark_stack_arg_precision(env, arg_idx_from_argno(size_argno)); 6883 } 6884 6885 return err; 6886 } 6887 6888 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6889 argno_t argno, u32 mem_size, enum bpf_access_type access_type, 6890 struct bpf_call_arg_meta *meta) 6891 { 6892 int size, err = 0; 6893 6894 if (bpf_register_is_null(reg)) 6895 return 0; 6896 6897 if (mem_size > S32_MAX) { 6898 verbose(env, "%s memory size %u is too large\n", 6899 reg_arg_name(env, argno), mem_size); 6900 return -EACCES; 6901 } 6902 6903 /* 6904 * Only a global subprog (meta == NULL) may read poisoned stack slots: 6905 * its static stack liveness proved the callee body skips them. 6906 */ 6907 size = (!meta && base_type(reg->type) == PTR_TO_STACK) ? -(int)mem_size : mem_size; 6908 6909 if (access_type & BPF_READ) 6910 err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, meta); 6911 if (!err && (access_type & BPF_WRITE)) 6912 err = check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, meta); 6913 6914 return err; 6915 } 6916 6917 static int process_const_alloc_mem_size(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6918 argno_t argno, struct ret_mem_desc *ret_mem) 6919 { 6920 int regno = reg_from_argno(argno); 6921 int err; 6922 6923 if (ret_mem->found) { 6924 verifier_bug(env, "only one allocation size argument permitted"); 6925 return -EFAULT; 6926 } 6927 6928 if (!tnum_is_const(reg->var_off)) { 6929 verbose(env, "%s is not a const\n", reg_arg_name(env, argno)); 6930 return -EINVAL; 6931 } 6932 6933 if (reg->var_off.value > U32_MAX) { 6934 verbose(env, "%s allocation size exceeds u32 max\n", reg_arg_name(env, argno)); 6935 return -EINVAL; 6936 } 6937 6938 if (regno >= 0) 6939 err = mark_chain_precision(env, regno); 6940 else 6941 err = mark_stack_arg_precision(env, arg_idx_from_argno(argno)); 6942 if (err) 6943 return err; 6944 6945 ret_mem->size = reg->var_off.value; 6946 ret_mem->found = true; 6947 6948 return 0; 6949 } 6950 6951 static int process_const_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6952 argno_t argno, struct bpf_call_arg_meta *meta) 6953 { 6954 int regno = reg_from_argno(argno); 6955 int err; 6956 6957 if (meta->arg_constant.found) { 6958 verifier_bug(env, "only one constant argument permitted"); 6959 return -EFAULT; 6960 } 6961 6962 if (!tnum_is_const(reg->var_off)) { 6963 verbose(env, "%s must be a known constant\n", reg_arg_name(env, argno)); 6964 return -EINVAL; 6965 } 6966 6967 if (regno >= 0) 6968 err = mark_chain_precision(env, regno); 6969 else 6970 err = mark_stack_arg_precision(env, arg_idx_from_argno(argno)); 6971 if (err < 0) 6972 return err; 6973 6974 meta->arg_constant.found = true; 6975 meta->arg_constant.value = reg->var_off.value; 6976 6977 return 0; 6978 } 6979 6980 enum { 6981 PROCESS_SPIN_LOCK = (1 << 0), 6982 PROCESS_RES_LOCK = (1 << 1), 6983 PROCESS_LOCK_IRQ = (1 << 2), 6984 }; 6985 6986 /* Implementation details: 6987 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 6988 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 6989 * Two bpf_map_lookups (even with the same key) will have different reg->id. 6990 * Two separate bpf_obj_new will also have different reg->id. 6991 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 6992 * clears reg->id after value_or_null->value transition, since the verifier only 6993 * cares about the range of access to valid map value pointer and doesn't care 6994 * about actual address of the map element. 6995 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 6996 * reg->id > 0 after value_or_null->value transition. By doing so 6997 * two bpf_map_lookups will be considered two different pointers that 6998 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 6999 * returned from bpf_obj_new. 7000 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7001 * dead-locks. 7002 * Since only one bpf_spin_lock is allowed the checks are simpler than 7003 * reg_is_refcounted() logic. The verifier needs to remember only 7004 * one spin_lock instead of array of acquired_refs. 7005 * env->cur_state->active_locks remembers which map value element or allocated 7006 * object got locked and clears it after bpf_spin_unlock. 7007 */ 7008 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags) 7009 { 7010 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK; 7011 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin"; 7012 struct bpf_verifier_state *cur = env->cur_state; 7013 bool is_const = tnum_is_const(reg->var_off); 7014 bool is_irq = flags & PROCESS_LOCK_IRQ; 7015 u64 val = reg->var_off.value; 7016 struct bpf_map *map = NULL; 7017 struct btf *btf = NULL; 7018 struct btf_record *rec; 7019 u32 spin_lock_off; 7020 int err; 7021 7022 if (!is_const) { 7023 verbose(env, 7024 "%s doesn't have constant offset. %s_lock has to be at the constant offset\n", 7025 reg_arg_name(env, argno), lock_str); 7026 return -EINVAL; 7027 } 7028 if (reg->type == PTR_TO_MAP_VALUE) { 7029 map = reg->map_ptr; 7030 if (!map->btf) { 7031 verbose(env, 7032 "map '%s' has to have BTF in order to use %s_lock\n", 7033 map->name, lock_str); 7034 return -EINVAL; 7035 } 7036 } else { 7037 btf = reg->btf; 7038 } 7039 7040 rec = reg_btf_record(reg); 7041 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) { 7042 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local", 7043 map ? map->name : "kptr", lock_str); 7044 return -EINVAL; 7045 } 7046 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off; 7047 if (spin_lock_off != val) { 7048 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n", 7049 val, lock_str, spin_lock_off); 7050 return -EINVAL; 7051 } 7052 if (is_lock) { 7053 void *ptr; 7054 int type; 7055 7056 if (map) 7057 ptr = map; 7058 else 7059 ptr = btf; 7060 7061 if (!is_res_lock && cur->active_locks) { 7062 if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) { 7063 verbose(env, 7064 "Locking two bpf_spin_locks are not allowed\n"); 7065 return -EINVAL; 7066 } 7067 } else if (is_res_lock && cur->active_locks) { 7068 if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) { 7069 verbose(env, "Acquiring the same lock again, AA deadlock detected\n"); 7070 return -EINVAL; 7071 } 7072 } 7073 7074 if (is_res_lock && is_irq) 7075 type = REF_TYPE_RES_LOCK_IRQ; 7076 else if (is_res_lock) 7077 type = REF_TYPE_RES_LOCK; 7078 else 7079 type = REF_TYPE_LOCK; 7080 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr); 7081 if (err < 0) { 7082 verbose(env, "Failed to acquire lock state\n"); 7083 return err; 7084 } 7085 } else { 7086 void *ptr; 7087 int type; 7088 7089 if (map) 7090 ptr = map; 7091 else 7092 ptr = btf; 7093 7094 if (!cur->active_locks) { 7095 verbose(env, "%s_unlock without taking a lock\n", lock_str); 7096 return -EINVAL; 7097 } 7098 7099 if (is_res_lock && is_irq) 7100 type = REF_TYPE_RES_LOCK_IRQ; 7101 else if (is_res_lock) 7102 type = REF_TYPE_RES_LOCK; 7103 else 7104 type = REF_TYPE_LOCK; 7105 if (!find_lock_state(cur, type, reg->id, ptr)) { 7106 verbose(env, "%s_unlock of different lock\n", lock_str); 7107 return -EINVAL; 7108 } 7109 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) { 7110 verbose(env, "%s_unlock cannot be out of order\n", lock_str); 7111 return -EINVAL; 7112 } 7113 if (release_lock_state(cur, type, reg->id, ptr)) { 7114 verbose(env, "%s_unlock of different lock\n", lock_str); 7115 return -EINVAL; 7116 } 7117 if (!in_rcu_cs(env)) 7118 invalidate_rcu_protected_refs(env); 7119 7120 invalidate_non_owning_refs(env); 7121 } 7122 return 0; 7123 } 7124 7125 /* Check if @regno is a pointer to a specific field in a map value */ 7126 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7127 enum btf_field_type field_type, 7128 struct bpf_map_desc *map_desc) 7129 { 7130 bool is_const = tnum_is_const(reg->var_off); 7131 struct bpf_map *map = reg->map_ptr; 7132 u64 val = reg->var_off.value; 7133 const char *struct_name = btf_field_type_name(field_type); 7134 int field_off = -1; 7135 7136 if (!is_const) { 7137 verbose(env, 7138 "%s doesn't have constant offset. %s has to be at the constant offset\n", 7139 reg_arg_name(env, argno), struct_name); 7140 return -EINVAL; 7141 } 7142 if (!map->btf) { 7143 verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name, 7144 struct_name); 7145 return -EINVAL; 7146 } 7147 if (!btf_record_has_field(map->record, field_type)) { 7148 verbose(env, "map '%s' has no valid %s\n", map->name, struct_name); 7149 return -EINVAL; 7150 } 7151 switch (field_type) { 7152 case BPF_TIMER: 7153 field_off = map->record->timer_off; 7154 break; 7155 case BPF_TASK_WORK: 7156 field_off = map->record->task_work_off; 7157 break; 7158 case BPF_WORKQUEUE: 7159 field_off = map->record->wq_off; 7160 break; 7161 default: 7162 verifier_bug(env, "unsupported BTF field type: %s\n", struct_name); 7163 return -EINVAL; 7164 } 7165 if (field_off != val) { 7166 verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n", 7167 val, struct_name, field_off); 7168 return -EINVAL; 7169 } 7170 if (map_desc->ptr) { 7171 verifier_bug(env, "Two map pointers in a %s helper", struct_name); 7172 return -EFAULT; 7173 } 7174 map_desc->uid = reg->map_uid; 7175 map_desc->ptr = map; 7176 return 0; 7177 } 7178 7179 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7180 struct bpf_map_desc *map) 7181 { 7182 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 7183 verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n"); 7184 return -EOPNOTSUPP; 7185 } 7186 return check_map_field_pointer(env, reg, argno, BPF_TIMER, map); 7187 } 7188 7189 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7190 struct bpf_call_arg_meta *meta) 7191 { 7192 struct bpf_reg_state *reg = reg_state(env, regno); 7193 struct btf_field *kptr_field; 7194 struct bpf_map *map_ptr; 7195 struct btf_record *rec; 7196 u32 kptr_off; 7197 7198 if (type_is_ptr_alloc_obj(reg->type)) { 7199 rec = reg_btf_record(reg); 7200 } else { /* PTR_TO_MAP_VALUE */ 7201 map_ptr = reg->map_ptr; 7202 if (!map_ptr->btf) { 7203 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7204 map_ptr->name); 7205 return -EINVAL; 7206 } 7207 rec = map_ptr->record; 7208 meta->map.ptr = map_ptr; 7209 } 7210 7211 if (!tnum_is_const(reg->var_off)) { 7212 verbose(env, 7213 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7214 regno); 7215 return -EINVAL; 7216 } 7217 7218 if (!btf_record_has_field(rec, BPF_KPTR)) { 7219 verbose(env, "R%d has no valid kptr\n", regno); 7220 return -EINVAL; 7221 } 7222 7223 kptr_off = reg->var_off.value; 7224 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 7225 if (!kptr_field) { 7226 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7227 return -EACCES; 7228 } 7229 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7230 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7231 return -EACCES; 7232 } 7233 meta->kptr_field = kptr_field; 7234 return 0; 7235 } 7236 7237 /* 7238 * Validate dynptr arguments for helper, kfunc and subprog. 7239 * 7240 * @dynptr is both input and output. It is populated when the argument is 7241 * tagged with MEM_UNINIT (i.e., the dynptr argument that will be constructed) 7242 * and consumed when the argument is expecting to be an initialized dynptr. 7243 * @parent_id is used to track the referenced parent object (e.g., file or skb in 7244 * qdisc program) when constructing a dynptr. 7245 * 7246 * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7247 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7248 * 7249 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7250 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7251 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7252 * 7253 * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the 7254 * dynptr points to. At the first level, the verifier will make sure a 7255 * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of 7256 * a dynptr's view (i.e., start and offset) is not tracked as there is not such 7257 * use case. The second level is tracked using the upper bit of bpf_dynptr->size 7258 * and checked dynamically during runtime. 7259 */ 7260 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7261 argno_t argno, int insn_idx, enum bpf_arg_type arg_type, 7262 struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr) 7263 { 7264 int spi, err = 0; 7265 7266 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 7267 verbose(env, 7268 "%s expected pointer to stack or const struct bpf_dynptr\n", 7269 reg_arg_name(env, argno)); 7270 return -EINVAL; 7271 } 7272 7273 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7274 * constructing a mutable bpf_dynptr object. 7275 * 7276 * Currently, this is only possible with PTR_TO_STACK 7277 * pointing to a region of at least 16 bytes which doesn't 7278 * contain an existing bpf_dynptr. 7279 * 7280 * OBJ_RELEASE - Points to a initialized bpf_dynptr that will be 7281 * destroyed. 7282 * 7283 * None - Points to a initialized dynptr that cannot be 7284 * reinitialized or destroyed. However, the view of the 7285 * dynptr and the memory it points to may be mutated. 7286 */ 7287 if (arg_type & MEM_UNINIT) { 7288 int i; 7289 7290 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7291 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7292 return -EINVAL; 7293 } 7294 7295 /* we write BPF_DW bits (8 bytes) at a time */ 7296 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7297 err = check_mem_access(env, insn_idx, reg, argno, 7298 i, BPF_DW, BPF_WRITE, -1, false, false); 7299 if (err) 7300 return err; 7301 } 7302 7303 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, ref_obj, dynptr); 7304 } else /* OBJ_RELEASE and None case from above */ { 7305 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7306 if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) { 7307 verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n"); 7308 return -EINVAL; 7309 } 7310 7311 if (!is_dynptr_reg_valid_init(env, reg)) { 7312 verbose(env, "Expected an initialized dynptr as %s\n", 7313 reg_arg_name(env, argno)); 7314 return -EINVAL; 7315 } 7316 7317 /* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */ 7318 if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) { 7319 verbose(env, 7320 "Expected a dynptr of type %s as %s\n", 7321 dynptr_type_str(arg_to_dynptr_type(arg_type)), 7322 reg_arg_name(env, argno)); 7323 return -EINVAL; 7324 } 7325 7326 if (reg->type != CONST_PTR_TO_DYNPTR) { 7327 struct bpf_func_state *state = bpf_func(env, reg); 7328 7329 spi = dynptr_get_spi(env, reg); 7330 if (spi < 0) 7331 return spi; 7332 7333 mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS); 7334 7335 reg = &state->stack[spi].spilled_ptr; 7336 } 7337 7338 if (dynptr) { 7339 dynptr->type = reg->dynptr.type; 7340 dynptr->id = reg->id; 7341 dynptr->parent_id = reg->parent_id; 7342 } 7343 } 7344 return err; 7345 } 7346 7347 static bool is_iter_kfunc(struct bpf_call_arg_meta *meta) 7348 { 7349 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7350 } 7351 7352 static bool is_iter_new_kfunc(struct bpf_call_arg_meta *meta) 7353 { 7354 return meta->kfunc_flags & KF_ITER_NEW; 7355 } 7356 7357 7358 static bool is_iter_destroy_kfunc(struct bpf_call_arg_meta *meta) 7359 { 7360 return meta->kfunc_flags & KF_ITER_DESTROY; 7361 } 7362 7363 static bool is_kfunc_arg_iter(struct bpf_call_arg_meta *meta, int arg_idx, 7364 const struct btf_param *arg) 7365 { 7366 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7367 * kfunc is iter state pointer 7368 */ 7369 if (is_iter_kfunc(meta)) 7370 return arg_idx == 0; 7371 7372 /* iter passed as an argument to a generic kfunc */ 7373 return btf_param_match_suffix(meta->btf, arg, "__iter"); 7374 } 7375 7376 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx, 7377 struct bpf_call_arg_meta *meta) 7378 { 7379 struct bpf_func_state *state = bpf_func(env, reg); 7380 const struct btf_type *t; 7381 u32 arg_idx = arg_idx_from_argno(argno); 7382 int spi, err, i, nr_slots, btf_id; 7383 7384 if (reg->type != PTR_TO_STACK) { 7385 verbose(env, "%s expected pointer to an iterator on stack\n", 7386 reg_arg_name(env, argno)); 7387 return -EINVAL; 7388 } 7389 7390 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 7391 * ensures struct convention, so we wouldn't need to do any BTF 7392 * validation here. But given iter state can be passed as a parameter 7393 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 7394 * conservative here. 7395 */ 7396 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg_idx); 7397 if (btf_id < 0) { 7398 verbose(env, "expected valid iter pointer as %s\n", 7399 reg_arg_name(env, argno)); 7400 return -EINVAL; 7401 } 7402 t = btf_type_by_id(meta->btf, btf_id); 7403 nr_slots = t->size / BPF_REG_SIZE; 7404 7405 if (is_iter_new_kfunc(meta)) { 7406 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7407 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7408 verbose(env, "expected uninitialized iter_%s as %s\n", 7409 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7410 return -EINVAL; 7411 } 7412 7413 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7414 err = check_mem_access(env, insn_idx, reg, argno, 7415 i, BPF_DW, BPF_WRITE, -1, false, false); 7416 if (err) 7417 return err; 7418 } 7419 7420 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7421 if (err) 7422 return err; 7423 } else { 7424 /* iter_next() or iter_destroy(), as well as any kfunc 7425 * accepting iter argument, expect initialized iter state 7426 */ 7427 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7428 switch (err) { 7429 case 0: 7430 break; 7431 case -EINVAL: 7432 verbose(env, "expected an initialized iter_%s as %s\n", 7433 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7434 return err; 7435 case -EPROTO: 7436 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7437 return err; 7438 default: 7439 return err; 7440 } 7441 7442 spi = iter_get_spi(env, reg, nr_slots); 7443 if (spi < 0) 7444 return spi; 7445 7446 mark_stack_slots_scratched(env, spi, nr_slots); 7447 7448 /* remember meta->iter info for process_iter_next_call() */ 7449 meta->iter.spi = spi; 7450 meta->iter.frameno = reg->frameno; 7451 update_ref_obj(&meta->ref_obj, &state->stack[spi].spilled_ptr); 7452 7453 if (is_iter_destroy_kfunc(meta)) { 7454 err = unmark_stack_slots_iter(env, reg, nr_slots); 7455 if (err) 7456 return err; 7457 } 7458 } 7459 7460 return 0; 7461 } 7462 7463 /* Look for a previous loop entry at insn_idx: nearest parent state 7464 * stopped at insn_idx with callsites matching those in cur->frame. 7465 */ 7466 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7467 struct bpf_verifier_state *cur, 7468 int insn_idx) 7469 { 7470 struct bpf_verifier_state_list *sl; 7471 struct bpf_verifier_state *st; 7472 struct list_head *pos, *head; 7473 7474 /* Explored states are pushed in stack order, most recent states come first */ 7475 head = bpf_explored_state(env, insn_idx); 7476 list_for_each(pos, head) { 7477 sl = container_of(pos, struct bpf_verifier_state_list, node); 7478 /* If st->branches != 0 state is a part of current DFS verification path, 7479 * hence cur & st for a loop. 7480 */ 7481 st = &sl->state; 7482 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7483 st->dfs_depth < cur->dfs_depth) 7484 return st; 7485 } 7486 7487 return NULL; 7488 } 7489 7490 /* 7491 * Check if scalar registers are exact for the purpose of not widening. 7492 * More lenient than regs_exact() 7493 */ 7494 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold, 7495 const struct bpf_reg_state *rcur) 7496 { 7497 return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)); 7498 } 7499 7500 static void maybe_widen_reg(struct bpf_verifier_env *env, 7501 struct bpf_reg_state *rold, struct bpf_reg_state *rcur) 7502 { 7503 if (rold->type != SCALAR_VALUE) 7504 return; 7505 if (rold->type != rcur->type) 7506 return; 7507 if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur)) 7508 return; 7509 __mark_reg_unknown(env, rcur); 7510 } 7511 7512 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7513 struct bpf_verifier_state *old, 7514 struct bpf_verifier_state *cur) 7515 { 7516 struct bpf_func_state *fold, *fcur; 7517 int i, fr, num_slots; 7518 7519 for (fr = old->curframe; fr >= 0; fr--) { 7520 fold = old->frame[fr]; 7521 fcur = cur->frame[fr]; 7522 7523 for (i = 0; i < MAX_BPF_REG; i++) 7524 maybe_widen_reg(env, 7525 &fold->regs[i], 7526 &fcur->regs[i]); 7527 7528 num_slots = min(fold->allocated_stack / BPF_REG_SIZE, 7529 fcur->allocated_stack / BPF_REG_SIZE); 7530 for (i = 0; i < num_slots; i++) { 7531 if (!bpf_is_spilled_reg(&fold->stack[i]) || 7532 !bpf_is_spilled_reg(&fcur->stack[i])) 7533 continue; 7534 7535 maybe_widen_reg(env, 7536 &fold->stack[i].spilled_ptr, 7537 &fcur->stack[i].spilled_ptr); 7538 } 7539 } 7540 return 0; 7541 } 7542 7543 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 7544 struct bpf_call_arg_meta *meta) 7545 { 7546 int iter_frameno = meta->iter.frameno; 7547 int iter_spi = meta->iter.spi; 7548 7549 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7550 } 7551 7552 /* process_iter_next_call() is called when verifier gets to iterator's next 7553 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7554 * to it as just "iter_next()" in comments below. 7555 * 7556 * BPF verifier relies on a crucial contract for any iter_next() 7557 * implementation: it should *eventually* return NULL, and once that happens 7558 * it should keep returning NULL. That is, once iterator exhausts elements to 7559 * iterate, it should never reset or spuriously return new elements. 7560 * 7561 * With the assumption of such contract, process_iter_next_call() simulates 7562 * a fork in the verifier state to validate loop logic correctness and safety 7563 * without having to simulate infinite amount of iterations. 7564 * 7565 * In current state, we first assume that iter_next() returned NULL and 7566 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7567 * conditions we should not form an infinite loop and should eventually reach 7568 * exit. 7569 * 7570 * Besides that, we also fork current state and enqueue it for later 7571 * verification. In a forked state we keep iterator state as ACTIVE 7572 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7573 * also bump iteration depth to prevent erroneous infinite loop detection 7574 * later on (see iter_active_depths_differ() comment for details). In this 7575 * state we assume that we'll eventually loop back to another iter_next() 7576 * calls (it could be in exactly same location or in some other instruction, 7577 * it doesn't matter, we don't make any unnecessary assumptions about this, 7578 * everything revolves around iterator state in a stack slot, not which 7579 * instruction is calling iter_next()). When that happens, we either will come 7580 * to iter_next() with equivalent state and can conclude that next iteration 7581 * will proceed in exactly the same way as we just verified, so it's safe to 7582 * assume that loop converges. If not, we'll go on another iteration 7583 * simulation with a different input state, until all possible starting states 7584 * are validated or we reach maximum number of instructions limit. 7585 * 7586 * This way, we will either exhaustively discover all possible input states 7587 * that iterator loop can start with and eventually will converge, or we'll 7588 * effectively regress into bounded loop simulation logic and either reach 7589 * maximum number of instructions if loop is not provably convergent, or there 7590 * is some statically known limit on number of iterations (e.g., if there is 7591 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7592 * 7593 * Iteration convergence logic in is_state_visited() relies on exact 7594 * states comparison, which ignores read and precision marks. 7595 * This is necessary because read and precision marks are not finalized 7596 * while in the loop. Exact comparison might preclude convergence for 7597 * simple programs like below: 7598 * 7599 * i = 0; 7600 * while(iter_next(&it)) 7601 * i++; 7602 * 7603 * At each iteration step i++ would produce a new distinct state and 7604 * eventually instruction processing limit would be reached. 7605 * 7606 * To avoid such behavior speculatively forget (widen) range for 7607 * imprecise scalar registers, if those registers were not precise at the 7608 * end of the previous iteration and do not match exactly. 7609 * 7610 * This is a conservative heuristic that allows to verify wide range of programs, 7611 * however it precludes verification of programs that conjure an 7612 * imprecise value on the first loop iteration and use it as precise on a second. 7613 * For example, the following safe program would fail to verify: 7614 * 7615 * struct bpf_num_iter it; 7616 * int arr[10]; 7617 * int i = 0, a = 0; 7618 * bpf_iter_num_new(&it, 0, 10); 7619 * while (bpf_iter_num_next(&it)) { 7620 * if (a == 0) { 7621 * a = 1; 7622 * i = 7; // Because i changed verifier would forget 7623 * // it's range on second loop entry. 7624 * } else { 7625 * arr[i] = 42; // This would fail to verify. 7626 * } 7627 * } 7628 * bpf_iter_num_destroy(&it); 7629 */ 7630 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7631 struct bpf_call_arg_meta *meta) 7632 { 7633 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7634 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7635 struct bpf_reg_state *cur_iter, *queued_iter; 7636 7637 BTF_TYPE_EMIT(struct bpf_iter); 7638 7639 cur_iter = get_iter_from_state(cur_st, meta); 7640 7641 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7642 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7643 verifier_bug(env, "unexpected iterator state %d (%s)", 7644 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7645 return -EFAULT; 7646 } 7647 7648 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7649 /* Because iter_next() call is a checkpoint is_state_visitied() 7650 * should guarantee parent state with same call sites and insn_idx. 7651 */ 7652 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7653 !same_callsites(cur_st->parent, cur_st)) { 7654 verifier_bug(env, "bad parent state for iter next call"); 7655 return -EFAULT; 7656 } 7657 /* Note cur_st->parent in the call below, it is necessary to skip 7658 * checkpoint created for cur_st by is_state_visited() 7659 * right at this instruction. 7660 */ 7661 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7662 /* branch out active iter state */ 7663 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7664 if (IS_ERR(queued_st)) 7665 return PTR_ERR(queued_st); 7666 7667 queued_iter = get_iter_from_state(queued_st, meta); 7668 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7669 queued_iter->iter.depth++; 7670 if (prev_st) 7671 widen_imprecise_scalars(env, prev_st, queued_st); 7672 7673 queued_fr = queued_st->frame[queued_st->curframe]; 7674 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7675 } 7676 7677 /* switch to DRAINED state, but keep the depth unchanged */ 7678 /* mark current iter state as drained and assume returned NULL */ 7679 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7680 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7681 7682 return 0; 7683 } 7684 7685 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7686 { 7687 return type == ARG_MEM_SIZE || type == ARG_MEM_SIZE_OR_ZERO; 7688 } 7689 7690 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 7691 { 7692 /* 7693 * A map value output buffer (e.g. bpf_map_pop_elem) is also a raw 7694 * (uninitialized) memory argument, and like ARG_PTR_TO_MEM it may be 7695 * passed as a PTR_TO_STACK that reaches check_stack_range_initialized(). 7696 */ 7697 return (base_type(type) == ARG_PTR_TO_MEM || 7698 base_type(type) == ARG_PTR_TO_MAP_VALUE) && 7699 type & MEM_UNINIT; 7700 } 7701 7702 static bool arg_type_is_release(enum bpf_arg_type type) 7703 { 7704 return type & OBJ_RELEASE; 7705 } 7706 7707 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7708 { 7709 return base_type(type) == ARG_PTR_TO_DYNPTR; 7710 } 7711 7712 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7713 const struct bpf_call_arg_meta *meta, 7714 enum bpf_arg_type *arg_type) 7715 { 7716 if (!meta->map.ptr) { 7717 /* kernel subsystem misconfigured verifier */ 7718 verifier_bug(env, "invalid map_ptr to access map->type"); 7719 return -EFAULT; 7720 } 7721 7722 switch (meta->map.ptr->map_type) { 7723 case BPF_MAP_TYPE_SOCKMAP: 7724 case BPF_MAP_TYPE_SOCKHASH: 7725 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7726 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7727 } else { 7728 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7729 return -EINVAL; 7730 } 7731 break; 7732 case BPF_MAP_TYPE_BLOOM_FILTER: 7733 if (meta->func_id == BPF_FUNC_map_peek_elem) 7734 *arg_type = ARG_PTR_TO_MAP_VALUE; 7735 break; 7736 default: 7737 break; 7738 } 7739 return 0; 7740 } 7741 7742 struct bpf_reg_types { 7743 const enum bpf_reg_type types[10]; 7744 u32 *btf_id; 7745 }; 7746 7747 static const struct bpf_reg_types sock_types = { 7748 .types = { 7749 PTR_TO_SOCK_COMMON, 7750 PTR_TO_SOCKET, 7751 PTR_TO_TCP_SOCK, 7752 PTR_TO_XDP_SOCK, 7753 }, 7754 }; 7755 7756 #ifdef CONFIG_NET 7757 static const struct bpf_reg_types btf_id_sock_common_types = { 7758 .types = { 7759 PTR_TO_SOCK_COMMON, 7760 PTR_TO_SOCKET, 7761 PTR_TO_TCP_SOCK, 7762 PTR_TO_XDP_SOCK, 7763 PTR_TO_BTF_ID, 7764 PTR_TO_BTF_ID | PTR_TRUSTED, 7765 }, 7766 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7767 }; 7768 #endif 7769 7770 static const struct bpf_reg_types mem_types = { 7771 .types = { 7772 PTR_TO_STACK, 7773 PTR_TO_PACKET, 7774 PTR_TO_PACKET_META, 7775 PTR_TO_MAP_KEY, 7776 PTR_TO_MAP_VALUE, 7777 PTR_TO_MEM, 7778 PTR_TO_MEM | MEM_RINGBUF, 7779 PTR_TO_BUF, 7780 PTR_TO_BTF_ID | PTR_TRUSTED, 7781 PTR_TO_CTX, 7782 }, 7783 }; 7784 7785 static const struct bpf_reg_types spin_lock_types = { 7786 .types = { 7787 PTR_TO_MAP_VALUE, 7788 PTR_TO_BTF_ID | MEM_ALLOC, 7789 } 7790 }; 7791 7792 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7793 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7794 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7795 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7796 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7797 static const struct bpf_reg_types btf_ptr_types = { 7798 .types = { 7799 PTR_TO_BTF_ID, 7800 PTR_TO_BTF_ID | PTR_TRUSTED, 7801 PTR_TO_BTF_ID | MEM_RCU, 7802 }, 7803 }; 7804 static const struct bpf_reg_types percpu_btf_ptr_types = { 7805 .types = { 7806 PTR_TO_BTF_ID | MEM_PERCPU, 7807 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 7808 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7809 } 7810 }; 7811 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7812 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7813 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7814 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7815 static const struct bpf_reg_types kptr_xchg_dest_types = { 7816 .types = { 7817 PTR_TO_MAP_VALUE, 7818 PTR_TO_BTF_ID | MEM_ALLOC, 7819 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF, 7820 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU, 7821 } 7822 }; 7823 static const struct bpf_reg_types dynptr_types = { 7824 .types = { 7825 PTR_TO_STACK, 7826 CONST_PTR_TO_DYNPTR, 7827 } 7828 }; 7829 7830 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7831 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7832 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7833 [ARG_MEM_SIZE] = &scalar_types, 7834 [ARG_MEM_SIZE_OR_ZERO] = &scalar_types, 7835 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7836 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7837 [ARG_PTR_TO_CTX] = &context_types, 7838 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7839 #ifdef CONFIG_NET 7840 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7841 #endif 7842 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7843 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7844 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7845 [ARG_PTR_TO_MEM] = &mem_types, 7846 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7847 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7848 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7849 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7850 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7851 [ARG_PTR_TO_TIMER] = &timer_types, 7852 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 7853 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7854 }; 7855 7856 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7857 enum bpf_arg_type arg_type, 7858 const u32 *arg_btf_id, 7859 struct bpf_call_arg_meta *meta) 7860 { 7861 enum bpf_reg_type expected, type = reg->type; 7862 const struct bpf_reg_types *compatible; 7863 int i, j, err; 7864 7865 compatible = compatible_reg_types[base_type(arg_type)]; 7866 if (!compatible) { 7867 verifier_bug(env, "unsupported arg type %d", arg_type); 7868 return -EFAULT; 7869 } 7870 7871 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7872 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7873 * 7874 * Same for MAYBE_NULL: 7875 * 7876 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7877 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7878 * 7879 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 7880 * 7881 * Therefore we fold these flags depending on the arg_type before comparison. 7882 */ 7883 if (arg_type & MEM_RDONLY) 7884 type &= ~MEM_RDONLY; 7885 if (arg_type & PTR_MAYBE_NULL) 7886 type &= ~PTR_MAYBE_NULL; 7887 if (base_type(arg_type) == ARG_PTR_TO_MEM) 7888 type &= ~DYNPTR_TYPE_FLAG_MASK; 7889 7890 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 7891 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && reg_from_argno(argno) == BPF_REG_2) { 7892 type &= ~MEM_ALLOC; 7893 type &= ~MEM_PERCPU; 7894 } 7895 7896 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7897 expected = compatible->types[i]; 7898 if (expected == NOT_INIT) 7899 break; 7900 7901 if (type == expected) 7902 goto found; 7903 } 7904 7905 verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7906 for (j = 0; j + 1 < i; j++) 7907 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7908 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7909 return -EACCES; 7910 7911 found: 7912 if (base_type(reg->type) != PTR_TO_BTF_ID) 7913 return 0; 7914 7915 if (compatible == &mem_types) { 7916 if (!(arg_type & MEM_RDONLY)) { 7917 verbose(env, 7918 "%s() may write into memory pointed by %s type=%s\n", 7919 func_id_name(meta->func_id), 7920 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7921 return -EACCES; 7922 } 7923 return 0; 7924 } 7925 7926 switch ((int)reg->type) { 7927 case PTR_TO_BTF_ID: 7928 case PTR_TO_BTF_ID | PTR_TRUSTED: 7929 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 7930 case PTR_TO_BTF_ID | MEM_RCU: 7931 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 7932 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 7933 { 7934 /* For bpf_sk_release, it needs to match against first member 7935 * 'struct sock_common', hence make an exception for it. This 7936 * allows bpf_sk_release to work for multiple socket types. 7937 */ 7938 bool strict_type_match = arg_type_is_release(arg_type) && 7939 meta->func_id != BPF_FUNC_sk_release; 7940 7941 if (type_may_be_null(reg->type) && 7942 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 7943 verbose(env, "Possibly NULL pointer passed to helper %s\n", 7944 reg_arg_name(env, argno)); 7945 return -EACCES; 7946 } 7947 7948 if (!arg_btf_id) { 7949 if (!compatible->btf_id) { 7950 verifier_bug(env, "missing arg compatible BTF ID"); 7951 return -EFAULT; 7952 } 7953 arg_btf_id = compatible->btf_id; 7954 } 7955 7956 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7957 if (map_kptr_match_type(env, meta->kptr_field, reg, reg_from_argno(argno))) 7958 return -EACCES; 7959 } else { 7960 if (arg_btf_id == BPF_PTR_POISON) { 7961 verbose(env, "verifier internal error:"); 7962 verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n", 7963 reg_arg_name(env, argno)); 7964 return -EACCES; 7965 } 7966 7967 err = __check_ptr_off_reg(env, reg, argno, true); 7968 if (err) 7969 return err; 7970 7971 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 7972 reg->var_off.value, btf_vmlinux, *arg_btf_id, 7973 strict_type_match, !type_is_alloc(reg->type))) { 7974 verbose(env, "%s is of type %s but %s is expected\n", 7975 reg_arg_name(env, argno), 7976 btf_type_name(reg->btf, reg->btf_id), 7977 btf_type_name(btf_vmlinux, *arg_btf_id)); 7978 return -EACCES; 7979 } 7980 } 7981 break; 7982 } 7983 case PTR_TO_BTF_ID | MEM_ALLOC: 7984 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 7985 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 7986 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 7987 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 7988 meta->func_id != BPF_FUNC_kptr_xchg) { 7989 verifier_bug(env, "unimplemented handling of MEM_ALLOC"); 7990 return -EFAULT; 7991 } 7992 /* Check if local kptr in src arg matches kptr in dst arg */ 7993 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7994 int regno = reg_from_argno(argno); 7995 7996 if (regno == BPF_REG_2 && 7997 map_kptr_match_type(env, meta->kptr_field, reg, regno)) 7998 return -EACCES; 7999 } 8000 break; 8001 case PTR_TO_BTF_ID | MEM_PERCPU: 8002 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8003 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8004 /* Handled by helper specific checks */ 8005 break; 8006 default: 8007 verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match"); 8008 return -EFAULT; 8009 } 8010 return 0; 8011 } 8012 8013 static struct btf_field * 8014 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8015 { 8016 struct btf_field *field; 8017 struct btf_record *rec; 8018 8019 rec = reg_btf_record(reg); 8020 if (!rec) 8021 return NULL; 8022 8023 field = btf_record_find(rec, off, fields); 8024 if (!field) 8025 return NULL; 8026 8027 return field; 8028 } 8029 8030 static int __check_func_arg_reg_off(struct bpf_verifier_env *env, 8031 const struct bpf_reg_state *reg, argno_t argno, 8032 enum bpf_arg_type arg_type, 8033 bool btf_id_fixed_off_ok) 8034 { 8035 u32 type = reg->type; 8036 8037 /* When referenced register is passed to release function, its fixed 8038 * offset must be 0. 8039 * 8040 * We will check arg_type_is_release reg has id when storing 8041 * meta->release_regno. 8042 */ 8043 if (arg_type_is_release(arg_type)) { 8044 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8045 * may not directly point to the object being released, but to 8046 * dynptr pointing to such object, which might be at some offset 8047 * on the stack. In that case, we simply to fallback to the 8048 * default handling. 8049 */ 8050 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8051 return 0; 8052 8053 /* Doing check_ptr_off_reg check for the offset will catch this 8054 * because fixed_off_ok is false, but checking here allows us 8055 * to give the user a better error message. 8056 */ 8057 if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) { 8058 verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n", 8059 reg_arg_name(env, argno)); 8060 return -EINVAL; 8061 } 8062 } 8063 8064 switch (type) { 8065 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8066 case PTR_TO_STACK: 8067 case PTR_TO_PACKET: 8068 case PTR_TO_PACKET_META: 8069 case PTR_TO_MAP_KEY: 8070 case PTR_TO_MAP_VALUE: 8071 case PTR_TO_MEM: 8072 case PTR_TO_MEM | MEM_RDONLY: 8073 case PTR_TO_MEM | MEM_RINGBUF: 8074 case PTR_TO_BUF: 8075 case PTR_TO_BUF | MEM_RDONLY: 8076 case PTR_TO_ARENA: 8077 case SCALAR_VALUE: 8078 return 0; 8079 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8080 * fixed offset. 8081 */ 8082 case PTR_TO_BTF_ID: 8083 case PTR_TO_BTF_ID | MEM_ALLOC: 8084 case PTR_TO_BTF_ID | PTR_TRUSTED: 8085 case PTR_TO_BTF_ID | MEM_RCU: 8086 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8087 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8088 /* When referenced PTR_TO_BTF_ID is passed to release function, 8089 * its fixed offset must be 0. In the other cases, fixed offset 8090 * can be non-zero unless the caller requires otherwise. 8091 * var_off always must be 0 for PTR_TO_BTF_ID, hence we still 8092 * need to do checks instead of returning. 8093 */ 8094 return __check_ptr_off_reg(env, reg, argno, btf_id_fixed_off_ok); 8095 case PTR_TO_CTX: 8096 /* 8097 * Allow fixed and variable offsets for syscall context, but 8098 * only when the argument is passed as memory, not ctx, 8099 * otherwise we may get modified ctx in tail called programs and 8100 * global subprogs (that may act as extension prog hooks). 8101 */ 8102 if (arg_type != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog)) 8103 return 0; 8104 fallthrough; 8105 default: 8106 return __check_ptr_off_reg(env, reg, argno, false); 8107 } 8108 } 8109 8110 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8111 const struct bpf_reg_state *reg, argno_t argno, 8112 enum bpf_arg_type arg_type) 8113 { 8114 return __check_func_arg_reg_off(env, reg, argno, arg_type, true); 8115 } 8116 8117 static int check_arg_const_str(struct bpf_verifier_env *env, 8118 struct bpf_reg_state *reg, argno_t argno) 8119 { 8120 struct bpf_map *map = reg->map_ptr; 8121 int err; 8122 int map_off; 8123 u64 map_addr; 8124 char *str_ptr; 8125 8126 if (reg->type != PTR_TO_MAP_VALUE) 8127 return -EINVAL; 8128 8129 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 8130 verbose(env, "%s points to insn_array map which cannot be used as const string\n", 8131 reg_arg_name(env, argno)); 8132 return -EACCES; 8133 } 8134 8135 if (!bpf_map_is_rdonly(map)) { 8136 verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno)); 8137 return -EACCES; 8138 } 8139 8140 if (!tnum_is_const(reg->var_off)) { 8141 verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno)); 8142 return -EACCES; 8143 } 8144 8145 if (!map->ops->map_direct_value_addr) { 8146 verbose(env, "no direct value access support for this map type\n"); 8147 return -EACCES; 8148 } 8149 8150 err = check_map_access(env, reg, argno, 0, 8151 map->value_size - reg->var_off.value, false, 8152 ACCESS_HELPER); 8153 if (err) 8154 return err; 8155 8156 map_off = reg->var_off.value; 8157 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8158 if (err) { 8159 verbose(env, "direct value access on string failed\n"); 8160 return err; 8161 } 8162 8163 str_ptr = (char *)(long)(map_addr); 8164 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8165 verbose(env, "string is not zero-terminated\n"); 8166 return -EINVAL; 8167 } 8168 return 0; 8169 } 8170 8171 /* Returns constant key value in `value` if possible, else negative error */ 8172 static int get_constant_map_key(struct bpf_verifier_env *env, 8173 struct bpf_reg_state *key, 8174 u32 key_size, 8175 s64 *value) 8176 { 8177 struct bpf_func_state *state = bpf_func(env, key); 8178 struct bpf_reg_state *reg; 8179 int slot, spi, off; 8180 int spill_size = 0; 8181 int zero_size = 0; 8182 int stack_off; 8183 int i, err; 8184 u8 *stype; 8185 8186 if (!env->bpf_capable) 8187 return -EOPNOTSUPP; 8188 if (key->type != PTR_TO_STACK) 8189 return -EOPNOTSUPP; 8190 if (!tnum_is_const(key->var_off)) 8191 return -EOPNOTSUPP; 8192 8193 stack_off = key->var_off.value; 8194 slot = -stack_off - 1; 8195 spi = slot / BPF_REG_SIZE; 8196 off = slot % BPF_REG_SIZE; 8197 stype = state->stack[spi].slot_type; 8198 8199 /* First handle precisely tracked STACK_ZERO */ 8200 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) 8201 zero_size++; 8202 if (zero_size >= key_size) { 8203 *value = 0; 8204 return 0; 8205 } 8206 8207 /* Check that stack contains a scalar spill of expected size */ 8208 if (!bpf_is_spilled_scalar_reg(&state->stack[spi])) 8209 return -EOPNOTSUPP; 8210 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) 8211 spill_size++; 8212 if (spill_size != key_size) 8213 return -EOPNOTSUPP; 8214 8215 reg = &state->stack[spi].spilled_ptr; 8216 if (!tnum_is_const(reg->var_off)) 8217 /* Stack value not statically known */ 8218 return -EOPNOTSUPP; 8219 8220 /* We are relying on a constant value. So mark as precise 8221 * to prevent pruning on it. 8222 */ 8223 bpf_bt_set_frame_slot(&env->bt, key->frameno, spi); 8224 err = mark_chain_precision_batch(env, env->cur_state); 8225 if (err < 0) 8226 return err; 8227 8228 *value = reg->var_off.value; 8229 return 0; 8230 } 8231 8232 static bool can_elide_value_nullness(const struct bpf_map *map); 8233 8234 static int process_map_ptr_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 8235 argno_t argno, struct bpf_call_arg_meta *meta) 8236 { 8237 /* Use map_uid (which is unique id of inner map) to reject: 8238 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8239 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8240 * if (inner_map1 && inner_map2) { 8241 * timer = bpf_map_lookup_elem(inner_map1); 8242 * if (timer) 8243 * // mismatch would have been allowed 8244 * bpf_timer_init(timer, inner_map2); 8245 * } 8246 * 8247 * Comparing map_ptr is enough to distinguish normal and outer maps. 8248 */ 8249 if (meta->map.ptr && 8250 (meta->map.ptr != reg->map_ptr || meta->map.uid != reg->map_uid)) { 8251 argno_t obj_argno = argno_from_reg(reg_from_argno(argno) - 1); 8252 struct btf_record *rec = meta->map.ptr->record; 8253 const char *obj_name = "workqueue"; 8254 8255 if (rec->timer_off >= 0) 8256 obj_name = "timer"; 8257 else if (rec->task_work_off >= 0) 8258 obj_name = "bpf_task_work"; 8259 8260 verbose(env, "%s pointer in %s map_uid=%d ", 8261 obj_name, reg_arg_name(env, obj_argno), meta->map.uid); 8262 verbose(env, "doesn't match map pointer in %s map_uid=%d\n", 8263 reg_arg_name(env, argno), reg->map_uid); 8264 return -EINVAL; 8265 } 8266 8267 meta->map.ptr = reg->map_ptr; 8268 meta->map.uid = reg->map_uid; 8269 return 0; 8270 } 8271 8272 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8273 struct bpf_call_arg_meta *meta, 8274 int insn_idx) 8275 { 8276 const struct bpf_func_proto *fn = meta->fn; 8277 u32 regno = BPF_REG_1 + arg; 8278 struct bpf_reg_state *reg = reg_state(env, regno); 8279 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8280 argno_t argno = argno_from_reg(regno); 8281 enum bpf_reg_type type = reg->type; 8282 u32 *arg_btf_id = NULL; 8283 u32 key_size; 8284 int err = 0; 8285 8286 if (arg_type == ARG_DONTCARE) 8287 return 0; 8288 8289 err = check_reg_arg(env, regno, SRC_OP); 8290 if (err) 8291 return err; 8292 8293 if (arg_type == ARG_ANYTHING) { 8294 if (is_pointer_value(env, regno)) { 8295 verbose(env, "R%d leaks addr into helper function\n", 8296 regno); 8297 return -EACCES; 8298 } 8299 return 0; 8300 } 8301 8302 if (type_is_pkt_pointer(type) && 8303 !may_access_direct_pkt_data(env, fn, BPF_READ)) { 8304 verbose(env, "helper access to the packet is not allowed\n"); 8305 return -EACCES; 8306 } 8307 8308 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8309 err = resolve_map_arg_type(env, meta, &arg_type); 8310 if (err) 8311 return err; 8312 } 8313 8314 if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) 8315 /* A NULL register has a SCALAR_VALUE type, so skip 8316 * type checking. 8317 */ 8318 goto skip_type_check; 8319 8320 /* arg_btf_id and arg_size are in a union. */ 8321 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8322 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8323 arg_btf_id = fn->arg_btf_id[arg]; 8324 8325 err = check_reg_type(env, reg, argno, arg_type, arg_btf_id, meta); 8326 if (err) 8327 return err; 8328 8329 err = check_func_arg_reg_off(env, reg, argno, arg_type); 8330 if (err) 8331 return err; 8332 8333 skip_type_check: 8334 if (arg_type_is_release(arg_type) && !arg_type_is_dynptr(arg_type) && 8335 !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) { 8336 verbose(env, "release helper %s expects referenced PTR_TO_BTF_ID passed to %s\n", 8337 func_id_name(meta->func_id), reg_arg_name(env, argno)); 8338 return -EINVAL; 8339 } 8340 8341 if (reg_is_referenced(env, reg)) 8342 update_ref_obj(&meta->ref_obj, reg); 8343 8344 switch (base_type(arg_type)) { 8345 case ARG_CONST_MAP_PTR: 8346 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8347 err = process_map_ptr_arg(env, reg, argno, meta); 8348 if (err) 8349 return err; 8350 break; 8351 case ARG_PTR_TO_MAP_KEY: 8352 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8353 * check that [key, key + map->key_size) are within 8354 * stack limits and initialized 8355 */ 8356 if (!meta->map.ptr) { 8357 /* in function declaration map_ptr must come before 8358 * map_key, so that it's verified and known before 8359 * we have to check map_key here. Otherwise it means 8360 * that kernel subsystem misconfigured verifier 8361 */ 8362 verifier_bug(env, "invalid map_ptr to access map->key"); 8363 return -EFAULT; 8364 } 8365 key_size = meta->map.ptr->key_size; 8366 err = check_helper_mem_access(env, reg, argno, key_size, BPF_READ, false, NULL); 8367 if (err) 8368 return err; 8369 if (can_elide_value_nullness(meta->map.ptr)) { 8370 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key); 8371 if (err < 0) { 8372 meta->const_map_key = -1; 8373 if (err == -EOPNOTSUPP) 8374 err = 0; 8375 else 8376 return err; 8377 } 8378 } 8379 break; 8380 case ARG_PTR_TO_MAP_VALUE: 8381 if (type_may_be_null(arg_type) && bpf_register_is_null(reg)) 8382 return 0; 8383 8384 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8385 * check [value, value + map->value_size) validity 8386 */ 8387 if (!meta->map.ptr) { 8388 /* kernel subsystem misconfigured verifier */ 8389 verifier_bug(env, "invalid map_ptr to access map->value"); 8390 return -EFAULT; 8391 } 8392 8393 /* 8394 * Disable raw mode for bpf_map_peek_elem() on a bloom filter. The helper reads 8395 * the value buffer as an input rather than filling it. 8396 */ 8397 if (meta->func_id == BPF_FUNC_map_peek_elem && 8398 meta->map.ptr->map_type == BPF_MAP_TYPE_BLOOM_FILTER) 8399 meta->arg_raw_mem.regno = 0; 8400 8401 err = check_helper_mem_access(env, reg, argno, meta->map.ptr->value_size, 8402 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8403 false, meta); 8404 break; 8405 case ARG_PTR_TO_PERCPU_BTF_ID: 8406 if (!reg->btf_id) { 8407 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8408 return -EACCES; 8409 } 8410 meta->ret_btf = reg->btf; 8411 meta->ret_btf_id = reg->btf_id; 8412 break; 8413 case ARG_PTR_TO_SPIN_LOCK: 8414 if (in_rbtree_lock_required_cb(env)) { 8415 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8416 return -EACCES; 8417 } 8418 if (meta->func_id == BPF_FUNC_spin_lock) { 8419 err = process_spin_lock(env, reg, argno, PROCESS_SPIN_LOCK); 8420 if (err) 8421 return err; 8422 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8423 err = process_spin_lock(env, reg, argno, 0); 8424 if (err) 8425 return err; 8426 } else { 8427 verifier_bug(env, "spin lock arg on unexpected helper"); 8428 return -EFAULT; 8429 } 8430 break; 8431 case ARG_PTR_TO_TIMER: 8432 err = process_timer_func(env, reg, argno, &meta->map); 8433 if (err) 8434 return err; 8435 break; 8436 case ARG_PTR_TO_FUNC: 8437 meta->subprogno = reg->subprogno; 8438 break; 8439 case ARG_PTR_TO_MEM: 8440 /* The access to this pointer is only checked when we hit the 8441 * next is_mem_size argument below. 8442 */ 8443 if (arg_type & MEM_FIXED_SIZE) { 8444 err = check_mem_reg(env, reg, argno_from_reg(regno), fn->arg_size[arg], 8445 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, meta); 8446 if (err) 8447 return err; 8448 if (arg_type & MEM_ALIGNED) 8449 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 8450 } 8451 break; 8452 case ARG_MEM_SIZE: 8453 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, 8454 argno_from_reg(regno - 1), argno, 8455 fn->arg_type[arg - 1] & MEM_WRITE ? BPF_WRITE : BPF_READ, 8456 false, meta); 8457 break; 8458 case ARG_MEM_SIZE_OR_ZERO: 8459 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, 8460 argno_from_reg(regno - 1), argno, 8461 fn->arg_type[arg - 1] & MEM_WRITE ? BPF_WRITE : BPF_READ, 8462 true, meta); 8463 break; 8464 case ARG_PTR_TO_DYNPTR: 8465 err = process_dynptr_func(env, reg, argno, insn_idx, arg_type, &meta->ref_obj, 8466 &meta->dynptr); 8467 if (err) 8468 return err; 8469 break; 8470 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8471 err = process_const_alloc_mem_size(env, reg, argno, &meta->ret_mem); 8472 if (err) 8473 return err; 8474 break; 8475 case ARG_PTR_TO_CONST_STR: 8476 { 8477 err = check_arg_const_str(env, reg, argno); 8478 if (err) 8479 return err; 8480 break; 8481 } 8482 case ARG_KPTR_XCHG_DEST: 8483 err = process_kptr_func(env, regno, meta); 8484 if (err) 8485 return err; 8486 break; 8487 } 8488 8489 return err; 8490 } 8491 8492 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8493 { 8494 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8495 enum bpf_prog_type type = resolve_prog_type(env->prog); 8496 8497 if (func_id != BPF_FUNC_map_update_elem && 8498 func_id != BPF_FUNC_map_delete_elem) 8499 return false; 8500 8501 /* It's not possible to get access to a locked struct sock in these 8502 * contexts, so updating is safe. 8503 */ 8504 switch (type) { 8505 case BPF_PROG_TYPE_TRACING: 8506 if (eatype == BPF_TRACE_ITER) 8507 return true; 8508 break; 8509 case BPF_PROG_TYPE_SOCK_OPS: 8510 /* map_update allowed only via dedicated helpers with event type checks */ 8511 if (func_id == BPF_FUNC_map_delete_elem) 8512 return true; 8513 break; 8514 case BPF_PROG_TYPE_SK_REUSEPORT: 8515 case BPF_PROG_TYPE_SK_LOOKUP: 8516 return true; 8517 default: 8518 break; 8519 } 8520 8521 verbose(env, "cannot update sockmap in this context\n"); 8522 return false; 8523 } 8524 8525 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8526 { 8527 return env->prog->jit_requested && 8528 bpf_jit_supports_subprog_tailcalls(); 8529 } 8530 8531 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8532 struct bpf_map *map, int func_id) 8533 { 8534 if (!map) 8535 return 0; 8536 8537 /* We need a two way check, first is from map perspective ... */ 8538 switch (map->map_type) { 8539 case BPF_MAP_TYPE_PROG_ARRAY: 8540 if (func_id != BPF_FUNC_tail_call) 8541 goto error; 8542 break; 8543 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8544 if (func_id != BPF_FUNC_perf_event_read && 8545 func_id != BPF_FUNC_perf_event_output && 8546 func_id != BPF_FUNC_skb_output && 8547 func_id != BPF_FUNC_perf_event_read_value && 8548 func_id != BPF_FUNC_xdp_output) 8549 goto error; 8550 break; 8551 case BPF_MAP_TYPE_RINGBUF: 8552 if (func_id != BPF_FUNC_ringbuf_output && 8553 func_id != BPF_FUNC_ringbuf_reserve && 8554 func_id != BPF_FUNC_ringbuf_query && 8555 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8556 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8557 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8558 goto error; 8559 break; 8560 case BPF_MAP_TYPE_USER_RINGBUF: 8561 if (func_id != BPF_FUNC_user_ringbuf_drain) 8562 goto error; 8563 break; 8564 case BPF_MAP_TYPE_STACK_TRACE: 8565 if (func_id != BPF_FUNC_get_stackid) 8566 goto error; 8567 break; 8568 case BPF_MAP_TYPE_CGROUP_ARRAY: 8569 if (func_id != BPF_FUNC_skb_under_cgroup && 8570 func_id != BPF_FUNC_current_task_under_cgroup) 8571 goto error; 8572 break; 8573 case BPF_MAP_TYPE_CGROUP_STORAGE: 8574 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8575 if (func_id != BPF_FUNC_get_local_storage) 8576 goto error; 8577 break; 8578 case BPF_MAP_TYPE_DEVMAP: 8579 case BPF_MAP_TYPE_DEVMAP_HASH: 8580 if (func_id != BPF_FUNC_redirect_map && 8581 func_id != BPF_FUNC_map_lookup_elem) 8582 goto error; 8583 break; 8584 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8585 * appear. 8586 */ 8587 case BPF_MAP_TYPE_CPUMAP: 8588 if (func_id != BPF_FUNC_redirect_map) 8589 goto error; 8590 break; 8591 case BPF_MAP_TYPE_XSKMAP: 8592 if (func_id != BPF_FUNC_redirect_map && 8593 func_id != BPF_FUNC_map_lookup_elem) 8594 goto error; 8595 break; 8596 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8597 case BPF_MAP_TYPE_HASH_OF_MAPS: 8598 if (func_id != BPF_FUNC_map_lookup_elem) 8599 goto error; 8600 break; 8601 case BPF_MAP_TYPE_SOCKMAP: 8602 if (func_id != BPF_FUNC_sk_redirect_map && 8603 func_id != BPF_FUNC_sock_map_update && 8604 func_id != BPF_FUNC_msg_redirect_map && 8605 func_id != BPF_FUNC_sk_select_reuseport && 8606 func_id != BPF_FUNC_map_lookup_elem && 8607 !may_update_sockmap(env, func_id)) 8608 goto error; 8609 break; 8610 case BPF_MAP_TYPE_SOCKHASH: 8611 if (func_id != BPF_FUNC_sk_redirect_hash && 8612 func_id != BPF_FUNC_sock_hash_update && 8613 func_id != BPF_FUNC_msg_redirect_hash && 8614 func_id != BPF_FUNC_sk_select_reuseport && 8615 func_id != BPF_FUNC_map_lookup_elem && 8616 !may_update_sockmap(env, func_id)) 8617 goto error; 8618 break; 8619 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8620 if (func_id != BPF_FUNC_sk_select_reuseport) 8621 goto error; 8622 break; 8623 case BPF_MAP_TYPE_QUEUE: 8624 case BPF_MAP_TYPE_STACK: 8625 if (func_id != BPF_FUNC_map_peek_elem && 8626 func_id != BPF_FUNC_map_pop_elem && 8627 func_id != BPF_FUNC_map_push_elem) 8628 goto error; 8629 break; 8630 case BPF_MAP_TYPE_SK_STORAGE: 8631 if (func_id != BPF_FUNC_sk_storage_get && 8632 func_id != BPF_FUNC_sk_storage_delete && 8633 func_id != BPF_FUNC_kptr_xchg) 8634 goto error; 8635 break; 8636 case BPF_MAP_TYPE_INODE_STORAGE: 8637 if (func_id != BPF_FUNC_inode_storage_get && 8638 func_id != BPF_FUNC_inode_storage_delete && 8639 func_id != BPF_FUNC_kptr_xchg) 8640 goto error; 8641 break; 8642 case BPF_MAP_TYPE_TASK_STORAGE: 8643 if (func_id != BPF_FUNC_task_storage_get && 8644 func_id != BPF_FUNC_task_storage_delete && 8645 func_id != BPF_FUNC_kptr_xchg) 8646 goto error; 8647 break; 8648 case BPF_MAP_TYPE_CGRP_STORAGE: 8649 if (func_id != BPF_FUNC_cgrp_storage_get && 8650 func_id != BPF_FUNC_cgrp_storage_delete && 8651 func_id != BPF_FUNC_kptr_xchg) 8652 goto error; 8653 break; 8654 case BPF_MAP_TYPE_BLOOM_FILTER: 8655 if (func_id != BPF_FUNC_map_peek_elem && 8656 func_id != BPF_FUNC_map_push_elem) 8657 goto error; 8658 break; 8659 case BPF_MAP_TYPE_INSN_ARRAY: 8660 goto error; 8661 default: 8662 break; 8663 } 8664 8665 /* ... and second from the function itself. */ 8666 switch (func_id) { 8667 case BPF_FUNC_tail_call: 8668 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8669 goto error; 8670 if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) { 8671 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n"); 8672 return -EINVAL; 8673 } 8674 break; 8675 case BPF_FUNC_perf_event_read: 8676 case BPF_FUNC_perf_event_output: 8677 case BPF_FUNC_perf_event_read_value: 8678 case BPF_FUNC_skb_output: 8679 case BPF_FUNC_xdp_output: 8680 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8681 goto error; 8682 break; 8683 case BPF_FUNC_ringbuf_output: 8684 case BPF_FUNC_ringbuf_reserve: 8685 case BPF_FUNC_ringbuf_query: 8686 case BPF_FUNC_ringbuf_reserve_dynptr: 8687 case BPF_FUNC_ringbuf_submit_dynptr: 8688 case BPF_FUNC_ringbuf_discard_dynptr: 8689 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8690 goto error; 8691 break; 8692 case BPF_FUNC_user_ringbuf_drain: 8693 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8694 goto error; 8695 break; 8696 case BPF_FUNC_get_stackid: 8697 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8698 goto error; 8699 break; 8700 case BPF_FUNC_current_task_under_cgroup: 8701 case BPF_FUNC_skb_under_cgroup: 8702 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8703 goto error; 8704 break; 8705 case BPF_FUNC_redirect_map: 8706 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8707 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8708 map->map_type != BPF_MAP_TYPE_CPUMAP && 8709 map->map_type != BPF_MAP_TYPE_XSKMAP) 8710 goto error; 8711 break; 8712 case BPF_FUNC_sk_redirect_map: 8713 case BPF_FUNC_msg_redirect_map: 8714 case BPF_FUNC_sock_map_update: 8715 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8716 goto error; 8717 break; 8718 case BPF_FUNC_sk_redirect_hash: 8719 case BPF_FUNC_msg_redirect_hash: 8720 case BPF_FUNC_sock_hash_update: 8721 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8722 goto error; 8723 break; 8724 case BPF_FUNC_get_local_storage: 8725 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8726 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8727 goto error; 8728 break; 8729 case BPF_FUNC_sk_select_reuseport: 8730 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8731 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8732 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8733 goto error; 8734 break; 8735 case BPF_FUNC_map_pop_elem: 8736 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8737 map->map_type != BPF_MAP_TYPE_STACK) 8738 goto error; 8739 break; 8740 case BPF_FUNC_map_peek_elem: 8741 case BPF_FUNC_map_push_elem: 8742 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8743 map->map_type != BPF_MAP_TYPE_STACK && 8744 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8745 goto error; 8746 break; 8747 case BPF_FUNC_map_lookup_percpu_elem: 8748 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8749 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8750 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8751 goto error; 8752 break; 8753 case BPF_FUNC_sk_storage_get: 8754 case BPF_FUNC_sk_storage_delete: 8755 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8756 goto error; 8757 break; 8758 case BPF_FUNC_inode_storage_get: 8759 case BPF_FUNC_inode_storage_delete: 8760 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8761 goto error; 8762 break; 8763 case BPF_FUNC_task_storage_get: 8764 case BPF_FUNC_task_storage_delete: 8765 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8766 goto error; 8767 break; 8768 case BPF_FUNC_cgrp_storage_get: 8769 case BPF_FUNC_cgrp_storage_delete: 8770 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8771 goto error; 8772 break; 8773 default: 8774 break; 8775 } 8776 8777 return 0; 8778 error: 8779 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8780 map->map_type, func_id_name(func_id), func_id); 8781 return -EINVAL; 8782 } 8783 8784 static bool check_raw_mode_ok(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8785 { 8786 int i; 8787 8788 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8789 if (fn->arg_type[i] == ARG_DONTCARE) 8790 break; 8791 if (!arg_type_is_raw_mem(fn->arg_type[i])) 8792 continue; 8793 if (meta->arg_raw_mem.regno) 8794 return false; 8795 meta->arg_raw_mem.regno = i + 1; 8796 } 8797 8798 return true; 8799 } 8800 8801 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8802 { 8803 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8804 bool has_size = fn->arg_size[arg] != 0; 8805 bool is_next_size = false; 8806 8807 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8808 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8809 8810 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8811 return is_next_size; 8812 8813 return has_size == is_next_size || is_next_size == is_fixed; 8814 } 8815 8816 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8817 { 8818 /* bpf_xxx(..., buf, len) call will access 'len' 8819 * bytes from memory 'buf'. Both arg types need 8820 * to be paired, so make sure there's no buggy 8821 * helper function specification. 8822 */ 8823 if (arg_type_is_mem_size(fn->arg1_type) || 8824 check_args_pair_invalid(fn, 0) || 8825 check_args_pair_invalid(fn, 1) || 8826 check_args_pair_invalid(fn, 2) || 8827 check_args_pair_invalid(fn, 3) || 8828 check_args_pair_invalid(fn, 4)) 8829 return false; 8830 8831 return true; 8832 } 8833 8834 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8835 { 8836 int i; 8837 8838 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8839 if (fn->arg_type[i] == ARG_DONTCARE) 8840 break; 8841 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8842 return !!fn->arg_btf_id[i]; 8843 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8844 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8845 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8846 /* arg_btf_id and arg_size are in a union. */ 8847 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8848 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8849 return false; 8850 } 8851 8852 return true; 8853 } 8854 8855 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn) 8856 { 8857 int i; 8858 8859 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8860 enum bpf_arg_type arg_type = fn->arg_type[i]; 8861 8862 if (arg_type == ARG_DONTCARE) 8863 break; 8864 if (base_type(arg_type) != ARG_PTR_TO_MEM) 8865 continue; 8866 if (!(arg_type & (MEM_WRITE | MEM_RDONLY))) 8867 return false; 8868 } 8869 8870 return true; 8871 } 8872 8873 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8874 { 8875 int i; 8876 8877 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8878 enum bpf_arg_type arg_type = fn->arg_type[i]; 8879 8880 if (arg_type == ARG_DONTCARE) 8881 break; 8882 if (arg_type_is_release(arg_type)) { 8883 if (meta->release_regno) 8884 return false; 8885 meta->release_regno = i + 1; 8886 } 8887 } 8888 8889 return true; 8890 } 8891 8892 static int check_func_proto(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8893 { 8894 return check_raw_mode_ok(fn, meta) && 8895 check_arg_pair_ok(fn) && 8896 check_mem_arg_rw_flag_ok(fn) && 8897 check_proto_release_reg(fn, meta) && 8898 check_btf_id_ok(fn) ? 0 : -EINVAL; 8899 } 8900 8901 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8902 * are now invalid, so turn them into unknown SCALAR_VALUE. 8903 * 8904 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8905 * since these slices point to packet data. 8906 */ 8907 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8908 { 8909 struct bpf_func_state *state; 8910 struct bpf_reg_state *reg; 8911 8912 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8913 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8914 mark_reg_invalid(env, reg); 8915 })); 8916 } 8917 8918 enum { 8919 AT_PKT_END = -1, 8920 BEYOND_PKT_END = -2, 8921 }; 8922 8923 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8924 { 8925 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8926 struct bpf_reg_state *reg = &state->regs[regn]; 8927 8928 if (reg->type != PTR_TO_PACKET) 8929 /* PTR_TO_PACKET_META is not supported yet */ 8930 return; 8931 8932 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8933 * How far beyond pkt_end it goes is unknown. 8934 * if (!range_open) it's the case of pkt >= pkt_end 8935 * if (range_open) it's the case of pkt > pkt_end 8936 * hence this pointer is at least 1 byte bigger than pkt_end 8937 */ 8938 if (range_open) 8939 reg->range = BEYOND_PKT_END; 8940 else 8941 reg->range = AT_PKT_END; 8942 } 8943 8944 static int release_reference_nomark(struct bpf_verifier_state *state, int id) 8945 { 8946 int i; 8947 8948 for (i = 0; i < state->acquired_refs; i++) { 8949 if (state->refs[i].type != REF_TYPE_PTR) 8950 continue; 8951 if (state->refs[i].id == id) { 8952 release_reference_state(state, i); 8953 return 0; 8954 } 8955 } 8956 return -EINVAL; 8957 } 8958 8959 static int idstack_push(struct bpf_idmap *idmap, u32 id) 8960 { 8961 int i; 8962 8963 if (!id) 8964 return 0; 8965 8966 for (i = 0; i < idmap->cnt; i++) 8967 if (idmap->map[i].old == id) 8968 return 0; 8969 8970 if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE)) 8971 return -EFAULT; 8972 8973 idmap->map[idmap->cnt++].old = id; 8974 return 0; 8975 } 8976 8977 static int idstack_pop(struct bpf_idmap *idmap) 8978 { 8979 if (!idmap->cnt) 8980 return 0; 8981 8982 return idmap->map[--idmap->cnt].old; 8983 } 8984 8985 /* Release id and objects derived from it iteratively in a DFS manner */ 8986 static int release_reference(struct bpf_verifier_env *env, int id) 8987 { 8988 u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR); 8989 struct bpf_verifier_state *vstate = env->cur_state; 8990 struct bpf_idmap *idstack = &env->idmap_scratch; 8991 struct bpf_stack_state *stack; 8992 struct bpf_func_state *state; 8993 struct bpf_reg_state *reg; 8994 int i, err; 8995 8996 idstack->cnt = 0; 8997 err = idstack_push(idstack, id); 8998 if (err) 8999 return err; 9000 9001 if (find_reference_state(vstate, id)) 9002 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 9003 9004 while ((id = idstack_pop(idstack))) { 9005 /* 9006 * Child references are inaccessible after parent is released, 9007 * any child references that exist at this point are a leak. 9008 */ 9009 for (i = 0; i < vstate->acquired_refs; i++) { 9010 if (vstate->refs[i].type != REF_TYPE_PTR) 9011 continue; 9012 if (vstate->refs[i].parent_id != id) 9013 continue; 9014 verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n", 9015 vstate->refs[i].id, vstate->refs[i].insn_idx); 9016 return -EINVAL; 9017 } 9018 9019 bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({ 9020 if (reg->id != id && reg->parent_id != id) 9021 continue; 9022 9023 /* Free objects derived from the current object */ 9024 if (reg->parent_id == id) { 9025 err = idstack_push(idstack, reg->id); 9026 if (err) 9027 return err; 9028 } 9029 9030 if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL) 9031 mark_reg_invalid(env, reg); 9032 else if (stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR) 9033 invalidate_dynptr(env, stack); 9034 })); 9035 } 9036 9037 return 0; 9038 } 9039 9040 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9041 { 9042 struct bpf_func_state *unused; 9043 struct bpf_reg_state *reg; 9044 9045 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9046 if (type_is_non_owning_ref(reg->type)) 9047 mark_reg_invalid(env, reg); 9048 })); 9049 } 9050 9051 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env) 9052 { 9053 struct bpf_stack_state *stack; 9054 struct bpf_func_state *state; 9055 struct bpf_reg_state *reg; 9056 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 9057 9058 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({ 9059 if (reg->type & MEM_RCU) { 9060 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 9061 reg->type |= PTR_UNTRUSTED; 9062 } 9063 })); 9064 } 9065 9066 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id) 9067 { 9068 struct bpf_func_state *state; 9069 struct bpf_reg_state *reg; 9070 int err; 9071 9072 err = release_reference_nomark(env->cur_state, id); 9073 9074 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9075 if (reg->id != id) 9076 continue; 9077 if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 9078 reg->id = 0; 9079 reg->type &= ~MEM_ALLOC; 9080 reg->type |= MEM_RCU; 9081 } 9082 })); 9083 9084 return err; 9085 } 9086 9087 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9088 struct bpf_reg_state *regs) 9089 { 9090 int i; 9091 9092 /* after the call registers r0 - r5 were scratched */ 9093 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9094 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 9095 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9096 } 9097 } 9098 9099 static void invalidate_outgoing_stack_args(const struct bpf_verifier_env *env, 9100 struct bpf_func_state *state) 9101 { 9102 int i, nslots = state->out_stack_arg_cnt; 9103 9104 for (i = 0; i < nslots; i++) 9105 bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]); 9106 } 9107 9108 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9109 struct bpf_func_state *caller, 9110 struct bpf_func_state *callee, 9111 int insn_idx); 9112 9113 static int set_callee_state(struct bpf_verifier_env *env, 9114 struct bpf_func_state *caller, 9115 struct bpf_func_state *callee, int insn_idx); 9116 9117 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9118 set_callee_state_fn set_callee_state_cb, 9119 struct bpf_verifier_state *state) 9120 { 9121 struct bpf_func_state *caller, *callee; 9122 int err; 9123 9124 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9125 verbose(env, "the call stack of %d frames is too deep\n", 9126 state->curframe + 2); 9127 return -E2BIG; 9128 } 9129 9130 if (state->frame[state->curframe + 1]) { 9131 verifier_bug(env, "Frame %d already allocated", state->curframe + 1); 9132 return -EFAULT; 9133 } 9134 9135 caller = state->frame[state->curframe]; 9136 callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT); 9137 if (!callee) 9138 return -ENOMEM; 9139 state->frame[state->curframe + 1] = callee; 9140 9141 /* callee cannot access r0, r6 - r9 for reading and has to write 9142 * into its own stack before reading from it. 9143 * callee can read/write into caller's stack 9144 */ 9145 init_func_state(env, callee, 9146 /* remember the callsite, it will be used by bpf_exit */ 9147 callsite, 9148 state->curframe + 1 /* frameno within this callchain */, 9149 subprog /* subprog number within this prog */); 9150 err = set_callee_state_cb(env, caller, callee, callsite); 9151 if (err) 9152 goto err_out; 9153 9154 /* only increment it after check_reg_arg() finished */ 9155 state->curframe++; 9156 9157 return 0; 9158 9159 err_out: 9160 free_func_state(callee); 9161 state->frame[state->curframe + 1] = NULL; 9162 return err; 9163 } 9164 9165 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9166 const struct btf *btf, 9167 struct bpf_reg_state *regs) 9168 { 9169 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9170 struct bpf_func_state *caller = cur_func(env); 9171 struct bpf_verifier_log *log = &env->log; 9172 struct ref_obj_desc ref_obj = {}; 9173 u32 i; 9174 int ret, err; 9175 9176 ret = btf_prepare_func_args(env, subprog); 9177 if (ret) { 9178 if (bpf_in_stack_arg_cnt(sub) > 0) { 9179 err = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9180 if (err) 9181 return err; 9182 } 9183 return ret; 9184 } 9185 9186 ret = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9187 if (ret) 9188 return ret; 9189 9190 /* check that BTF function arguments match actual types that the 9191 * verifier sees. 9192 */ 9193 for (i = 0; i < sub->arg_cnt; i++) { 9194 argno_t argno = argno_from_arg(i + 1); 9195 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 9196 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9197 9198 if (arg->arg_type == ARG_ANYTHING) { 9199 if (reg->type != SCALAR_VALUE) { 9200 bpf_log(log, "%s is not a scalar\n", reg_arg_name(env, argno)); 9201 return -EINVAL; 9202 } 9203 } else if (arg->arg_type & PTR_UNTRUSTED) { 9204 /* 9205 * Anything is allowed for untrusted arguments, as these are 9206 * read-only and probe read instructions would protect against 9207 * invalid memory access. 9208 */ 9209 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9210 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_CTX); 9211 if (ret < 0) 9212 return ret; 9213 /* If function expects ctx type in BTF check that caller 9214 * is passing PTR_TO_CTX. 9215 */ 9216 if (reg->type != PTR_TO_CTX) { 9217 bpf_log(log, "%s expects pointer to ctx\n", 9218 reg_arg_name(env, argno)); 9219 return -EINVAL; 9220 } 9221 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9222 ret = check_func_arg_reg_off(env, reg, argno, ARG_DONTCARE); 9223 if (ret < 0) 9224 return ret; 9225 if (check_mem_reg(env, reg, argno, arg->mem_size, BPF_READ | BPF_WRITE, NULL)) 9226 return -EINVAL; 9227 if (!(arg->arg_type & PTR_MAYBE_NULL) && 9228 (type_may_be_null(reg->type) || bpf_register_is_null(reg))) { 9229 bpf_log(log, "%s is expected to be non-NULL\n", 9230 reg_arg_name(env, argno)); 9231 return -EINVAL; 9232 } 9233 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9234 /* 9235 * Can pass any value and the kernel won't crash, but 9236 * only PTR_TO_ARENA or SCALAR make sense. Everything 9237 * else is a bug in the bpf program. Point it out to 9238 * the user at the verification time instead of 9239 * run-time debug nightmare. 9240 */ 9241 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9242 bpf_log(log, "%s is not a pointer to arena or scalar.\n", 9243 reg_arg_name(env, argno)); 9244 return -EINVAL; 9245 } 9246 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 9247 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_DYNPTR); 9248 if (ret) 9249 return ret; 9250 9251 ret = process_dynptr_func(env, reg, argno, -1, arg->arg_type, &ref_obj, NULL); 9252 if (ret) 9253 return ret; 9254 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9255 struct bpf_call_arg_meta meta; 9256 int err; 9257 9258 if (bpf_register_is_null(reg) && type_may_be_null(arg->arg_type)) 9259 continue; 9260 9261 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9262 err = check_reg_type(env, reg, argno, arg->arg_type, &arg->btf_id, &meta); 9263 err = err ?: check_func_arg_reg_off(env, reg, argno, arg->arg_type); 9264 if (err) 9265 return err; 9266 } else { 9267 verifier_bug(env, "unrecognized %s type %d", 9268 reg_arg_name(env, argno), arg->arg_type); 9269 return -EFAULT; 9270 } 9271 } 9272 9273 return 0; 9274 } 9275 9276 /* Compare BTF of a function call with given bpf_reg_state. 9277 * Returns: 9278 * EFAULT - there is a verifier bug. Abort verification. 9279 * EINVAL - there is a type mismatch or BTF is not available. 9280 * 0 - BTF matches with what bpf_reg_state expects. 9281 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9282 */ 9283 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9284 struct bpf_reg_state *regs) 9285 { 9286 struct bpf_prog *prog = env->prog; 9287 struct btf *btf = prog->aux->btf; 9288 u32 btf_id; 9289 int err; 9290 9291 if (!prog->aux->func_info) 9292 return -EINVAL; 9293 9294 btf_id = prog->aux->func_info[subprog].type_id; 9295 if (!btf_id) 9296 return -EFAULT; 9297 9298 if (prog->aux->func_info_aux[subprog].unreliable) 9299 return -EINVAL; 9300 9301 err = btf_check_func_arg_match(env, subprog, btf, regs); 9302 /* Compiler optimizations can remove arguments from static functions 9303 * or mismatched type can be passed into a global function. 9304 * In such cases mark the function as unreliable from BTF point of view. 9305 */ 9306 if (err) 9307 prog->aux->func_info_aux[subprog].unreliable = true; 9308 return err; 9309 } 9310 9311 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9312 int insn_idx, int subprog, 9313 set_callee_state_fn set_callee_state_cb) 9314 { 9315 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9316 struct bpf_func_state *caller, *callee; 9317 int err; 9318 9319 caller = state->frame[state->curframe]; 9320 err = btf_check_subprog_call(env, subprog, caller->regs); 9321 if (err == -EFAULT) 9322 return err; 9323 9324 /* set_callee_state is used for direct subprog calls, but we are 9325 * interested in validating only BPF helpers that can call subprogs as 9326 * callbacks 9327 */ 9328 env->subprog_info[subprog].is_cb = true; 9329 if (bpf_pseudo_kfunc_call(insn) && 9330 !is_callback_calling_kfunc(insn->imm)) { 9331 verifier_bug(env, "kfunc %s#%d not marked as callback-calling", 9332 func_id_name(insn->imm), insn->imm); 9333 return -EFAULT; 9334 } else if (!bpf_pseudo_kfunc_call(insn) && 9335 !is_callback_calling_function(insn->imm)) { /* helper */ 9336 verifier_bug(env, "helper %s#%d not marked as callback-calling", 9337 func_id_name(insn->imm), insn->imm); 9338 return -EFAULT; 9339 } 9340 9341 if (bpf_is_async_callback_calling_insn(insn)) { 9342 struct bpf_verifier_state *async_cb; 9343 9344 /* there is no real recursion here. timer and workqueue callbacks are async */ 9345 env->subprog_info[subprog].is_async_cb = true; 9346 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9347 insn_idx, subprog, 9348 is_async_cb_sleepable(env, insn)); 9349 if (IS_ERR(async_cb)) 9350 return PTR_ERR(async_cb); 9351 callee = async_cb->frame[0]; 9352 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9353 9354 /* Convert bpf_timer_set_callback() args into timer callback args */ 9355 err = set_callee_state_cb(env, caller, callee, insn_idx); 9356 if (err) 9357 return err; 9358 9359 return 0; 9360 } 9361 9362 /* for callback functions enqueue entry to callback and 9363 * proceed with next instruction within current frame. 9364 */ 9365 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9366 if (IS_ERR(callback_state)) 9367 return PTR_ERR(callback_state); 9368 9369 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9370 callback_state); 9371 if (err) 9372 return err; 9373 9374 callback_state->callback_unroll_depth++; 9375 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9376 caller->callback_depth = 0; 9377 return 0; 9378 } 9379 9380 static int process_bpf_exit_full(struct bpf_verifier_env *env, 9381 bool *do_print_state, bool exception_exit); 9382 9383 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9384 int *insn_idx) 9385 { 9386 struct bpf_verifier_state *state = env->cur_state; 9387 struct bpf_subprog_info *caller_info; 9388 u16 callee_incoming, stack_arg_cnt; 9389 struct bpf_func_state *caller; 9390 int err, subprog, target_insn; 9391 9392 target_insn = *insn_idx + insn->imm + 1; 9393 subprog = bpf_find_subprog(env, target_insn); 9394 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program", 9395 target_insn)) 9396 return -EFAULT; 9397 9398 caller = state->frame[state->curframe]; 9399 err = btf_check_subprog_call(env, subprog, caller->regs); 9400 if (err == -EFAULT) 9401 return err; 9402 if (bpf_subprog_is_global(env, subprog)) { 9403 const char *sub_name = subprog_name(env, subprog); 9404 9405 if (env->cur_state->active_locks) { 9406 verbose(env, "global function calls are not allowed while holding a lock,\n" 9407 "use static function instead\n"); 9408 return -EINVAL; 9409 } 9410 9411 if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) { 9412 verbose(env, "sleepable global function %s() called in %s\n", 9413 sub_name, non_sleepable_context_description(env)); 9414 return -EINVAL; 9415 } 9416 9417 if (err) { 9418 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9419 subprog, sub_name); 9420 return err; 9421 } 9422 9423 if (env->log.level & BPF_LOG_LEVEL) 9424 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9425 subprog, sub_name); 9426 if (env->subprog_info[subprog].changes_pkt_data) 9427 clear_all_pkt_pointers(env); 9428 /* mark global subprog for verifying after main prog */ 9429 subprog_aux(env, subprog)->called = true; 9430 clear_caller_saved_regs(env, caller->regs); 9431 invalidate_outgoing_stack_args(env, cur_func(env)); 9432 9433 /* All non-void global functions return a 64-bit SCALAR_VALUE. */ 9434 if (!subprog_returns_void(env, subprog)) { 9435 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9436 } 9437 9438 if (env->subprog_info[subprog].might_throw) { 9439 struct bpf_verifier_state *branch; 9440 9441 branch = push_stack(env, *insn_idx + 1, *insn_idx, false); 9442 if (IS_ERR(branch)) { 9443 verbose(env, "failed to push state for global subprog exception path\n"); 9444 return PTR_ERR(branch); 9445 } 9446 return process_bpf_exit_full(env, NULL, true); 9447 } 9448 9449 /* continue with next insn after call */ 9450 return 0; 9451 } 9452 9453 /* 9454 * Track caller's total stack arg count (incoming + max outgoing). 9455 * This is needed so the JIT knows how much stack arg space to allocate. 9456 */ 9457 caller_info = &env->subprog_info[caller->subprogno]; 9458 callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]); 9459 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming; 9460 if (stack_arg_cnt > caller_info->stack_arg_cnt) 9461 caller_info->stack_arg_cnt = stack_arg_cnt; 9462 9463 /* for regular function entry setup new frame and continue 9464 * from that frame. 9465 */ 9466 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9467 if (err) 9468 return err; 9469 9470 clear_caller_saved_regs(env, caller->regs); 9471 9472 /* and go analyze first insn of the callee */ 9473 *insn_idx = env->subprog_info[subprog].start - 1; 9474 9475 if (env->log.level & BPF_LOG_LEVEL) { 9476 verbose(env, "caller:\n"); 9477 print_verifier_state(env, state, caller->frameno, true); 9478 verbose(env, "callee:\n"); 9479 print_verifier_state(env, state, state->curframe, true); 9480 } 9481 9482 return 0; 9483 } 9484 9485 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9486 struct bpf_func_state *caller, 9487 struct bpf_func_state *callee) 9488 { 9489 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9490 * void *callback_ctx, u64 flags); 9491 * callback_fn(struct bpf_map *map, void *key, void *value, 9492 * void *callback_ctx); 9493 */ 9494 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9495 9496 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9497 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9498 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9499 9500 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9501 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9502 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9503 9504 /* pointer to stack or null */ 9505 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9506 9507 /* unused */ 9508 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9509 return 0; 9510 } 9511 9512 static int set_callee_state(struct bpf_verifier_env *env, 9513 struct bpf_func_state *caller, 9514 struct bpf_func_state *callee, int insn_idx) 9515 { 9516 int i; 9517 9518 /* copy r1 - r5 args that callee can access. The copy includes parent 9519 * pointers, which connects us up to the liveness chain 9520 */ 9521 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9522 callee->regs[i] = caller->regs[i]; 9523 return 0; 9524 } 9525 9526 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9527 struct bpf_func_state *caller, 9528 struct bpf_func_state *callee, 9529 int insn_idx) 9530 { 9531 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9532 struct bpf_map *map; 9533 int err; 9534 9535 /* valid map_ptr and poison value does not matter */ 9536 map = insn_aux->map_ptr_state.map_ptr; 9537 if (!map->ops->map_set_for_each_callback_args || 9538 !map->ops->map_for_each_callback) { 9539 verbose(env, "callback function not allowed for map\n"); 9540 return -ENOTSUPP; 9541 } 9542 9543 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9544 if (err) 9545 return err; 9546 9547 callee->in_callback_fn = true; 9548 callee->callback_ret_range = retval_range(0, 1); 9549 return 0; 9550 } 9551 9552 static int set_loop_callback_state(struct bpf_verifier_env *env, 9553 struct bpf_func_state *caller, 9554 struct bpf_func_state *callee, 9555 int insn_idx) 9556 { 9557 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9558 * u64 flags); 9559 * callback_fn(u64 index, void *callback_ctx); 9560 */ 9561 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9562 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9563 9564 /* unused */ 9565 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9566 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9567 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9568 9569 callee->in_callback_fn = true; 9570 callee->callback_ret_range = retval_range(0, 1); 9571 return 0; 9572 } 9573 9574 static int set_timer_callback_state(struct bpf_verifier_env *env, 9575 struct bpf_func_state *caller, 9576 struct bpf_func_state *callee, 9577 int insn_idx) 9578 { 9579 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9580 9581 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9582 * callback_fn(struct bpf_map *map, void *key, void *value); 9583 */ 9584 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9585 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9586 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9587 9588 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9589 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9590 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9591 9592 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9593 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9594 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9595 9596 /* unused */ 9597 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9598 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9599 callee->in_async_callback_fn = true; 9600 callee->callback_ret_range = retval_range(0, 0); 9601 return 0; 9602 } 9603 9604 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9605 struct bpf_func_state *caller, 9606 struct bpf_func_state *callee, 9607 int insn_idx) 9608 { 9609 /* bpf_find_vma(struct task_struct *task, u64 addr, 9610 * void *callback_fn, void *callback_ctx, u64 flags) 9611 * (callback_fn)(struct task_struct *task, 9612 * struct vm_area_struct *vma, void *callback_ctx); 9613 */ 9614 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9615 9616 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9617 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9618 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9619 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9620 9621 /* pointer to stack or null */ 9622 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9623 9624 /* unused */ 9625 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9626 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9627 callee->in_callback_fn = true; 9628 callee->callback_ret_range = retval_range(0, 1); 9629 return 0; 9630 } 9631 9632 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9633 struct bpf_func_state *caller, 9634 struct bpf_func_state *callee, 9635 int insn_idx) 9636 { 9637 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9638 * callback_ctx, u64 flags); 9639 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9640 */ 9641 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9642 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9643 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9644 9645 /* unused */ 9646 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9647 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9648 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9649 9650 callee->in_callback_fn = true; 9651 callee->callback_ret_range = retval_range(0, 1); 9652 return 0; 9653 } 9654 9655 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9656 struct bpf_func_state *caller, 9657 struct bpf_func_state *callee, 9658 int insn_idx) 9659 { 9660 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9661 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9662 * 9663 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9664 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9665 * by this point, so look at 'root' 9666 */ 9667 struct btf_field *field; 9668 9669 field = reg_find_field_offset(&caller->regs[BPF_REG_1], 9670 caller->regs[BPF_REG_1].var_off.value, 9671 BPF_RB_ROOT); 9672 if (!field || !field->graph_root.value_btf_id) 9673 return -EFAULT; 9674 9675 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9676 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9677 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9678 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9679 9680 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9681 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9682 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9683 callee->in_callback_fn = true; 9684 callee->callback_ret_range = retval_range(0, 1); 9685 return 0; 9686 } 9687 9688 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env, 9689 struct bpf_func_state *caller, 9690 struct bpf_func_state *callee, 9691 int insn_idx) 9692 { 9693 struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr; 9694 9695 /* 9696 * callback_fn(struct bpf_map *map, void *key, void *value); 9697 */ 9698 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9699 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9700 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9701 9702 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9703 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9704 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9705 9706 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9707 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9708 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9709 9710 /* unused */ 9711 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9712 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9713 callee->in_async_callback_fn = true; 9714 callee->callback_ret_range = retval_range(S32_MIN, S32_MAX); 9715 return 0; 9716 } 9717 9718 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9719 9720 /* Are we currently verifying the callback for a rbtree helper that must 9721 * be called with lock held? If so, no need to complain about unreleased 9722 * lock 9723 */ 9724 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9725 { 9726 struct bpf_verifier_state *state = env->cur_state; 9727 struct bpf_insn *insn = env->prog->insnsi; 9728 struct bpf_func_state *callee; 9729 int kfunc_btf_id; 9730 9731 if (!state->curframe) 9732 return false; 9733 9734 callee = state->frame[state->curframe]; 9735 9736 if (!callee->in_callback_fn) 9737 return false; 9738 9739 kfunc_btf_id = insn[callee->callsite].imm; 9740 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9741 } 9742 9743 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9744 { 9745 if (range.return_32bit) 9746 return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval; 9747 else 9748 return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval; 9749 } 9750 9751 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9752 { 9753 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9754 struct bpf_func_state *caller, *callee; 9755 struct bpf_reg_state *r0; 9756 bool in_callback_fn; 9757 int err; 9758 9759 callee = state->frame[state->curframe]; 9760 r0 = &callee->regs[BPF_REG_0]; 9761 if (r0->type == PTR_TO_STACK) { 9762 /* technically it's ok to return caller's stack pointer 9763 * (or caller's caller's pointer) back to the caller, 9764 * since these pointers are valid. Only current stack 9765 * pointer will be invalid as soon as function exits, 9766 * but let's be conservative 9767 */ 9768 verbose(env, "cannot return stack pointer to the caller\n"); 9769 return -EINVAL; 9770 } 9771 9772 caller = state->frame[state->curframe - 1]; 9773 if (callee->in_callback_fn) { 9774 if (r0->type != SCALAR_VALUE) { 9775 verbose(env, "R0 not a scalar value\n"); 9776 return -EACCES; 9777 } 9778 9779 /* we are going to rely on register's precise value */ 9780 err = mark_chain_precision(env, BPF_REG_0); 9781 if (err) 9782 return err; 9783 9784 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 9785 if (!retval_range_within(callee->callback_ret_range, r0)) { 9786 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9787 "At callback return", "R0"); 9788 return -EINVAL; 9789 } 9790 if (!bpf_calls_callback(env, callee->callsite)) { 9791 verifier_bug(env, "in callback at %d, callsite %d !calls_callback", 9792 *insn_idx, callee->callsite); 9793 return -EFAULT; 9794 } 9795 } else { 9796 /* return to the caller whatever r0 had in the callee */ 9797 caller->regs[BPF_REG_0] = *r0; 9798 } 9799 9800 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9801 * there function call logic would reschedule callback visit. If iteration 9802 * converges is_state_visited() would prune that visit eventually. 9803 */ 9804 in_callback_fn = callee->in_callback_fn; 9805 if (in_callback_fn) 9806 *insn_idx = callee->callsite; 9807 else 9808 *insn_idx = callee->callsite + 1; 9809 9810 if (env->log.level & BPF_LOG_LEVEL) { 9811 verbose(env, "returning from callee:\n"); 9812 print_verifier_state(env, state, callee->frameno, true); 9813 verbose(env, "to caller at %d:\n", *insn_idx); 9814 print_verifier_state(env, state, caller->frameno, true); 9815 } 9816 /* clear everything in the callee. In case of exceptional exits using 9817 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9818 free_func_state(callee); 9819 state->frame[state->curframe--] = NULL; 9820 invalidate_outgoing_stack_args(env, caller); 9821 9822 /* for callbacks widen imprecise scalars to make programs like below verify: 9823 * 9824 * struct ctx { int i; } 9825 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9826 * ... 9827 * struct ctx = { .i = 0; } 9828 * bpf_loop(100, cb, &ctx, 0); 9829 * 9830 * This is similar to what is done in process_iter_next_call() for open 9831 * coded iterators. 9832 */ 9833 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9834 if (prev_st) { 9835 err = widen_imprecise_scalars(env, prev_st, state); 9836 if (err) 9837 return err; 9838 } 9839 return 0; 9840 } 9841 9842 static int do_refine_retval_range(struct bpf_verifier_env *env, 9843 struct bpf_reg_state *regs, int ret_type, 9844 int func_id, 9845 struct bpf_call_arg_meta *meta) 9846 { 9847 struct bpf_retval_range range; 9848 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9849 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9850 9851 if (ret_type != RET_INTEGER) 9852 return 0; 9853 9854 switch (func_id) { 9855 case BPF_FUNC_get_stack: 9856 case BPF_FUNC_get_task_stack: 9857 case BPF_FUNC_probe_read_str: 9858 case BPF_FUNC_probe_read_kernel_str: 9859 case BPF_FUNC_probe_read_user_str: 9860 reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9861 reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9862 reg_bounds_sync(ret_reg); 9863 break; 9864 case BPF_FUNC_get_smp_processor_id: 9865 reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1); 9866 reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1); 9867 reg_bounds_sync(ret_reg); 9868 break; 9869 case BPF_FUNC_get_retval: 9870 /* 9871 * bpf_get_retval may see arbitrary value passed by bpf_prog_run_array_cg for 9872 * CGROUP_GETSOCKOPT type. 9873 */ 9874 if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT && 9875 env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) 9876 break; 9877 9878 if (prog_type == BPF_PROG_TYPE_LSM && 9879 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 9880 if (!env->prog->aux->attach_func_proto->type) 9881 break; 9882 bpf_lsm_get_retval_range(env->prog, &range); 9883 } else { 9884 range.minval = -MAX_ERRNO; 9885 range.maxval = 0; 9886 } 9887 9888 reg_set_srange64(ret_reg, range.minval, range.maxval); 9889 reg_set_srange32(ret_reg, range.minval, range.maxval); 9890 reg_bounds_sync(ret_reg); 9891 break; 9892 } 9893 9894 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9895 } 9896 9897 static int 9898 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9899 int func_id, int insn_idx) 9900 { 9901 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9902 struct bpf_map *map = meta->map.ptr; 9903 9904 if (func_id != BPF_FUNC_tail_call && 9905 func_id != BPF_FUNC_map_lookup_elem && 9906 func_id != BPF_FUNC_map_update_elem && 9907 func_id != BPF_FUNC_map_delete_elem && 9908 func_id != BPF_FUNC_map_push_elem && 9909 func_id != BPF_FUNC_map_pop_elem && 9910 func_id != BPF_FUNC_map_peek_elem && 9911 func_id != BPF_FUNC_for_each_map_elem && 9912 func_id != BPF_FUNC_redirect_map && 9913 func_id != BPF_FUNC_map_lookup_percpu_elem) 9914 return 0; 9915 9916 if (map == NULL) { 9917 verifier_bug(env, "expected map for helper call"); 9918 return -EFAULT; 9919 } 9920 9921 /* In case of read-only, some additional restrictions 9922 * need to be applied in order to prevent altering the 9923 * state of the map from program side. 9924 */ 9925 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9926 (func_id == BPF_FUNC_map_delete_elem || 9927 func_id == BPF_FUNC_map_update_elem || 9928 func_id == BPF_FUNC_map_push_elem || 9929 func_id == BPF_FUNC_map_pop_elem)) { 9930 verbose(env, "write into map forbidden\n"); 9931 return -EACCES; 9932 } 9933 9934 if (!aux->map_ptr_state.map_ptr) 9935 bpf_map_ptr_store(aux, meta->map.ptr, 9936 !meta->map.ptr->bypass_spec_v1, false); 9937 else if (aux->map_ptr_state.map_ptr != meta->map.ptr) 9938 bpf_map_ptr_store(aux, meta->map.ptr, 9939 !meta->map.ptr->bypass_spec_v1, true); 9940 return 0; 9941 } 9942 9943 static int 9944 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9945 int func_id, int insn_idx) 9946 { 9947 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9948 struct bpf_reg_state *reg; 9949 struct bpf_map *map = meta->map.ptr; 9950 u64 val, max; 9951 int err; 9952 9953 if (func_id != BPF_FUNC_tail_call) 9954 return 0; 9955 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9956 verbose(env, "expected prog array map for tail call"); 9957 return -EINVAL; 9958 } 9959 9960 reg = reg_state(env, BPF_REG_3); 9961 val = reg->var_off.value; 9962 max = map->max_entries; 9963 9964 if (!(is_reg_const(reg, false) && val < max)) { 9965 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9966 return 0; 9967 } 9968 9969 err = mark_chain_precision(env, BPF_REG_3); 9970 if (err) 9971 return err; 9972 if (bpf_map_key_unseen(aux)) 9973 bpf_map_key_store(aux, val); 9974 else if (!bpf_map_key_poisoned(aux) && 9975 bpf_map_key_immediate(aux) != val) 9976 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9977 return 0; 9978 } 9979 9980 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9981 { 9982 struct bpf_verifier_state *state = env->cur_state; 9983 enum bpf_prog_type type = resolve_prog_type(env->prog); 9984 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 9985 bool refs_lingering = false; 9986 int i; 9987 9988 if (!exception_exit && cur_func(env)->frameno) 9989 return 0; 9990 9991 for (i = 0; i < state->acquired_refs; i++) { 9992 if (state->refs[i].type != REF_TYPE_PTR) 9993 continue; 9994 /* Allow struct_ops programs to return a referenced kptr back to 9995 * kernel. Type checks are performed later in check_return_code. 9996 */ 9997 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && 9998 reg->id == state->refs[i].id) 9999 continue; 10000 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 10001 state->refs[i].id, state->refs[i].insn_idx); 10002 refs_lingering = true; 10003 } 10004 return refs_lingering ? -EINVAL : 0; 10005 } 10006 10007 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 10008 { 10009 int err; 10010 10011 if (check_lock && env->cur_state->active_locks) { 10012 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 10013 return -EINVAL; 10014 } 10015 10016 err = check_reference_leak(env, exception_exit); 10017 if (err) { 10018 verbose(env, "%s would lead to reference leak\n", prefix); 10019 return err; 10020 } 10021 10022 if (check_lock && env->cur_state->active_irq_id) { 10023 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix); 10024 return -EINVAL; 10025 } 10026 10027 if (check_lock && env->cur_state->active_rcu_locks) { 10028 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 10029 return -EINVAL; 10030 } 10031 10032 if (check_lock && env->cur_state->active_preempt_locks) { 10033 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 10034 return -EINVAL; 10035 } 10036 10037 return 0; 10038 } 10039 10040 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10041 struct bpf_reg_state *regs) 10042 { 10043 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10044 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10045 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10046 struct bpf_bprintf_data data = {}; 10047 int err, fmt_map_off, num_args; 10048 u64 fmt_addr; 10049 char *fmt; 10050 10051 /* data must be an array of u64 */ 10052 if (data_len_reg->var_off.value % 8) 10053 return -EINVAL; 10054 num_args = data_len_reg->var_off.value / 8; 10055 10056 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10057 * and map_direct_value_addr is set. 10058 */ 10059 fmt_map_off = fmt_reg->var_off.value; 10060 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10061 fmt_map_off); 10062 if (err) { 10063 verbose(env, "failed to retrieve map value address\n"); 10064 return -EFAULT; 10065 } 10066 fmt = (char *)(long)fmt_addr + fmt_map_off; 10067 10068 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10069 * can focus on validating the format specifiers. 10070 */ 10071 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10072 if (err < 0) 10073 verbose(env, "Invalid format string\n"); 10074 10075 return err; 10076 } 10077 10078 static int check_get_func_ip(struct bpf_verifier_env *env) 10079 { 10080 enum bpf_prog_type type = resolve_prog_type(env->prog); 10081 int func_id = BPF_FUNC_get_func_ip; 10082 10083 if (type == BPF_PROG_TYPE_TRACING) { 10084 if (!bpf_prog_has_trampoline(env->prog)) { 10085 verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n", 10086 func_id_name(func_id), func_id); 10087 return -ENOTSUPP; 10088 } 10089 return 0; 10090 } else if (type == BPF_PROG_TYPE_KPROBE) { 10091 return 0; 10092 } 10093 10094 verbose(env, "func %s#%d not supported for program type %d\n", 10095 func_id_name(func_id), func_id, type); 10096 return -ENOTSUPP; 10097 } 10098 10099 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env) 10100 { 10101 return &env->insn_aux_data[env->insn_idx]; 10102 } 10103 10104 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10105 { 10106 struct bpf_reg_state *reg = reg_state(env, BPF_REG_4); 10107 bool reg_is_null = bpf_register_is_null(reg); 10108 10109 if (reg_is_null) 10110 mark_chain_precision(env, BPF_REG_4); 10111 10112 return reg_is_null; 10113 } 10114 10115 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10116 { 10117 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10118 10119 if (!state->initialized) { 10120 state->initialized = 1; 10121 state->fit_for_inline = loop_flag_is_zero(env); 10122 state->callback_subprogno = subprogno; 10123 return; 10124 } 10125 10126 if (!state->fit_for_inline) 10127 return; 10128 10129 state->fit_for_inline = (loop_flag_is_zero(env) && 10130 state->callback_subprogno == subprogno); 10131 } 10132 10133 /* Returns whether or not the given map can potentially elide 10134 * lookup return value nullness check. This is possible if the key 10135 * is statically known. 10136 */ 10137 static bool can_elide_value_nullness(const struct bpf_map *map) 10138 { 10139 if (map->map_flags & BPF_F_INNER_MAP) 10140 return false; 10141 10142 switch (map->map_type) { 10143 case BPF_MAP_TYPE_ARRAY: 10144 case BPF_MAP_TYPE_PERCPU_ARRAY: 10145 return true; 10146 default: 10147 return false; 10148 } 10149 } 10150 10151 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id, 10152 const struct bpf_func_proto **ptr) 10153 { 10154 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 10155 return -ERANGE; 10156 10157 if (!env->ops->get_func_proto) 10158 return -EINVAL; 10159 10160 *ptr = env->ops->get_func_proto(func_id, env->prog); 10161 return *ptr && (*ptr)->func ? 0 : -EINVAL; 10162 } 10163 10164 /* Check if we're in a sleepable context. */ 10165 static inline bool in_sleepable_context(struct bpf_verifier_env *env) 10166 { 10167 return !env->cur_state->active_rcu_locks && 10168 !env->cur_state->active_preempt_locks && 10169 !env->cur_state->active_locks && 10170 !env->cur_state->active_irq_id && 10171 in_sleepable(env); 10172 } 10173 10174 static const char *non_sleepable_context_description(struct bpf_verifier_env *env) 10175 { 10176 if (env->cur_state->active_rcu_locks) 10177 return "rcu_read_lock region"; 10178 if (env->cur_state->active_preempt_locks) 10179 return "non-preemptible region"; 10180 if (env->cur_state->active_irq_id) 10181 return "IRQ-disabled region"; 10182 if (env->cur_state->active_locks) 10183 return "lock region"; 10184 return "non-sleepable prog"; 10185 } 10186 10187 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 10188 bool convert_rcu, bool release_dynptr) 10189 { 10190 int err = -EINVAL; 10191 10192 if (bpf_register_is_null(reg)) 10193 return 0; 10194 10195 if (release_dynptr) 10196 err = unmark_stack_slots_dynptr(env, reg); 10197 else if (convert_rcu) 10198 err = ref_convert_alloc_rcu_protected(env, reg->id); 10199 else if (reg_is_referenced(env, reg)) 10200 err = release_reference(env, reg->id); 10201 10202 return err; 10203 } 10204 10205 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10206 int *insn_idx_p) 10207 { 10208 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10209 bool returns_cpu_specific_alloc_ptr = false; 10210 const struct bpf_func_proto *fn = NULL; 10211 enum bpf_return_type ret_type; 10212 enum bpf_type_flag ret_flag; 10213 struct bpf_reg_state *regs; 10214 struct bpf_call_arg_meta meta; 10215 int insn_idx = *insn_idx_p; 10216 bool changes_data; 10217 int i, err, func_id; 10218 10219 /* find function prototype */ 10220 func_id = insn->imm; 10221 err = bpf_get_helper_proto(env, insn->imm, &fn); 10222 if (err == -ERANGE) { 10223 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 10224 return -EINVAL; 10225 } 10226 10227 if (err) { 10228 verbose(env, "program of this type cannot use helper %s#%d\n", 10229 func_id_name(func_id), func_id); 10230 return err; 10231 } 10232 10233 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10234 if (!env->prog->gpl_compatible && fn->gpl_only) { 10235 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10236 return -EINVAL; 10237 } 10238 10239 if (fn->allowed && !fn->allowed(env->prog)) { 10240 verbose(env, "helper call is not allowed in probe\n"); 10241 return -EINVAL; 10242 } 10243 10244 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10245 changes_data = bpf_helper_changes_pkt_data(func_id); 10246 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10247 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id); 10248 return -EFAULT; 10249 } 10250 10251 memset(&meta, 0, sizeof(meta)); 10252 10253 err = check_func_proto(fn, &meta); 10254 if (err) { 10255 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id); 10256 return err; 10257 } 10258 10259 if (fn->might_sleep && !in_sleepable_context(env)) { 10260 verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id, 10261 non_sleepable_context_description(env)); 10262 return -EINVAL; 10263 } 10264 10265 /* Track non-sleepable context for helpers. */ 10266 if (!in_sleepable_context(env)) 10267 env->insn_aux_data[insn_idx].non_sleepable = true; 10268 10269 meta.func_id = func_id; 10270 meta.fn = fn; 10271 /* check args */ 10272 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10273 err = check_func_arg(env, i, &meta, insn_idx); 10274 if (err) 10275 return err; 10276 } 10277 10278 err = record_func_map(env, &meta, func_id, insn_idx); 10279 if (err) 10280 return err; 10281 10282 err = record_func_key(env, &meta, func_id, insn_idx); 10283 if (err) 10284 return err; 10285 10286 regs = cur_regs(env); 10287 10288 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10289 * is inferred from register state. 10290 */ 10291 for (i = 0; i < meta.arg_raw_mem.size; i++) { 10292 err = check_mem_access(env, insn_idx, regs + meta.arg_raw_mem.regno, 10293 argno_from_reg(meta.arg_raw_mem.regno), i, BPF_B, 10294 BPF_WRITE, -1, false, false); 10295 if (err) 10296 return err; 10297 } 10298 10299 if (meta.release_regno) { 10300 struct bpf_reg_state *reg = ®s[meta.release_regno]; 10301 bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) && 10302 (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU); 10303 10304 err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id); 10305 if (err) 10306 return err; 10307 } 10308 10309 switch (func_id) { 10310 case BPF_FUNC_tail_call: 10311 err = check_resource_leak(env, false, true, "tail_call"); 10312 if (err) 10313 return err; 10314 break; 10315 case BPF_FUNC_get_local_storage: 10316 /* check that flags argument in get_local_storage(map, flags) is 0, 10317 * this is required because get_local_storage() can't return an error. 10318 */ 10319 if (!bpf_register_is_null(®s[BPF_REG_2])) { 10320 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10321 return -EINVAL; 10322 } 10323 break; 10324 case BPF_FUNC_for_each_map_elem: 10325 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10326 set_map_elem_callback_state); 10327 break; 10328 case BPF_FUNC_timer_set_callback: 10329 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10330 set_timer_callback_state); 10331 break; 10332 case BPF_FUNC_find_vma: 10333 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10334 set_find_vma_callback_state); 10335 break; 10336 case BPF_FUNC_snprintf: 10337 err = check_bpf_snprintf_call(env, regs); 10338 break; 10339 case BPF_FUNC_loop: 10340 update_loop_inline_state(env, meta.subprogno); 10341 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10342 * is finished, thus mark it precise. 10343 */ 10344 err = mark_chain_precision(env, BPF_REG_1); 10345 if (err) 10346 return err; 10347 if (cur_func(env)->callback_depth < reg_umax(®s[BPF_REG_1])) { 10348 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10349 set_loop_callback_state); 10350 } else { 10351 cur_func(env)->callback_depth = 0; 10352 if (env->log.level & BPF_LOG_LEVEL2) 10353 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10354 env->cur_state->curframe); 10355 } 10356 break; 10357 case BPF_FUNC_dynptr_from_mem: 10358 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10359 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10360 reg_type_str(env, regs[BPF_REG_1].type)); 10361 return -EACCES; 10362 } 10363 break; 10364 case BPF_FUNC_set_retval: 10365 { 10366 struct bpf_retval_range range = { 10367 .minval = -MAX_ERRNO, 10368 .maxval = 0, 10369 .return_32bit = true 10370 }; 10371 struct bpf_reg_state *r1 = ®s[BPF_REG_1]; 10372 10373 if (r1->type != SCALAR_VALUE) { 10374 verbose(env, "R1 is not a scalar\n"); 10375 return -EINVAL; 10376 } 10377 10378 /* CGROUP_GETSOCKOPT is allowed to return arbitrary value */ 10379 if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT && 10380 env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) 10381 break; 10382 10383 if (prog_type == BPF_PROG_TYPE_LSM && 10384 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10385 if (!env->prog->aux->attach_func_proto->type) { 10386 /* Make sure programs that attach to void 10387 * hooks don't try to modify return value. 10388 */ 10389 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10390 return -EINVAL; 10391 } 10392 bpf_lsm_get_retval_range(env->prog, &range); 10393 } 10394 10395 err = mark_chain_precision(env, BPF_REG_1); 10396 if (err) 10397 return err; 10398 10399 if (!retval_range_within(range, r1)) { 10400 verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1"); 10401 return -EINVAL; 10402 } 10403 10404 break; 10405 } 10406 case BPF_FUNC_dynptr_write: 10407 { 10408 enum bpf_dynptr_type dynptr_type = meta.dynptr.type; 10409 10410 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10411 return -EFAULT; 10412 10413 if (dynptr_type == BPF_DYNPTR_TYPE_SKB || 10414 dynptr_type == BPF_DYNPTR_TYPE_SKB_META) 10415 /* this will trigger clear_all_pkt_pointers(), which will 10416 * invalidate all dynptr slices associated with the skb 10417 */ 10418 changes_data = true; 10419 10420 break; 10421 } 10422 case BPF_FUNC_per_cpu_ptr: 10423 case BPF_FUNC_this_cpu_ptr: 10424 { 10425 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10426 const struct btf_type *type; 10427 10428 if (reg->type & MEM_RCU) { 10429 type = btf_type_by_id(reg->btf, reg->btf_id); 10430 if (!type || !btf_type_is_struct(type)) { 10431 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10432 return -EFAULT; 10433 } 10434 returns_cpu_specific_alloc_ptr = true; 10435 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10436 } 10437 break; 10438 } 10439 case BPF_FUNC_user_ringbuf_drain: 10440 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10441 set_user_ringbuf_callback_state); 10442 break; 10443 } 10444 10445 if (err) 10446 return err; 10447 10448 /* reset caller saved regs */ 10449 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10450 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 10451 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10452 } 10453 invalidate_outgoing_stack_args(env, cur_func(env)); 10454 10455 /* update return register (already marked as written above) */ 10456 ret_type = fn->ret_type; 10457 ret_flag = type_flag(ret_type); 10458 10459 switch (base_type(ret_type)) { 10460 case RET_INTEGER: 10461 /* sets type to SCALAR_VALUE */ 10462 mark_reg_unknown(env, regs, BPF_REG_0); 10463 break; 10464 case RET_VOID: 10465 regs[BPF_REG_0].type = NOT_INIT; 10466 break; 10467 case RET_PTR_TO_MAP_VALUE: 10468 /* There is no offset yet applied, variable or fixed */ 10469 mark_reg_known_zero(env, regs, BPF_REG_0); 10470 /* remember map_ptr, so that check_map_access() 10471 * can check 'value_size' boundary of memory access 10472 * to map element returned from bpf_map_lookup_elem() 10473 */ 10474 if (meta.map.ptr == NULL) { 10475 verifier_bug(env, "unexpected null map_ptr"); 10476 return -EFAULT; 10477 } 10478 10479 if (func_id == BPF_FUNC_map_lookup_elem && 10480 can_elide_value_nullness(meta.map.ptr) && 10481 meta.const_map_key >= 0 && 10482 meta.const_map_key < meta.map.ptr->max_entries) 10483 ret_flag &= ~PTR_MAYBE_NULL; 10484 10485 regs[BPF_REG_0].map_ptr = meta.map.ptr; 10486 regs[BPF_REG_0].map_uid = meta.map.uid; 10487 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10488 if (type_may_be_null(ret_flag) || 10489 btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 10490 regs[BPF_REG_0].id = ++env->id_gen; 10491 } 10492 /* requires regs[BPF_REG_0].id to be set because of the map-in-map case */ 10493 refine_map_lookup_value(®s[BPF_REG_0]); 10494 break; 10495 case RET_PTR_TO_SOCKET: 10496 mark_reg_known_zero(env, regs, BPF_REG_0); 10497 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10498 break; 10499 case RET_PTR_TO_SOCK_COMMON: 10500 mark_reg_known_zero(env, regs, BPF_REG_0); 10501 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10502 break; 10503 case RET_PTR_TO_TCP_SOCK: 10504 mark_reg_known_zero(env, regs, BPF_REG_0); 10505 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10506 break; 10507 case RET_PTR_TO_MEM: 10508 mark_reg_known_zero(env, regs, BPF_REG_0); 10509 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10510 regs[BPF_REG_0].mem_size = meta.ret_mem.size; 10511 break; 10512 case RET_PTR_TO_MEM_OR_BTF_ID: 10513 { 10514 const struct btf_type *t; 10515 10516 mark_reg_known_zero(env, regs, BPF_REG_0); 10517 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10518 if (!btf_type_is_struct(t)) { 10519 u32 tsize; 10520 const struct btf_type *ret; 10521 const char *tname; 10522 10523 /* resolve the type size of ksym. */ 10524 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10525 if (IS_ERR(ret)) { 10526 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10527 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10528 tname, PTR_ERR(ret)); 10529 return -EINVAL; 10530 } 10531 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10532 regs[BPF_REG_0].mem_size = tsize; 10533 } else { 10534 if (returns_cpu_specific_alloc_ptr) { 10535 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10536 } else { 10537 /* MEM_RDONLY may be carried from ret_flag, but it 10538 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10539 * it will confuse the check of PTR_TO_BTF_ID in 10540 * check_mem_access(). 10541 */ 10542 ret_flag &= ~MEM_RDONLY; 10543 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10544 } 10545 10546 regs[BPF_REG_0].btf = meta.ret_btf; 10547 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10548 } 10549 break; 10550 } 10551 case RET_PTR_TO_BTF_ID: 10552 { 10553 struct btf *ret_btf; 10554 int ret_btf_id; 10555 10556 mark_reg_known_zero(env, regs, BPF_REG_0); 10557 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10558 if (func_id == BPF_FUNC_kptr_xchg) { 10559 ret_btf = meta.kptr_field->kptr.btf; 10560 ret_btf_id = meta.kptr_field->kptr.btf_id; 10561 if (!btf_is_kernel(ret_btf)) { 10562 regs[BPF_REG_0].type |= MEM_ALLOC; 10563 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10564 regs[BPF_REG_0].type |= MEM_PERCPU; 10565 } 10566 } else { 10567 if (fn->ret_btf_id == BPF_PTR_POISON) { 10568 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type", 10569 func_id_name(func_id)); 10570 return -EFAULT; 10571 } 10572 ret_btf = btf_vmlinux; 10573 ret_btf_id = *fn->ret_btf_id; 10574 } 10575 if (ret_btf_id == 0) { 10576 verbose(env, "invalid return type %u of func %s#%d\n", 10577 base_type(ret_type), func_id_name(func_id), 10578 func_id); 10579 return -EINVAL; 10580 } 10581 regs[BPF_REG_0].btf = ret_btf; 10582 regs[BPF_REG_0].btf_id = ret_btf_id; 10583 break; 10584 } 10585 default: 10586 verbose(env, "unknown return type %u of func %s#%d\n", 10587 base_type(ret_type), func_id_name(func_id), func_id); 10588 return -EINVAL; 10589 } 10590 10591 if (type_may_be_null(regs[BPF_REG_0].type) && !regs[BPF_REG_0].id) 10592 regs[BPF_REG_0].id = ++env->id_gen; 10593 10594 if (is_ptr_cast_function(func_id) && 10595 find_reference_state(env->cur_state, meta.ref_obj.id)) { 10596 struct bpf_verifier_state *branch; 10597 struct bpf_reg_state *r0; 10598 10599 err = validate_ref_obj(env, &meta.ref_obj); 10600 if (err) 10601 return err; 10602 10603 /* 10604 * In order for a release of any of the original or cast pointers 10605 * to invalidate all other pointers, reuse the same reference id for 10606 * the cast result. 10607 * This reference id can't be used for nullness propagation, 10608 * as cast might return NULL for a non-NULL input. 10609 * Hence, explore the NULL case as a separate branch. 10610 */ 10611 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10612 if (IS_ERR(branch)) 10613 return PTR_ERR(branch); 10614 10615 r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0]; 10616 __mark_reg_known_zero(r0); 10617 r0->type = SCALAR_VALUE; 10618 10619 regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL; 10620 regs[BPF_REG_0].id = meta.ref_obj.id; 10621 } else if (is_acquire_function(func_id, meta.map.ptr)) { 10622 int id = acquire_reference(env, insn_idx, 0); 10623 10624 if (id < 0) 10625 return id; 10626 10627 regs[BPF_REG_0].id = id; 10628 } 10629 10630 if (func_id == BPF_FUNC_dynptr_data) 10631 regs[BPF_REG_0].parent_id = meta.dynptr.id; 10632 10633 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10634 if (err) 10635 return err; 10636 10637 err = check_map_func_compatibility(env, meta.map.ptr, func_id); 10638 if (err) 10639 return err; 10640 10641 if ((func_id == BPF_FUNC_get_stack || 10642 func_id == BPF_FUNC_get_task_stack) && 10643 !env->prog->has_callchain_buf) { 10644 const char *err_str; 10645 10646 #ifdef CONFIG_PERF_EVENTS 10647 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10648 err_str = "cannot get callchain buffer for func %s#%d\n"; 10649 #else 10650 err = -ENOTSUPP; 10651 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10652 #endif 10653 if (err) { 10654 verbose(env, err_str, func_id_name(func_id), func_id); 10655 return err; 10656 } 10657 10658 env->prog->has_callchain_buf = true; 10659 } 10660 10661 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10662 env->prog->call_get_stack = true; 10663 10664 if (func_id == BPF_FUNC_get_func_ip) { 10665 if (check_get_func_ip(env)) 10666 return -ENOTSUPP; 10667 env->prog->call_get_func_ip = true; 10668 } 10669 10670 if (func_id == BPF_FUNC_tail_call) { 10671 if (env->cur_state->curframe) { 10672 struct bpf_verifier_state *branch; 10673 10674 mark_reg_scratched(env, BPF_REG_0); 10675 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10676 if (IS_ERR(branch)) 10677 return PTR_ERR(branch); 10678 clear_all_pkt_pointers(env); 10679 mark_reg_unknown(env, regs, BPF_REG_0); 10680 err = prepare_func_exit(env, &env->insn_idx); 10681 if (err) 10682 return err; 10683 env->insn_idx--; 10684 } else { 10685 changes_data = false; 10686 } 10687 } 10688 10689 if (changes_data) 10690 clear_all_pkt_pointers(env); 10691 return 0; 10692 } 10693 10694 static bool is_kfunc_acquire(struct bpf_call_arg_meta *meta) 10695 { 10696 return meta->kfunc_flags & KF_ACQUIRE; 10697 } 10698 10699 static bool is_kfunc_release(struct bpf_call_arg_meta *meta) 10700 { 10701 return meta->kfunc_flags & KF_RELEASE; 10702 } 10703 10704 static bool is_kfunc_destructive(struct bpf_call_arg_meta *meta) 10705 { 10706 return meta->kfunc_flags & KF_DESTRUCTIVE; 10707 } 10708 10709 static bool is_kfunc_rcu(struct bpf_call_arg_meta *meta) 10710 { 10711 return meta->kfunc_flags & KF_RCU; 10712 } 10713 10714 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta) 10715 { 10716 return meta->kfunc_flags & KF_RCU_PROTECTED; 10717 } 10718 10719 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10720 const struct btf_param *arg) 10721 { 10722 const struct btf_type *t; 10723 10724 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10725 if (!btf_type_is_scalar(t)) 10726 return false; 10727 10728 return btf_param_match_suffix(btf, arg, "__sz"); 10729 } 10730 10731 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10732 const struct btf_param *arg) 10733 { 10734 const struct btf_type *t; 10735 10736 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10737 if (!btf_type_is_scalar(t)) 10738 return false; 10739 10740 return btf_param_match_suffix(btf, arg, "__szk"); 10741 } 10742 10743 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10744 { 10745 return btf_param_match_suffix(btf, arg, "__k"); 10746 } 10747 10748 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10749 { 10750 return btf_param_match_suffix(btf, arg, "__ign"); 10751 } 10752 10753 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 10754 { 10755 return btf_param_match_suffix(btf, arg, "__map"); 10756 } 10757 10758 static bool is_kfunc_arg_const_map(const struct btf *btf, const struct btf_param *arg) 10759 { 10760 return btf_param_match_suffix(btf, arg, "__const_map"); 10761 } 10762 10763 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10764 { 10765 return btf_param_match_suffix(btf, arg, "__alloc"); 10766 } 10767 10768 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10769 { 10770 return btf_param_match_suffix(btf, arg, "__uninit"); 10771 } 10772 10773 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10774 { 10775 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 10776 } 10777 10778 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10779 { 10780 return btf_param_match_suffix(btf, arg, "__nullable") || 10781 btf_param_match_suffix(btf, arg, "__arena"); 10782 } 10783 10784 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg) 10785 { 10786 return btf_param_match_suffix(btf, arg, "__nonown_allowed"); 10787 } 10788 10789 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10790 { 10791 return btf_param_match_suffix(btf, arg, "__str"); 10792 } 10793 10794 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg) 10795 { 10796 return btf_param_match_suffix(btf, arg, "__irq_flag"); 10797 } 10798 10799 static bool is_kfunc_arg_arena(const struct btf *btf, const struct btf_param *arg) 10800 { 10801 return btf_param_match_suffix(btf, arg, "__arena__nullable") || 10802 btf_param_match_suffix(btf, arg, "__arena"); 10803 } 10804 10805 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10806 const struct btf_param *arg, 10807 const char *name) 10808 { 10809 int len, target_len = strlen(name); 10810 const char *param_name; 10811 10812 param_name = btf_name_by_offset(btf, arg->name_off); 10813 if (str_is_empty(param_name)) 10814 return false; 10815 len = strlen(param_name); 10816 if (len != target_len) 10817 return false; 10818 if (strcmp(param_name, name)) 10819 return false; 10820 10821 return true; 10822 } 10823 10824 enum { 10825 KF_ARG_DYNPTR_ID, 10826 KF_ARG_LIST_HEAD_ID, 10827 KF_ARG_LIST_NODE_ID, 10828 KF_ARG_RB_ROOT_ID, 10829 KF_ARG_RB_NODE_ID, 10830 KF_ARG_WORKQUEUE_ID, 10831 KF_ARG_RES_SPIN_LOCK_ID, 10832 KF_ARG_TASK_WORK_ID, 10833 KF_ARG_PROG_AUX_ID, 10834 KF_ARG_TIMER_ID 10835 }; 10836 10837 BTF_ID_LIST(kf_arg_btf_ids) 10838 BTF_ID(struct, bpf_dynptr) 10839 BTF_ID(struct, bpf_list_head) 10840 BTF_ID(struct, bpf_list_node) 10841 BTF_ID(struct, bpf_rb_root) 10842 BTF_ID(struct, bpf_rb_node) 10843 BTF_ID(struct, bpf_wq) 10844 BTF_ID(struct, bpf_res_spin_lock) 10845 BTF_ID(struct, bpf_task_work) 10846 BTF_ID(struct, bpf_prog_aux) 10847 BTF_ID(struct, bpf_timer) 10848 10849 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10850 const struct btf_param *arg, int type) 10851 { 10852 const struct btf_type *t; 10853 u32 res_id; 10854 10855 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10856 if (!t) 10857 return false; 10858 if (!btf_type_is_ptr(t)) 10859 return false; 10860 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10861 if (!t) 10862 return false; 10863 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10864 } 10865 10866 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10867 { 10868 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10869 } 10870 10871 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10872 { 10873 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10874 } 10875 10876 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10877 { 10878 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10879 } 10880 10881 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10882 { 10883 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10884 } 10885 10886 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10887 { 10888 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10889 } 10890 10891 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg) 10892 { 10893 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID); 10894 } 10895 10896 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 10897 { 10898 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 10899 } 10900 10901 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg) 10902 { 10903 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID); 10904 } 10905 10906 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg) 10907 { 10908 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID); 10909 } 10910 10911 static bool is_rbtree_node_type(const struct btf_type *t) 10912 { 10913 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]); 10914 } 10915 10916 static bool is_list_node_type(const struct btf_type *t) 10917 { 10918 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]); 10919 } 10920 10921 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10922 const struct btf_param *arg) 10923 { 10924 const struct btf_type *t; 10925 10926 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10927 if (!t) 10928 return false; 10929 10930 return true; 10931 } 10932 10933 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg) 10934 { 10935 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID); 10936 } 10937 10938 /* 10939 * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF: 10940 * - the _impl prototype with full arg list (meta->func_proto) 10941 * - the BPF API prototype w/o implicit args (func->type in BTF) 10942 * To determine whether an argument is implicit, we compare its position 10943 * against the number of arguments in the prototype w/o implicit args. 10944 */ 10945 static bool is_kfunc_arg_implicit(const struct bpf_call_arg_meta *meta, u32 arg_idx) 10946 { 10947 const struct btf_type *func, *func_proto; 10948 u32 argn; 10949 10950 if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS)) 10951 return false; 10952 10953 func = btf_type_by_id(meta->btf, meta->func_id); 10954 func_proto = btf_type_by_id(meta->btf, func->type); 10955 argn = btf_type_vlen(func_proto); 10956 10957 return argn <= arg_idx; 10958 } 10959 10960 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10961 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10962 const struct btf *btf, 10963 const struct btf_type *t, int rec) 10964 { 10965 const struct btf_type *member_type; 10966 const struct btf_member *member; 10967 u32 i; 10968 10969 if (!btf_type_is_struct(t)) 10970 return false; 10971 10972 for_each_member(i, t, member) { 10973 const struct btf_array *array; 10974 10975 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10976 if (btf_type_is_struct(member_type)) { 10977 if (rec >= 3) { 10978 verbose(env, "max struct nesting depth exceeded\n"); 10979 return false; 10980 } 10981 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10982 return false; 10983 continue; 10984 } 10985 if (btf_type_is_array(member_type)) { 10986 array = btf_array(member_type); 10987 if (!array->nelems) 10988 return false; 10989 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10990 if (!btf_type_is_scalar(member_type)) 10991 return false; 10992 continue; 10993 } 10994 if (!btf_type_is_scalar(member_type)) 10995 return false; 10996 } 10997 return true; 10998 } 10999 11000 enum kfunc_ptr_arg_type { 11001 KF_ARG_CONST_MEM_SIZE, 11002 KF_ARG_MEM_SIZE, 11003 KF_ARG_CONST, 11004 KF_ARG_CONST_ALLOC_SIZE_OR_ZERO, 11005 KF_ARG_ANYTHING, 11006 KF_ARG_PTR_TO_CTX, 11007 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 11008 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 11009 KF_ARG_PTR_TO_DYNPTR, 11010 KF_ARG_PTR_TO_ITER, 11011 KF_ARG_PTR_TO_LIST_HEAD, 11012 KF_ARG_PTR_TO_LIST_NODE, 11013 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 11014 KF_ARG_PTR_TO_MEM, 11015 KF_ARG_PTR_TO_CALLBACK, 11016 KF_ARG_PTR_TO_RB_ROOT, 11017 KF_ARG_PTR_TO_RB_NODE, 11018 KF_ARG_PTR_TO_CONST_STR, 11019 KF_ARG_CONST_MAP_PTR, 11020 KF_ARG_PTR_TO_TIMER, 11021 KF_ARG_PTR_TO_WORKQUEUE, 11022 KF_ARG_PTR_TO_IRQ_FLAG, 11023 KF_ARG_PTR_TO_RES_SPIN_LOCK, 11024 KF_ARG_PTR_TO_TASK_WORK, 11025 KF_ARG_PTR_TO_ARENA, 11026 }; 11027 11028 enum special_kfunc_type { 11029 KF_bpf_obj_new_impl, 11030 KF_bpf_obj_new, 11031 KF_bpf_obj_drop_impl, 11032 KF_bpf_obj_drop, 11033 KF_bpf_refcount_acquire_impl, 11034 KF_bpf_refcount_acquire, 11035 KF_bpf_list_push_front_impl, 11036 KF_bpf_list_push_front, 11037 KF_bpf_list_push_back_impl, 11038 KF_bpf_list_push_back, 11039 KF_bpf_list_add, 11040 KF_bpf_list_pop_front, 11041 KF_bpf_list_pop_back, 11042 KF_bpf_list_del, 11043 KF_bpf_list_front, 11044 KF_bpf_list_back, 11045 KF_bpf_list_is_first, 11046 KF_bpf_list_is_last, 11047 KF_bpf_list_empty, 11048 KF_bpf_cast_to_kern_ctx, 11049 KF_bpf_rdonly_cast, 11050 KF_bpf_rcu_read_lock, 11051 KF_bpf_rcu_read_unlock, 11052 KF_bpf_rbtree_remove, 11053 KF_bpf_rbtree_add_impl, 11054 KF_bpf_rbtree_add, 11055 KF_bpf_rbtree_first, 11056 KF_bpf_rbtree_root, 11057 KF_bpf_rbtree_left, 11058 KF_bpf_rbtree_right, 11059 KF_bpf_dynptr_from_skb, 11060 KF_bpf_dynptr_from_xdp, 11061 KF_bpf_dynptr_from_skb_meta, 11062 KF_bpf_xdp_pull_data, 11063 KF_bpf_dynptr_slice, 11064 KF_bpf_dynptr_slice_rdwr, 11065 KF_bpf_dynptr_clone, 11066 KF_bpf_percpu_obj_new_impl, 11067 KF_bpf_percpu_obj_new, 11068 KF_bpf_percpu_obj_drop_impl, 11069 KF_bpf_percpu_obj_drop, 11070 KF_bpf_throw, 11071 KF_bpf_wq_set_callback, 11072 KF_bpf_preempt_disable, 11073 KF_bpf_preempt_enable, 11074 KF_bpf_iter_css_task_new, 11075 KF_bpf_session_cookie, 11076 KF_bpf_get_kmem_cache, 11077 KF_bpf_local_irq_save, 11078 KF_bpf_local_irq_restore, 11079 KF_bpf_iter_num_new, 11080 KF_bpf_iter_num_next, 11081 KF_bpf_iter_num_destroy, 11082 KF_bpf_set_dentry_xattr, 11083 KF_bpf_remove_dentry_xattr, 11084 KF_bpf_res_spin_lock, 11085 KF_bpf_res_spin_unlock, 11086 KF_bpf_res_spin_lock_irqsave, 11087 KF_bpf_res_spin_unlock_irqrestore, 11088 KF_bpf_dynptr_from_file, 11089 KF_bpf_dynptr_file_discard, 11090 KF___bpf_trap, 11091 KF_bpf_task_work_schedule_signal, 11092 KF_bpf_task_work_schedule_resume, 11093 KF_bpf_arena_alloc_pages, 11094 KF_bpf_arena_free_pages, 11095 KF_bpf_arena_reserve_pages, 11096 KF_bpf_session_is_return, 11097 KF_bpf_stream_vprintk, 11098 KF_bpf_stream_print_stack, 11099 }; 11100 11101 BTF_ID_LIST(special_kfunc_list) 11102 BTF_ID(func, bpf_obj_new_impl) 11103 BTF_ID(func, bpf_obj_new) 11104 BTF_ID(func, bpf_obj_drop_impl) 11105 BTF_ID(func, bpf_obj_drop) 11106 BTF_ID(func, bpf_refcount_acquire_impl) 11107 BTF_ID(func, bpf_refcount_acquire) 11108 BTF_ID(func, bpf_list_push_front_impl) 11109 BTF_ID(func, bpf_list_push_front) 11110 BTF_ID(func, bpf_list_push_back_impl) 11111 BTF_ID(func, bpf_list_push_back) 11112 BTF_ID(func, bpf_list_add) 11113 BTF_ID(func, bpf_list_pop_front) 11114 BTF_ID(func, bpf_list_pop_back) 11115 BTF_ID(func, bpf_list_del) 11116 BTF_ID(func, bpf_list_front) 11117 BTF_ID(func, bpf_list_back) 11118 BTF_ID(func, bpf_list_is_first) 11119 BTF_ID(func, bpf_list_is_last) 11120 BTF_ID(func, bpf_list_empty) 11121 BTF_ID(func, bpf_cast_to_kern_ctx) 11122 BTF_ID(func, bpf_rdonly_cast) 11123 BTF_ID(func, bpf_rcu_read_lock) 11124 BTF_ID(func, bpf_rcu_read_unlock) 11125 BTF_ID(func, bpf_rbtree_remove) 11126 BTF_ID(func, bpf_rbtree_add_impl) 11127 BTF_ID(func, bpf_rbtree_add) 11128 BTF_ID(func, bpf_rbtree_first) 11129 BTF_ID(func, bpf_rbtree_root) 11130 BTF_ID(func, bpf_rbtree_left) 11131 BTF_ID(func, bpf_rbtree_right) 11132 #ifdef CONFIG_NET 11133 BTF_ID(func, bpf_dynptr_from_skb) 11134 BTF_ID(func, bpf_dynptr_from_xdp) 11135 BTF_ID(func, bpf_dynptr_from_skb_meta) 11136 BTF_ID(func, bpf_xdp_pull_data) 11137 #else 11138 BTF_ID_UNUSED 11139 BTF_ID_UNUSED 11140 BTF_ID_UNUSED 11141 BTF_ID_UNUSED 11142 #endif 11143 BTF_ID(func, bpf_dynptr_slice) 11144 BTF_ID(func, bpf_dynptr_slice_rdwr) 11145 BTF_ID(func, bpf_dynptr_clone) 11146 BTF_ID(func, bpf_percpu_obj_new_impl) 11147 BTF_ID(func, bpf_percpu_obj_new) 11148 BTF_ID(func, bpf_percpu_obj_drop_impl) 11149 BTF_ID(func, bpf_percpu_obj_drop) 11150 BTF_ID(func, bpf_throw) 11151 BTF_ID(func, bpf_wq_set_callback) 11152 BTF_ID(func, bpf_preempt_disable) 11153 BTF_ID(func, bpf_preempt_enable) 11154 #ifdef CONFIG_CGROUPS 11155 BTF_ID(func, bpf_iter_css_task_new) 11156 #else 11157 BTF_ID_UNUSED 11158 #endif 11159 #ifdef CONFIG_BPF_EVENTS 11160 BTF_ID(func, bpf_session_cookie) 11161 #else 11162 BTF_ID_UNUSED 11163 #endif 11164 BTF_ID(func, bpf_get_kmem_cache) 11165 BTF_ID(func, bpf_local_irq_save) 11166 BTF_ID(func, bpf_local_irq_restore) 11167 BTF_ID(func, bpf_iter_num_new) 11168 BTF_ID(func, bpf_iter_num_next) 11169 BTF_ID(func, bpf_iter_num_destroy) 11170 #ifdef CONFIG_BPF_LSM 11171 BTF_ID(func, bpf_set_dentry_xattr) 11172 BTF_ID(func, bpf_remove_dentry_xattr) 11173 #else 11174 BTF_ID_UNUSED 11175 BTF_ID_UNUSED 11176 #endif 11177 BTF_ID(func, bpf_res_spin_lock) 11178 BTF_ID(func, bpf_res_spin_unlock) 11179 BTF_ID(func, bpf_res_spin_lock_irqsave) 11180 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 11181 BTF_ID(func, bpf_dynptr_from_file) 11182 BTF_ID(func, bpf_dynptr_file_discard) 11183 BTF_ID(func, __bpf_trap) 11184 BTF_ID(func, bpf_task_work_schedule_signal) 11185 BTF_ID(func, bpf_task_work_schedule_resume) 11186 BTF_ID(func, bpf_arena_alloc_pages) 11187 BTF_ID(func, bpf_arena_free_pages) 11188 BTF_ID(func, bpf_arena_reserve_pages) 11189 #ifdef CONFIG_BPF_EVENTS 11190 BTF_ID(func, bpf_session_is_return) 11191 #else 11192 BTF_ID_UNUSED 11193 #endif 11194 BTF_ID(func, bpf_stream_vprintk) 11195 BTF_ID(func, bpf_stream_print_stack) 11196 11197 static bool is_bpf_obj_new_kfunc(u32 func_id) 11198 { 11199 return func_id == special_kfunc_list[KF_bpf_obj_new] || 11200 func_id == special_kfunc_list[KF_bpf_obj_new_impl]; 11201 } 11202 11203 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id) 11204 { 11205 return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] || 11206 func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]; 11207 } 11208 11209 static bool is_bpf_obj_drop_kfunc(u32 func_id) 11210 { 11211 return func_id == special_kfunc_list[KF_bpf_obj_drop] || 11212 func_id == special_kfunc_list[KF_bpf_obj_drop_impl]; 11213 } 11214 11215 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id) 11216 { 11217 return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] || 11218 func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]; 11219 } 11220 11221 static bool is_bpf_refcount_acquire_kfunc(u32 func_id) 11222 { 11223 return func_id == special_kfunc_list[KF_bpf_refcount_acquire] || 11224 func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11225 } 11226 11227 static bool is_bpf_list_push_kfunc(u32 func_id) 11228 { 11229 return func_id == special_kfunc_list[KF_bpf_list_push_front] || 11230 func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11231 func_id == special_kfunc_list[KF_bpf_list_push_back] || 11232 func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11233 func_id == special_kfunc_list[KF_bpf_list_add]; 11234 } 11235 11236 static bool is_bpf_rbtree_add_kfunc(u32 func_id) 11237 { 11238 return func_id == special_kfunc_list[KF_bpf_rbtree_add] || 11239 func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11240 } 11241 11242 static bool is_task_work_add_kfunc(u32 func_id) 11243 { 11244 return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] || 11245 func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume]; 11246 } 11247 11248 static bool is_kfunc_ret_null(struct bpf_call_arg_meta *meta) 11249 { 11250 if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref) 11251 return false; 11252 11253 return meta->kfunc_flags & KF_RET_NULL; 11254 } 11255 11256 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_call_arg_meta *meta) 11257 { 11258 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11259 } 11260 11261 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_call_arg_meta *meta) 11262 { 11263 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11264 } 11265 11266 static bool is_kfunc_bpf_preempt_disable(struct bpf_call_arg_meta *meta) 11267 { 11268 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11269 } 11270 11271 static bool is_kfunc_bpf_preempt_enable(struct bpf_call_arg_meta *meta) 11272 { 11273 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11274 } 11275 11276 bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta) 11277 { 11278 return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data]; 11279 } 11280 11281 static int 11282 get_kfunc_arg_type(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 11283 const struct btf_param *args, int arg, int nargs) 11284 { 11285 const struct btf_type *t, *ref_t = NULL; 11286 argno_t argno = argno_from_arg(arg + 1); 11287 const char *ref_tname = NULL; 11288 int arg_type; 11289 11290 t = btf_type_skip_modifiers(meta->btf, args[arg].type, NULL); 11291 11292 /* Scalar arguments are classified from their BTF suffix/name alone. */ 11293 if (btf_type_is_scalar(t)) { 11294 if (is_kfunc_arg_constant(meta->btf, &args[arg])) 11295 return KF_ARG_CONST; 11296 if (is_kfunc_arg_const_mem_size(meta->btf, &args[arg])) 11297 return KF_ARG_CONST_MEM_SIZE; 11298 if (is_kfunc_arg_mem_size(meta->btf, &args[arg])) 11299 return KF_ARG_MEM_SIZE; 11300 if (is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdonly_buf_size") || 11301 is_kfunc_arg_scalar_with_name(meta->btf, &args[arg], "rdwr_buf_size")) 11302 return KF_ARG_CONST_ALLOC_SIZE_OR_ZERO; 11303 return KF_ARG_ANYTHING; 11304 } 11305 11306 if (!btf_type_is_ptr(t)) { 11307 verbose(env, "Unrecognized %s type %s\n", 11308 reg_arg_name(env, argno), btf_type_str(t)); 11309 return -EINVAL; 11310 } 11311 ref_t = btf_type_skip_modifiers(meta->btf, t->type, NULL); 11312 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off); 11313 11314 /* In this function, we verify the kfunc's BTF as per the argument type, 11315 * leaving the rest of the verification with respect to the register 11316 * type to our caller. When a set of conditions hold in the BTF type of 11317 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11318 */ 11319 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 11320 meta->func_id == special_kfunc_list[KF_bpf_session_is_return] || 11321 meta->func_id == special_kfunc_list[KF_bpf_session_cookie]) 11322 arg_type = KF_ARG_PTR_TO_CTX; 11323 else if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg)) 11324 arg_type = KF_ARG_PTR_TO_CTX; 11325 else if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg])) 11326 arg_type = KF_ARG_PTR_TO_ALLOC_BTF_ID; 11327 else if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg])) 11328 arg_type = KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11329 else if (is_kfunc_arg_dynptr(meta->btf, &args[arg])) 11330 arg_type = KF_ARG_PTR_TO_DYNPTR; 11331 else if (is_kfunc_arg_iter(meta, arg, &args[arg])) 11332 arg_type = KF_ARG_PTR_TO_ITER; 11333 else if (is_kfunc_arg_list_head(meta->btf, &args[arg])) 11334 arg_type = KF_ARG_PTR_TO_LIST_HEAD; 11335 else if (is_kfunc_arg_list_node(meta->btf, &args[arg])) 11336 arg_type = KF_ARG_PTR_TO_LIST_NODE; 11337 else if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg])) 11338 arg_type = KF_ARG_PTR_TO_RB_ROOT; 11339 else if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg])) 11340 arg_type = KF_ARG_PTR_TO_RB_NODE; 11341 else if (is_kfunc_arg_const_str(meta->btf, &args[arg])) 11342 arg_type = KF_ARG_PTR_TO_CONST_STR; 11343 else if (is_kfunc_arg_const_map(meta->btf, &args[arg])) 11344 arg_type = KF_ARG_CONST_MAP_PTR; 11345 else if (is_kfunc_arg_map(meta->btf, &args[arg])) 11346 arg_type = KF_ARG_PTR_TO_BTF_ID; 11347 else if (is_kfunc_arg_wq(meta->btf, &args[arg])) 11348 arg_type = KF_ARG_PTR_TO_WORKQUEUE; 11349 else if (is_kfunc_arg_timer(meta->btf, &args[arg])) 11350 arg_type = KF_ARG_PTR_TO_TIMER; 11351 else if (is_kfunc_arg_task_work(meta->btf, &args[arg])) 11352 arg_type = KF_ARG_PTR_TO_TASK_WORK; 11353 else if (is_kfunc_arg_irq_flag(meta->btf, &args[arg])) 11354 arg_type = KF_ARG_PTR_TO_IRQ_FLAG; 11355 else if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg])) 11356 arg_type = KF_ARG_PTR_TO_RES_SPIN_LOCK; 11357 else if (is_kfunc_arg_callback(env, meta->btf, &args[arg])) 11358 arg_type = KF_ARG_PTR_TO_CALLBACK; 11359 else if (is_kfunc_arg_arena(meta->btf, &args[arg])) { 11360 if (!bpf_jit_supports_arena_args()) { 11361 verbose(env, "JIT does not support kfunc %s() with arena pointer arguments\n", 11362 meta->func_name); 11363 return -ENOTSUPP; 11364 } 11365 if (!env->prog->aux->arena) { 11366 verbose(env, 11367 "%s arena pointer requires a program with an associated arena\n", 11368 reg_arg_name(env, argno)); 11369 return -EINVAL; 11370 } 11371 if (reg_from_argno(argno) < 0) { 11372 verbose(env, "%s arena pointer cannot be a stack argument\n", 11373 reg_arg_name(env, argno)); 11374 return -EINVAL; 11375 } 11376 /* 11377 * Both suffixes accept a constant zero. The function model determines 11378 * whether the JIT rebases it to the arena base or preserves NULL. 11379 * The common nullable path below records that verifier property. 11380 */ 11381 arg_type = KF_ARG_PTR_TO_ARENA; 11382 } else if (arg + 1 < nargs && 11383 (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1]) || 11384 is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1]))) { 11385 if (!btf_type_is_void(ref_t) && !btf_type_is_scalar(ref_t) && 11386 !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0)) { 11387 verbose(env, "%s pointer type %s %s must point to void, scalar, or struct with scalar\n", 11388 reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname); 11389 return -EINVAL; 11390 } 11391 arg_type = KF_ARG_PTR_TO_MEM; 11392 } else if (btf_type_is_struct(ref_t)) 11393 /* A pointer to a struct without a size argument is classified as KF_ARG_PTR_TO_BTF_ID */ 11394 arg_type = KF_ARG_PTR_TO_BTF_ID; 11395 else { 11396 /* 11397 * Otherwise this is a fixed-size memory buffer supported by 11398 * check_helper_mem_access(): a pointer to a scalar or a struct of 11399 * scalars. The access size is derived from the pointed-to BTF type. 11400 */ 11401 if (!btf_type_is_scalar(ref_t) && 11402 !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0)) { 11403 verbose(env, "%s pointer type %s %s must point to scalar, or struct with scalar\n", 11404 reg_arg_name(env, argno), btf_type_str(ref_t), ref_tname); 11405 return -EINVAL; 11406 } 11407 arg_type = KF_ARG_PTR_TO_MEM | MEM_FIXED_SIZE; 11408 } 11409 11410 if (is_kfunc_arg_nullable(meta->btf, &args[arg])) 11411 arg_type |= PTR_MAYBE_NULL; 11412 11413 return arg_type; 11414 } 11415 11416 static int gen_kfunc_arg_proto(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 11417 struct bpf_func_proto *proto) 11418 { 11419 const struct btf *btf = meta->btf; 11420 const struct btf_param *args; 11421 u32 i, nargs; 11422 int arg_type; 11423 11424 args = (const struct btf_param *)(meta->func_proto + 1); 11425 nargs = btf_type_vlen(meta->func_proto); 11426 if (nargs > MAX_BPF_FUNC_ARGS) { 11427 verbose(env, "Function %s has %d > %d args\n", meta->func_name, 11428 nargs, MAX_BPF_FUNC_ARGS); 11429 return -EINVAL; 11430 } 11431 if (nargs > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) { 11432 verbose(env, "JIT does not support kfunc %s() with %d args\n", 11433 meta->func_name, nargs); 11434 return -ENOTSUPP; 11435 } 11436 11437 for (i = 0; i < nargs; i++) { 11438 if (is_kfunc_arg_prog_aux(btf, &args[i]) || 11439 is_kfunc_arg_ignore(btf, &args[i]) || 11440 is_kfunc_arg_implicit(meta, i)) 11441 continue; 11442 11443 arg_type = get_kfunc_arg_type(env, meta, args, i, nargs); 11444 if (arg_type < 0) 11445 return arg_type; 11446 11447 proto->arg_type[i] = arg_type; 11448 } 11449 11450 return 0; 11451 } 11452 11453 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11454 struct bpf_reg_state *reg, 11455 const struct btf_type *ref_t, 11456 const char *ref_tname, u32 ref_id, 11457 struct bpf_call_arg_meta *meta, 11458 int arg, argno_t argno) 11459 { 11460 const struct btf_type *reg_ref_t; 11461 bool strict_type_match = false; 11462 const struct btf *reg_btf; 11463 const char *reg_ref_tname; 11464 bool taking_projection; 11465 bool struct_same; 11466 u32 reg_ref_id; 11467 11468 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11469 reg_btf = reg->btf; 11470 reg_ref_id = reg->btf_id; 11471 } else { 11472 reg_btf = btf_vmlinux; 11473 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11474 } 11475 11476 /* Enforce strict type matching for calls to kfuncs that are acquiring 11477 * or releasing a reference, or are no-cast aliases. We do _not_ 11478 * enforce strict matching for kfuncs by default, 11479 * as we want to enable BPF programs to pass types that are bitwise 11480 * equivalent without forcing them to explicitly cast with something 11481 * like bpf_cast_to_kern_ctx(). 11482 * 11483 * For example, say we had a type like the following: 11484 * 11485 * struct bpf_cpumask { 11486 * cpumask_t cpumask; 11487 * refcount_t usage; 11488 * }; 11489 * 11490 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11491 * to a struct cpumask, so it would be safe to pass a struct 11492 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11493 * 11494 * The philosophy here is similar to how we allow scalars of different 11495 * types to be passed to kfuncs as long as the size is the same. The 11496 * only difference here is that we're simply allowing 11497 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11498 * resolve types. 11499 */ 11500 if ((is_kfunc_release(meta) && reg_is_referenced(env, reg)) || 11501 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11502 strict_type_match = true; 11503 11504 WARN_ON_ONCE(is_kfunc_release(meta) && !tnum_is_const(reg->var_off)); 11505 11506 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11507 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11508 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->var_off.value, 11509 meta->btf, ref_id, strict_type_match, 11510 !type_is_alloc(reg->type)); 11511 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11512 * actually use it -- it must cast to the underlying type. So we allow 11513 * caller to pass in the underlying type. 11514 */ 11515 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11516 if (!taking_projection && !struct_same) { 11517 verbose(env, "kernel function %s %s expected pointer to %s %s but %s has a pointer to %s %s\n", 11518 meta->func_name, reg_arg_name(env, argno), 11519 btf_type_str(ref_t), ref_tname, reg_arg_name(env, argno), 11520 btf_type_str(reg_ref_t), reg_ref_tname); 11521 return -EINVAL; 11522 } 11523 return 0; 11524 } 11525 11526 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 11527 struct bpf_call_arg_meta *meta) 11528 { 11529 int err, spi, kfunc_class = IRQ_NATIVE_KFUNC; 11530 bool irq_save; 11531 11532 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] || 11533 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) { 11534 irq_save = true; 11535 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 11536 kfunc_class = IRQ_LOCK_KFUNC; 11537 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] || 11538 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) { 11539 irq_save = false; 11540 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 11541 kfunc_class = IRQ_LOCK_KFUNC; 11542 } else { 11543 verifier_bug(env, "unknown irq flags kfunc"); 11544 return -EFAULT; 11545 } 11546 11547 if (irq_save) { 11548 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 11549 verbose(env, "expected uninitialized irq flag as %s\n", 11550 reg_arg_name(env, argno)); 11551 return -EINVAL; 11552 } 11553 11554 err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW, 11555 BPF_WRITE, -1, false, false); 11556 if (err) 11557 return err; 11558 11559 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 11560 if (err) 11561 return err; 11562 } else { 11563 err = is_irq_flag_reg_valid_init(env, reg); 11564 if (err) { 11565 verbose(env, "expected an initialized irq flag as %s\n", 11566 reg_arg_name(env, argno)); 11567 return err; 11568 } 11569 11570 spi = irq_flag_get_spi(env, reg); 11571 if (spi < 0) 11572 return spi; 11573 11574 mark_stack_slots_scratched(env, spi, 1); 11575 11576 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 11577 if (err) 11578 return err; 11579 11580 if (!in_rcu_cs(env)) 11581 invalidate_rcu_protected_refs(env); 11582 } 11583 return 0; 11584 } 11585 11586 11587 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11588 { 11589 struct btf_record *rec = reg_btf_record(reg); 11590 11591 if (!env->cur_state->active_locks) { 11592 verifier_bug(env, "%s w/o active lock", __func__); 11593 return -EFAULT; 11594 } 11595 11596 if (type_flag(reg->type) & NON_OWN_REF) { 11597 verifier_bug(env, "NON_OWN_REF already set"); 11598 return -EFAULT; 11599 } 11600 11601 reg->type |= NON_OWN_REF; 11602 if (rec->refcount_off >= 0) 11603 reg->type |= MEM_RCU; 11604 11605 return 0; 11606 } 11607 11608 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id) 11609 { 11610 struct bpf_func_state *unused; 11611 struct bpf_reg_state *reg; 11612 11613 WARN_ON_ONCE(release_reference_nomark(env->cur_state, id)); 11614 11615 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11616 if (reg->id == id) { 11617 reg->id = 0; 11618 ref_set_non_owning(env, reg); 11619 } 11620 })); 11621 11622 return; 11623 } 11624 11625 /* Implementation details: 11626 * 11627 * Each register points to some region of memory, which we define as an 11628 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11629 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11630 * allocation. The lock and the data it protects are colocated in the same 11631 * memory region. 11632 * 11633 * Hence, everytime a register holds a pointer value pointing to such 11634 * allocation, the verifier preserves a unique reg->id for it. 11635 * 11636 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11637 * bpf_spin_lock is called. 11638 * 11639 * To enable this, lock state in the verifier captures two values: 11640 * active_lock.ptr = Register's type specific pointer 11641 * active_lock.id = A unique ID for each register pointer value 11642 * 11643 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11644 * supported register types. 11645 * 11646 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11647 * allocated objects is the reg->btf pointer. 11648 * 11649 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11650 * can establish the provenance of the map value statically for each distinct 11651 * lookup into such maps. They always contain a single map value hence unique 11652 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11653 * 11654 * So, in case of global variables, they use array maps with max_entries = 1, 11655 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11656 * into the same map value as max_entries is 1, as described above). 11657 * 11658 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11659 * outer map pointer (in verifier context), but each lookup into an inner map 11660 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11661 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11662 * will get different reg->id assigned to each lookup, hence different 11663 * active_lock.id. 11664 * 11665 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11666 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11667 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11668 */ 11669 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11670 { 11671 struct bpf_reference_state *s; 11672 void *ptr; 11673 u32 id; 11674 11675 switch ((int)reg->type) { 11676 case PTR_TO_MAP_VALUE: 11677 ptr = reg->map_ptr; 11678 break; 11679 case PTR_TO_BTF_ID | MEM_ALLOC: 11680 ptr = reg->btf; 11681 break; 11682 default: 11683 verifier_bug(env, "unknown reg type for lock check"); 11684 return -EFAULT; 11685 } 11686 id = reg->id; 11687 11688 if (!env->cur_state->active_locks) 11689 return -EINVAL; 11690 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 11691 if (!s) { 11692 verbose(env, "held lock and object are not in the same allocation\n"); 11693 return -EINVAL; 11694 } 11695 return 0; 11696 } 11697 11698 static bool is_bpf_list_api_kfunc(u32 btf_id) 11699 { 11700 return is_bpf_list_push_kfunc(btf_id) || 11701 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11702 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 11703 btf_id == special_kfunc_list[KF_bpf_list_del] || 11704 btf_id == special_kfunc_list[KF_bpf_list_front] || 11705 btf_id == special_kfunc_list[KF_bpf_list_back] || 11706 btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11707 btf_id == special_kfunc_list[KF_bpf_list_is_last] || 11708 btf_id == special_kfunc_list[KF_bpf_list_empty]; 11709 } 11710 11711 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11712 { 11713 return is_bpf_rbtree_add_kfunc(btf_id) || 11714 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11715 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 11716 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 11717 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11718 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 11719 } 11720 11721 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id) 11722 { 11723 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 11724 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 11725 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 11726 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]; 11727 } 11728 11729 static bool kfunc_spin_allowed(struct bpf_verifier_env *env, s32 func_id, s16 offset) 11730 { 11731 struct bpf_kfunc_meta kfunc; 11732 int err; 11733 11734 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 11735 if (err || !kfunc.flags) 11736 return false; 11737 11738 return *kfunc.flags & KF_SPINLOCK_SAFE; 11739 } 11740 11741 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11742 { 11743 return is_bpf_rbtree_add_kfunc(btf_id); 11744 } 11745 11746 static bool is_async_callback_calling_kfunc(u32 btf_id) 11747 { 11748 return is_bpf_wq_set_callback_kfunc(btf_id) || 11749 is_task_work_add_kfunc(btf_id); 11750 } 11751 11752 bool bpf_is_throw_kfunc(struct bpf_insn *insn) 11753 { 11754 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11755 insn->imm == special_kfunc_list[KF_bpf_throw]; 11756 } 11757 11758 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id) 11759 { 11760 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback]; 11761 } 11762 11763 static bool is_callback_calling_kfunc(u32 btf_id) 11764 { 11765 return is_sync_callback_calling_kfunc(btf_id) || 11766 is_async_callback_calling_kfunc(btf_id); 11767 } 11768 11769 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11770 { 11771 return is_bpf_rbtree_api_kfunc(btf_id); 11772 } 11773 11774 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11775 enum btf_field_type head_field_type, 11776 u32 kfunc_btf_id) 11777 { 11778 bool ret; 11779 11780 switch (head_field_type) { 11781 case BPF_LIST_HEAD: 11782 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11783 break; 11784 case BPF_RB_ROOT: 11785 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11786 break; 11787 default: 11788 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11789 btf_field_type_name(head_field_type)); 11790 return false; 11791 } 11792 11793 if (!ret) 11794 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11795 btf_field_type_name(head_field_type)); 11796 return ret; 11797 } 11798 11799 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11800 enum btf_field_type node_field_type, 11801 u32 kfunc_btf_id) 11802 { 11803 bool ret; 11804 11805 switch (node_field_type) { 11806 case BPF_LIST_NODE: 11807 ret = is_bpf_list_push_kfunc(kfunc_btf_id) || 11808 kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] || 11809 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11810 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last]; 11811 break; 11812 case BPF_RB_NODE: 11813 ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) || 11814 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11815 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11816 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 11817 break; 11818 default: 11819 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11820 btf_field_type_name(node_field_type)); 11821 return false; 11822 } 11823 11824 if (!ret) 11825 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11826 btf_field_type_name(node_field_type)); 11827 return ret; 11828 } 11829 11830 static int 11831 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11832 struct bpf_reg_state *reg, argno_t argno, 11833 struct bpf_call_arg_meta *meta, 11834 enum btf_field_type head_field_type, 11835 struct btf_field **head_field) 11836 { 11837 const char *head_type_name; 11838 struct btf_field *field; 11839 struct btf_record *rec; 11840 u32 head_off; 11841 11842 if (meta->btf != btf_vmlinux) { 11843 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11844 return -EFAULT; 11845 } 11846 11847 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11848 return -EFAULT; 11849 11850 head_type_name = btf_field_type_name(head_field_type); 11851 if (!tnum_is_const(reg->var_off)) { 11852 verbose(env, 11853 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11854 reg_arg_name(env, argno), head_type_name); 11855 return -EINVAL; 11856 } 11857 11858 rec = reg_btf_record(reg); 11859 head_off = reg->var_off.value; 11860 field = btf_record_find(rec, head_off, head_field_type); 11861 if (!field) { 11862 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11863 return -EINVAL; 11864 } 11865 11866 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11867 if (check_reg_allocation_locked(env, reg)) { 11868 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11869 rec->spin_lock_off, head_type_name); 11870 return -EINVAL; 11871 } 11872 11873 if (*head_field) { 11874 verifier_bug(env, "repeating %s arg", head_type_name); 11875 return -EFAULT; 11876 } 11877 *head_field = field; 11878 return 0; 11879 } 11880 11881 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11882 struct bpf_reg_state *reg, argno_t argno, 11883 struct bpf_call_arg_meta *meta) 11884 { 11885 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD, 11886 &meta->arg_list_head.field); 11887 } 11888 11889 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11890 struct bpf_reg_state *reg, argno_t argno, 11891 struct bpf_call_arg_meta *meta) 11892 { 11893 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT, 11894 &meta->arg_rbtree_root.field); 11895 } 11896 11897 static int 11898 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11899 struct bpf_reg_state *reg, argno_t argno, 11900 struct bpf_call_arg_meta *meta, 11901 enum btf_field_type head_field_type, 11902 enum btf_field_type node_field_type, 11903 struct btf_field **node_field) 11904 { 11905 const char *node_type_name; 11906 const struct btf_type *et, *t; 11907 struct btf_field *field; 11908 u32 node_off; 11909 11910 if (meta->btf != btf_vmlinux) { 11911 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11912 return -EFAULT; 11913 } 11914 11915 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11916 return -EFAULT; 11917 11918 node_type_name = btf_field_type_name(node_field_type); 11919 if (!tnum_is_const(reg->var_off)) { 11920 verbose(env, 11921 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11922 reg_arg_name(env, argno), node_type_name); 11923 return -EINVAL; 11924 } 11925 11926 node_off = reg->var_off.value; 11927 field = reg_find_field_offset(reg, node_off, node_field_type); 11928 if (!field) { 11929 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11930 return -EINVAL; 11931 } 11932 11933 field = *node_field; 11934 11935 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11936 t = btf_type_by_id(reg->btf, reg->btf_id); 11937 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11938 field->graph_root.value_btf_id, true, 11939 !type_is_alloc(reg->type))) { 11940 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11941 "in struct %s, but arg is at offset=%d in struct %s\n", 11942 btf_field_type_name(head_field_type), 11943 btf_field_type_name(node_field_type), 11944 field->graph_root.node_offset, 11945 btf_name_by_offset(field->graph_root.btf, et->name_off), 11946 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11947 return -EINVAL; 11948 } 11949 meta->arg_btf = reg->btf; 11950 meta->arg_btf_id = reg->btf_id; 11951 11952 if (node_off != field->graph_root.node_offset) { 11953 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11954 node_off, btf_field_type_name(node_field_type), 11955 field->graph_root.node_offset, 11956 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11957 return -EINVAL; 11958 } 11959 11960 return 0; 11961 } 11962 11963 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11964 struct bpf_reg_state *reg, argno_t argno, 11965 struct bpf_call_arg_meta *meta) 11966 { 11967 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 11968 BPF_LIST_HEAD, BPF_LIST_NODE, 11969 &meta->arg_list_head.field); 11970 } 11971 11972 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11973 struct bpf_reg_state *reg, argno_t argno, 11974 struct bpf_call_arg_meta *meta) 11975 { 11976 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 11977 BPF_RB_ROOT, BPF_RB_NODE, 11978 &meta->arg_rbtree_root.field); 11979 } 11980 11981 /* 11982 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11983 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11984 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11985 * them can only be attached to some specific hook points. 11986 */ 11987 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11988 { 11989 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11990 11991 switch (prog_type) { 11992 case BPF_PROG_TYPE_LSM: 11993 return true; 11994 case BPF_PROG_TYPE_TRACING: 11995 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11996 return true; 11997 fallthrough; 11998 default: 11999 return in_sleepable(env); 12000 } 12001 } 12002 12003 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 12004 int insn_idx) 12005 { 12006 const char *func_name = meta->func_name, *ref_tname; 12007 struct bpf_func_state *caller = cur_func(env); 12008 struct bpf_reg_state *regs = cur_regs(env); 12009 const struct btf *btf = meta->btf; 12010 const struct btf_param *args; 12011 struct btf_record *rec; 12012 u32 i, nargs; 12013 int ret; 12014 12015 args = (const struct btf_param *)(meta->func_proto + 1); 12016 nargs = btf_type_vlen(meta->func_proto); 12017 12018 ret = check_outgoing_stack_args(env, caller, nargs); 12019 if (ret) 12020 return ret; 12021 12022 /* Check that BTF function arguments match actual types that the 12023 * verifier sees. 12024 */ 12025 for (i = 0; i < nargs; i++) { 12026 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 12027 const struct btf_type *t, *ref_t, *resolve_ret; 12028 enum bpf_arg_type arg_type = ARG_DONTCARE; 12029 argno_t argno = argno_from_arg(i + 1); 12030 int regno = reg_from_argno(argno); 12031 bool btf_id_fixed_off_ok = true; 12032 u32 ref_id, type_size; 12033 int kf_arg_type = meta->fn->arg_type[i]; 12034 12035 if (is_kfunc_arg_prog_aux(btf, &args[i])) { 12036 /* Reject repeated use bpf_prog_aux */ 12037 if (meta->arg_prog) { 12038 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc"); 12039 return -EFAULT; 12040 } 12041 if (regno < 0) { 12042 verbose(env, "%s prog->aux cannot be a stack argument\n", 12043 reg_arg_name(env, argno)); 12044 return -EINVAL; 12045 } 12046 meta->arg_prog = true; 12047 cur_aux(env)->arg_prog = regno; 12048 continue; 12049 } 12050 12051 if (is_kfunc_arg_ignore(btf, &args[i]) || is_kfunc_arg_implicit(meta, i)) 12052 continue; 12053 12054 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 12055 12056 if (btf_type_is_ptr(t) && (bpf_register_is_null(reg) || type_may_be_null(reg->type)) && 12057 !type_may_be_null(kf_arg_type)) { 12058 verbose(env, "Possibly NULL pointer passed to trusted %s\n", 12059 reg_arg_name(env, argno)); 12060 return -EACCES; 12061 } 12062 12063 if (regno == meta->release_regno && !is_kfunc_arg_dynptr(meta->btf, &args[i]) && 12064 !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) { 12065 verbose(env, "release kfunc %s expects referenced PTR_TO_BTF_ID passed to %s\n", 12066 func_name, reg_arg_name(env, argno)); 12067 return -EINVAL; 12068 } 12069 12070 if (reg_is_referenced(env, reg)) 12071 update_ref_obj(&meta->ref_obj, reg); 12072 12073 if (btf_type_is_ptr(t)) { 12074 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 12075 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12076 } 12077 12078 12079 if (bpf_register_is_null(reg) && type_may_be_null(kf_arg_type)) 12080 continue; 12081 12082 if (is_kfunc_arg_map(btf, &args[i])) { 12083 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12084 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12085 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12086 } 12087 12088 switch (base_type(kf_arg_type)) { 12089 case KF_ARG_CONST: 12090 case KF_ARG_CONST_MEM_SIZE: 12091 case KF_ARG_MEM_SIZE: 12092 case KF_ARG_ANYTHING: 12093 case KF_ARG_CONST_ALLOC_SIZE_OR_ZERO: 12094 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12095 case KF_ARG_PTR_TO_BTF_ID: 12096 case KF_ARG_CONST_MAP_PTR: 12097 case KF_ARG_PTR_TO_ITER: 12098 case KF_ARG_PTR_TO_LIST_HEAD: 12099 case KF_ARG_PTR_TO_LIST_NODE: 12100 case KF_ARG_PTR_TO_RB_ROOT: 12101 case KF_ARG_PTR_TO_RB_NODE: 12102 case KF_ARG_PTR_TO_MEM: 12103 case KF_ARG_PTR_TO_CALLBACK: 12104 case KF_ARG_PTR_TO_CONST_STR: 12105 case KF_ARG_PTR_TO_WORKQUEUE: 12106 case KF_ARG_PTR_TO_TIMER: 12107 case KF_ARG_PTR_TO_TASK_WORK: 12108 case KF_ARG_PTR_TO_IRQ_FLAG: 12109 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12110 case KF_ARG_PTR_TO_ARENA: 12111 break; 12112 case KF_ARG_PTR_TO_DYNPTR: 12113 arg_type = ARG_PTR_TO_DYNPTR; 12114 break; 12115 case KF_ARG_PTR_TO_CTX: 12116 arg_type = ARG_PTR_TO_CTX; 12117 break; 12118 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12119 arg_type = ARG_PTR_TO_BTF_ID; 12120 btf_id_fixed_off_ok = false; 12121 break; 12122 default: 12123 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type); 12124 return -EFAULT; 12125 } 12126 12127 if (regno == meta->release_regno) 12128 arg_type |= OBJ_RELEASE; 12129 ret = __check_func_arg_reg_off(env, reg, argno, arg_type, 12130 btf_id_fixed_off_ok); 12131 if (ret < 0) 12132 return ret; 12133 12134 switch (base_type(kf_arg_type)) { 12135 case KF_ARG_CONST: 12136 if (reg->type != SCALAR_VALUE) { 12137 verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno)); 12138 return -EINVAL; 12139 } 12140 12141 ret = process_const_arg(env, reg, argno, meta); 12142 if (ret < 0) 12143 return ret; 12144 break; 12145 case KF_ARG_ANYTHING: 12146 if (reg->type != SCALAR_VALUE) { 12147 verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno)); 12148 return -EINVAL; 12149 } 12150 break; 12151 case KF_ARG_CONST_ALLOC_SIZE_OR_ZERO: 12152 if (reg->type != SCALAR_VALUE) { 12153 verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno)); 12154 return -EINVAL; 12155 } 12156 12157 if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) 12158 meta->r0_rdonly = true; 12159 ret = process_const_alloc_mem_size(env, reg, argno, &meta->ret_mem); 12160 if (ret < 0) 12161 return ret; 12162 break; 12163 case KF_ARG_PTR_TO_CTX: 12164 if (reg->type != PTR_TO_CTX) { 12165 verbose(env, "%s expected pointer to ctx, but got %s\n", 12166 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 12167 return -EINVAL; 12168 } 12169 12170 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12171 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 12172 if (ret < 0) 12173 return -EINVAL; 12174 meta->ret_btf_id = ret; 12175 } 12176 break; 12177 case KF_ARG_PTR_TO_ARENA: 12178 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 12179 verbose(env, "%s is not a pointer to arena or scalar\n", 12180 reg_arg_name(env, argno)); 12181 return -EINVAL; 12182 } 12183 break; 12184 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12185 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 12186 if (!is_bpf_obj_drop_kfunc(meta->func_id)) { 12187 verbose(env, "%s expected for bpf_obj_drop()\n", 12188 reg_arg_name(env, argno)); 12189 return -EINVAL; 12190 } 12191 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 12192 if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) { 12193 verbose(env, "%s expected for bpf_percpu_obj_drop()\n", 12194 reg_arg_name(env, argno)); 12195 return -EINVAL; 12196 } 12197 } else { 12198 verbose(env, "%s expected pointer to allocated object\n", 12199 reg_arg_name(env, argno)); 12200 return -EINVAL; 12201 } 12202 if (!reg_is_referenced(env, reg)) { 12203 verbose(env, "allocated object must be referenced\n"); 12204 return -EINVAL; 12205 } 12206 if (meta->btf == btf_vmlinux) { 12207 meta->arg_btf = reg->btf; 12208 meta->arg_btf_id = reg->btf_id; 12209 } 12210 break; 12211 case KF_ARG_PTR_TO_DYNPTR: 12212 { 12213 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 12214 12215 if (is_kfunc_arg_uninit(btf, &args[i])) 12216 dynptr_arg_type |= MEM_UNINIT; 12217 12218 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 12219 dynptr_arg_type |= DYNPTR_TYPE_SKB; 12220 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 12221 dynptr_arg_type |= DYNPTR_TYPE_XDP; 12222 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) { 12223 dynptr_arg_type |= DYNPTR_TYPE_SKB_META; 12224 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 12225 dynptr_arg_type |= DYNPTR_TYPE_FILE; 12226 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) { 12227 dynptr_arg_type |= DYNPTR_TYPE_FILE | OBJ_RELEASE; 12228 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 12229 (dynptr_arg_type & MEM_UNINIT)) { 12230 enum bpf_dynptr_type parent_type = meta->dynptr.type; 12231 12232 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 12233 verifier_bug(env, "no dynptr type for parent of clone"); 12234 return -EFAULT; 12235 } 12236 12237 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12238 } 12239 12240 ret = process_dynptr_func(env, reg, argno, insn_idx, dynptr_arg_type, 12241 &meta->ref_obj, &meta->dynptr); 12242 if (ret < 0) 12243 return ret; 12244 break; 12245 } 12246 case KF_ARG_PTR_TO_ITER: 12247 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12248 if (!check_css_task_iter_allowlist(env)) { 12249 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12250 return -EINVAL; 12251 } 12252 } 12253 ret = process_iter_arg(env, reg, argno, insn_idx, meta); 12254 if (ret < 0) 12255 return ret; 12256 break; 12257 case KF_ARG_PTR_TO_LIST_HEAD: 12258 if (reg->type != PTR_TO_MAP_VALUE && 12259 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12260 verbose(env, "%s expected pointer to map value or allocated object\n", 12261 reg_arg_name(env, argno)); 12262 return -EINVAL; 12263 } 12264 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 12265 !reg_is_referenced(env, reg)) { 12266 verbose(env, "allocated object must be referenced\n"); 12267 return -EINVAL; 12268 } 12269 ret = process_kf_arg_ptr_to_list_head(env, reg, argno, meta); 12270 if (ret < 0) 12271 return ret; 12272 break; 12273 case KF_ARG_PTR_TO_RB_ROOT: 12274 if (reg->type != PTR_TO_MAP_VALUE && 12275 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12276 verbose(env, "%s expected pointer to map value or allocated object\n", 12277 reg_arg_name(env, argno)); 12278 return -EINVAL; 12279 } 12280 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 12281 !reg_is_referenced(env, reg)) { 12282 verbose(env, "allocated object must be referenced\n"); 12283 return -EINVAL; 12284 } 12285 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta); 12286 if (ret < 0) 12287 return ret; 12288 break; 12289 case KF_ARG_PTR_TO_LIST_NODE: 12290 if (is_kfunc_arg_nonown_allowed(btf, &args[i]) && 12291 type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg)) { 12292 /* Allow bpf_list_front/back return value for 12293 * __nonown_allowed list-node arguments. 12294 */ 12295 goto check_ok; 12296 } 12297 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12298 verbose(env, "%s expected pointer to allocated object\n", 12299 reg_arg_name(env, argno)); 12300 return -EINVAL; 12301 } 12302 if (!reg_is_referenced(env, reg)) { 12303 verbose(env, "allocated object must be referenced\n"); 12304 return -EINVAL; 12305 } 12306 check_ok: 12307 ret = process_kf_arg_ptr_to_list_node(env, reg, argno, meta); 12308 if (ret < 0) 12309 return ret; 12310 break; 12311 case KF_ARG_PTR_TO_RB_NODE: 12312 if (is_bpf_rbtree_add_kfunc(meta->func_id)) { 12313 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12314 verbose(env, "%s expected pointer to allocated object\n", 12315 reg_arg_name(env, argno)); 12316 return -EINVAL; 12317 } 12318 if (!reg_is_referenced(env, reg)) { 12319 verbose(env, "allocated object must be referenced\n"); 12320 return -EINVAL; 12321 } 12322 } else { 12323 if (!type_is_non_owning_ref(reg->type) && 12324 !reg_is_referenced(env, reg)) { 12325 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name); 12326 return -EINVAL; 12327 } 12328 if (in_rbtree_lock_required_cb(env)) { 12329 verbose(env, "%s not allowed in rbtree cb\n", func_name); 12330 return -EINVAL; 12331 } 12332 } 12333 12334 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta); 12335 if (ret < 0) 12336 return ret; 12337 break; 12338 case KF_ARG_CONST_MAP_PTR: 12339 if (base_type(reg->type) != CONST_PTR_TO_MAP || 12340 type_may_be_null(reg->type)) { 12341 verbose(env, "pointer in %s isn't map pointer\n", 12342 reg_arg_name(env, argno)); 12343 return -EINVAL; 12344 } 12345 ret = process_map_ptr_arg(env, reg, argno, meta); 12346 if (ret < 0) 12347 return ret; 12348 break; 12349 case KF_ARG_PTR_TO_BTF_ID: 12350 /* Only base_type is checked, further checks are done here */ 12351 if (base_type(reg->type) == PTR_TO_BTF_ID || 12352 reg2btf_ids[base_type(reg->type)]) { 12353 if (!is_trusted_reg(env, reg) || 12354 bpf_type_has_unsafe_modifiers(reg->type)) { 12355 if (!is_kfunc_rcu(meta)) { 12356 verbose(env, "%s must be referenced or trusted\n", 12357 reg_arg_name(env, argno)); 12358 return -EINVAL; 12359 } 12360 if (!is_rcu_reg(reg)) { 12361 verbose(env, "%s must be a rcu pointer\n", 12362 reg_arg_name(env, argno)); 12363 return -EINVAL; 12364 } 12365 } 12366 12367 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i, argno); 12368 if (ret < 0) 12369 return ret; 12370 break; 12371 } 12372 12373 if (!__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0)) { 12374 enum bpf_reg_type reg2btf_type = lookup_reg2btf_ids(ref_id); 12375 12376 verbose(env, "%s is %s expected %s %s", 12377 reg_arg_name(env, argno), reg_type_str(env, reg->type), 12378 btf_type_str(ref_t), ref_tname); 12379 if (reg2btf_type != NOT_INIT) 12380 verbose(env, " or %s", reg_type_str(env, reg2btf_type)); 12381 verbose(env, "\n"); 12382 return -EINVAL; 12383 } 12384 12385 /* 12386 * If the register does not contain btf id but the argument type is a pointer to 12387 * scalar-only struct, allow verifying it as a fixed size memory. 12388 */ 12389 kf_arg_type = KF_ARG_PTR_TO_MEM | MEM_FIXED_SIZE; 12390 fallthrough; 12391 case KF_ARG_PTR_TO_MEM: 12392 if (kf_arg_type & MEM_FIXED_SIZE) { 12393 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12394 if (IS_ERR(resolve_ret)) { 12395 verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n", 12396 reg_arg_name(env, argno), btf_type_str(ref_t), 12397 ref_tname, PTR_ERR(resolve_ret)); 12398 return -EINVAL; 12399 } 12400 ret = check_mem_reg(env, reg, argno, type_size, BPF_READ | BPF_WRITE, meta); 12401 if (ret < 0) 12402 return ret; 12403 } 12404 break; 12405 case KF_ARG_CONST_MEM_SIZE: 12406 ret = process_const_arg(env, reg, argno, meta); 12407 if (ret < 0) 12408 return ret; 12409 fallthrough; 12410 case KF_ARG_MEM_SIZE: 12411 { 12412 struct bpf_reg_state *buff_reg = get_func_arg_reg(caller, regs, i - 1); 12413 struct bpf_reg_state *size_reg = reg; 12414 argno_t buff_argno = argno_from_arg(i); 12415 12416 if (reg->type != SCALAR_VALUE) { 12417 verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno)); 12418 return -EINVAL; 12419 } 12420 12421 if (bpf_register_is_null(buff_reg)) 12422 break; 12423 12424 ret = check_mem_size_reg(env, buff_reg, size_reg, buff_argno, argno, 12425 BPF_READ | BPF_WRITE, true, meta); 12426 if (ret < 0) { 12427 verbose(env, "%s and ", reg_arg_name(env, buff_argno)); 12428 verbose(env, "%s memory, len pair leads to invalid memory access\n", 12429 reg_arg_name(env, argno)); 12430 return ret; 12431 } 12432 break; 12433 } 12434 case KF_ARG_PTR_TO_CALLBACK: 12435 if (reg->type != PTR_TO_FUNC) { 12436 verbose(env, "%s expected pointer to func\n", reg_arg_name(env, argno)); 12437 return -EINVAL; 12438 } 12439 meta->subprogno = reg->subprogno; 12440 break; 12441 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12442 if (!type_is_ptr_alloc_obj(reg->type)) { 12443 verbose(env, "%s is neither owning or non-owning ref\n", 12444 reg_arg_name(env, argno)); 12445 return -EINVAL; 12446 } 12447 if (!type_is_non_owning_ref(reg->type)) 12448 meta->arg_owning_ref = true; 12449 12450 rec = reg_btf_record(reg); 12451 if (!rec) { 12452 verifier_bug(env, "Couldn't find btf_record"); 12453 return -EFAULT; 12454 } 12455 12456 if (rec->refcount_off < 0) { 12457 verbose(env, "%s doesn't point to a type with bpf_refcount field\n", 12458 reg_arg_name(env, argno)); 12459 return -EINVAL; 12460 } 12461 12462 meta->arg_btf = reg->btf; 12463 meta->arg_btf_id = reg->btf_id; 12464 break; 12465 case KF_ARG_PTR_TO_CONST_STR: 12466 if (reg->type != PTR_TO_MAP_VALUE) { 12467 verbose(env, "%s doesn't point to a const string\n", 12468 reg_arg_name(env, argno)); 12469 return -EINVAL; 12470 } 12471 ret = check_arg_const_str(env, reg, argno); 12472 if (ret) 12473 return ret; 12474 break; 12475 case KF_ARG_PTR_TO_WORKQUEUE: 12476 if (reg->type != PTR_TO_MAP_VALUE) { 12477 verbose(env, "%s doesn't point to a map value\n", 12478 reg_arg_name(env, argno)); 12479 return -EINVAL; 12480 } 12481 ret = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map); 12482 if (ret < 0) 12483 return ret; 12484 break; 12485 case KF_ARG_PTR_TO_TIMER: 12486 if (reg->type != PTR_TO_MAP_VALUE) { 12487 verbose(env, "%s doesn't point to a map value\n", 12488 reg_arg_name(env, argno)); 12489 return -EINVAL; 12490 } 12491 ret = process_timer_func(env, reg, argno, &meta->map); 12492 if (ret < 0) 12493 return ret; 12494 break; 12495 case KF_ARG_PTR_TO_TASK_WORK: 12496 if (reg->type != PTR_TO_MAP_VALUE) { 12497 verbose(env, "%s doesn't point to a map value\n", 12498 reg_arg_name(env, argno)); 12499 return -EINVAL; 12500 } 12501 ret = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map); 12502 if (ret < 0) 12503 return ret; 12504 break; 12505 case KF_ARG_PTR_TO_IRQ_FLAG: 12506 if (reg->type != PTR_TO_STACK) { 12507 verbose(env, "%s doesn't point to an irq flag on stack\n", 12508 reg_arg_name(env, argno)); 12509 return -EINVAL; 12510 } 12511 ret = process_irq_flag(env, reg, argno, meta); 12512 if (ret < 0) 12513 return ret; 12514 break; 12515 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12516 { 12517 int flags = PROCESS_RES_LOCK; 12518 12519 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12520 verbose(env, "%s doesn't point to map value or allocated object\n", 12521 reg_arg_name(env, argno)); 12522 return -EINVAL; 12523 } 12524 12525 if (!is_bpf_res_spin_lock_kfunc(meta->func_id)) 12526 return -EFAULT; 12527 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 12528 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 12529 flags |= PROCESS_SPIN_LOCK; 12530 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 12531 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 12532 flags |= PROCESS_LOCK_IRQ; 12533 ret = process_spin_lock(env, reg, argno, flags); 12534 if (ret < 0) 12535 return ret; 12536 break; 12537 } 12538 } 12539 } 12540 12541 return 0; 12542 } 12543 12544 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, 12545 s32 func_id, 12546 s16 offset, 12547 struct bpf_call_arg_meta *meta) 12548 { 12549 struct bpf_kfunc_meta kfunc; 12550 int err; 12551 12552 memset(meta, 0, sizeof(*meta)); 12553 12554 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 12555 if (err) 12556 return err; 12557 12558 meta->btf = kfunc.btf; 12559 meta->func_id = kfunc.id; 12560 meta->func_proto = kfunc.proto; 12561 meta->func_name = kfunc.name; 12562 12563 if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog)) 12564 return -EACCES; 12565 12566 meta->kfunc_flags = *kfunc.flags; 12567 12568 /* Only support release referenced argument passed by register */ 12569 if (is_kfunc_release(meta)) 12570 meta->release_regno = BPF_REG_1; 12571 12572 return 0; 12573 } 12574 12575 /* 12576 * Determine how many bytes a helper accesses through a stack pointer at 12577 * argument position @arg (0-based, corresponding to R1-R5). 12578 * 12579 * Returns: 12580 * > 0 known read access size in bytes 12581 * 0 doesn't read anything directly 12582 * S64_MIN unknown 12583 * < 0 known write access of (-return) bytes 12584 */ 12585 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12586 int arg, int insn_idx) 12587 { 12588 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12589 const struct bpf_func_proto *fn; 12590 enum bpf_arg_type at; 12591 s64 size; 12592 12593 if (bpf_get_helper_proto(env, insn->imm, &fn) < 0) 12594 return S64_MIN; 12595 12596 at = fn->arg_type[arg]; 12597 12598 switch (base_type(at)) { 12599 case ARG_PTR_TO_MAP_KEY: 12600 case ARG_PTR_TO_MAP_VALUE: { 12601 bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY; 12602 u64 val; 12603 int i, map_reg; 12604 12605 for (i = 0; i < arg; i++) { 12606 if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR) 12607 break; 12608 } 12609 if (i >= arg) 12610 goto scan_all_maps; 12611 12612 map_reg = BPF_REG_1 + i; 12613 12614 if (!(aux->const_reg_map_mask & BIT(map_reg))) 12615 goto scan_all_maps; 12616 12617 i = aux->const_reg_vals[map_reg]; 12618 if (i < env->used_map_cnt) { 12619 size = is_key ? env->used_maps[i]->key_size 12620 : env->used_maps[i]->value_size; 12621 goto out; 12622 } 12623 scan_all_maps: 12624 /* 12625 * Map pointer is not known at this call site (e.g. different 12626 * maps on merged paths). Conservatively return the largest 12627 * key_size or value_size across all maps used by the program. 12628 */ 12629 val = 0; 12630 for (i = 0; i < env->used_map_cnt; i++) { 12631 struct bpf_map *map = env->used_maps[i]; 12632 u32 sz = is_key ? map->key_size : map->value_size; 12633 12634 if (sz > val) 12635 val = sz; 12636 if (map->inner_map_meta) { 12637 sz = is_key ? map->inner_map_meta->key_size 12638 : map->inner_map_meta->value_size; 12639 if (sz > val) 12640 val = sz; 12641 } 12642 } 12643 if (!val) 12644 return S64_MIN; 12645 size = val; 12646 goto out; 12647 } 12648 case ARG_PTR_TO_MEM: 12649 if (at & MEM_FIXED_SIZE) { 12650 size = fn->arg_size[arg]; 12651 goto out; 12652 } 12653 if (arg + 1 < ARRAY_SIZE(fn->arg_type) && 12654 arg_type_is_mem_size(fn->arg_type[arg + 1])) { 12655 int size_reg = BPF_REG_1 + arg + 1; 12656 12657 if (aux->const_reg_mask & BIT(size_reg)) { 12658 size = (s64)aux->const_reg_vals[size_reg]; 12659 goto out; 12660 } 12661 /* 12662 * Size arg is const on each path but differs across merged 12663 * paths. MAX_BPF_STACK is a safe upper bound for reads. 12664 */ 12665 if (at & MEM_UNINIT) 12666 return 0; 12667 return MAX_BPF_STACK; 12668 } 12669 return S64_MIN; 12670 case ARG_PTR_TO_DYNPTR: 12671 size = BPF_DYNPTR_SIZE; 12672 break; 12673 case ARG_PTR_TO_STACK: 12674 /* 12675 * Only used by bpf_calls_callback() helpers. The helper itself 12676 * doesn't access stack. The callback subprog does and it's 12677 * analyzed separately. 12678 */ 12679 return 0; 12680 default: 12681 return S64_MIN; 12682 } 12683 out: 12684 /* 12685 * MEM_UNINIT args are write-only: the helper initializes the 12686 * buffer without reading it. 12687 */ 12688 if (at & MEM_UNINIT) 12689 return -size; 12690 return size; 12691 } 12692 12693 /* 12694 * Determine how many bytes a kfunc accesses through a stack pointer at 12695 * argument position @arg (0-based, corresponding to R1-R5). 12696 * 12697 * Returns: 12698 * > 0 known read access size in bytes 12699 * 0 doesn't access memory through that argument (ex: not a pointer) 12700 * S64_MIN unknown 12701 * < 0 known write access of (-return) bytes 12702 */ 12703 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12704 int arg, int insn_idx) 12705 { 12706 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12707 struct bpf_call_arg_meta meta; 12708 const struct btf_param *args; 12709 const struct btf_type *t, *ref_t; 12710 const struct btf *btf; 12711 u32 nargs, type_size; 12712 s64 size; 12713 12714 if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0) 12715 return S64_MIN; 12716 12717 btf = meta.btf; 12718 args = btf_params(meta.func_proto); 12719 nargs = btf_type_vlen(meta.func_proto); 12720 if (arg >= nargs) 12721 return 0; 12722 12723 t = btf_type_skip_modifiers(btf, args[arg].type, NULL); 12724 if (!btf_type_is_ptr(t)) 12725 return 0; 12726 12727 /* dynptr: fixed 16-byte on-stack representation */ 12728 if (is_kfunc_arg_dynptr(btf, &args[arg])) { 12729 size = BPF_DYNPTR_SIZE; 12730 goto out; 12731 } 12732 12733 /* ptr + __sz/__szk pair: size is in the next register */ 12734 if (arg + 1 < nargs && 12735 (btf_param_match_suffix(btf, &args[arg + 1], "__sz") || 12736 btf_param_match_suffix(btf, &args[arg + 1], "__szk"))) { 12737 int size_reg = BPF_REG_1 + arg + 1; 12738 12739 if (aux->const_reg_mask & BIT(size_reg)) { 12740 size = (s64)aux->const_reg_vals[size_reg]; 12741 goto out; 12742 } 12743 return MAX_BPF_STACK; 12744 } 12745 12746 /* fixed-size pointed-to type: resolve via BTF */ 12747 ref_t = btf_type_skip_modifiers(btf, t->type, NULL); 12748 if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) { 12749 size = type_size; 12750 goto out; 12751 } 12752 12753 return S64_MIN; 12754 out: 12755 /* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */ 12756 if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW) 12757 return -size; 12758 if (is_kfunc_arg_uninit(btf, &args[arg])) 12759 return -size; 12760 return size; 12761 } 12762 12763 /* check special kfuncs and return: 12764 * 1 - not fall-through to 'else' branch, continue verification 12765 * 0 - fall-through to 'else' branch 12766 * < 0 - not fall-through to 'else' branch, return error 12767 */ 12768 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 12769 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 12770 const struct btf_type *ptr_type, struct btf *desc_btf) 12771 { 12772 const struct btf_type *ret_t; 12773 int err = 0; 12774 12775 if (meta->btf != btf_vmlinux) 12776 return 0; 12777 12778 if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12779 struct btf_struct_meta *struct_meta; 12780 struct btf *ret_btf; 12781 u32 ret_btf_id; 12782 12783 if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set) 12784 return -ENOMEM; 12785 12786 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 12787 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12788 return -EINVAL; 12789 } 12790 12791 ret_btf = env->prog->aux->btf; 12792 ret_btf_id = meta->arg_constant.value; 12793 12794 /* This may be NULL due to user not supplying a BTF */ 12795 if (!ret_btf) { 12796 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12797 return -EINVAL; 12798 } 12799 12800 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12801 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12802 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12803 return -EINVAL; 12804 } 12805 12806 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12807 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12808 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12809 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12810 return -EINVAL; 12811 } 12812 12813 if (!bpf_global_percpu_ma_set) { 12814 mutex_lock(&bpf_percpu_ma_lock); 12815 if (!bpf_global_percpu_ma_set) { 12816 /* Charge memory allocated with bpf_global_percpu_ma to 12817 * root memcg. The obj_cgroup for root memcg is NULL. 12818 */ 12819 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12820 if (!err) 12821 bpf_global_percpu_ma_set = true; 12822 } 12823 mutex_unlock(&bpf_percpu_ma_lock); 12824 if (err) 12825 return err; 12826 } 12827 12828 mutex_lock(&bpf_percpu_ma_lock); 12829 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12830 mutex_unlock(&bpf_percpu_ma_lock); 12831 if (err) 12832 return err; 12833 } 12834 12835 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12836 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12837 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12838 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12839 return -EINVAL; 12840 } 12841 12842 if (struct_meta) { 12843 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12844 return -EINVAL; 12845 } 12846 } 12847 12848 mark_reg_known_zero(env, regs, BPF_REG_0); 12849 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12850 regs[BPF_REG_0].btf = ret_btf; 12851 regs[BPF_REG_0].btf_id = ret_btf_id; 12852 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) 12853 regs[BPF_REG_0].type |= MEM_PERCPU; 12854 12855 insn_aux->obj_new_size = ret_t->size; 12856 insn_aux->kptr_struct_meta = struct_meta; 12857 } else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) { 12858 mark_reg_known_zero(env, regs, BPF_REG_0); 12859 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12860 regs[BPF_REG_0].btf = meta->arg_btf; 12861 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 12862 12863 insn_aux->kptr_struct_meta = 12864 btf_find_struct_meta(meta->arg_btf, 12865 meta->arg_btf_id); 12866 } else if (is_list_node_type(ptr_type)) { 12867 struct btf_field *field = meta->arg_list_head.field; 12868 12869 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12870 } else if (is_rbtree_node_type(ptr_type)) { 12871 struct btf_field *field = meta->arg_rbtree_root.field; 12872 12873 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12874 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12875 mark_reg_known_zero(env, regs, BPF_REG_0); 12876 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12877 regs[BPF_REG_0].btf = desc_btf; 12878 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 12879 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12880 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 12881 if (!ret_t) { 12882 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n", 12883 meta->arg_constant.value); 12884 return -EINVAL; 12885 } else if (btf_type_is_struct(ret_t)) { 12886 mark_reg_known_zero(env, regs, BPF_REG_0); 12887 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12888 regs[BPF_REG_0].btf = desc_btf; 12889 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 12890 } else if (btf_type_is_void(ret_t)) { 12891 mark_reg_known_zero(env, regs, BPF_REG_0); 12892 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED; 12893 regs[BPF_REG_0].mem_size = 0; 12894 } else { 12895 verbose(env, 12896 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n"); 12897 return -EINVAL; 12898 } 12899 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12900 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12901 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type); 12902 12903 mark_reg_known_zero(env, regs, BPF_REG_0); 12904 12905 if (!meta->arg_constant.found) { 12906 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size"); 12907 return -EFAULT; 12908 } 12909 12910 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 12911 12912 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12913 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12914 12915 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12916 regs[BPF_REG_0].type |= MEM_RDONLY; 12917 } else { 12918 /* this will set env->seen_direct_write to true */ 12919 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12920 verbose(env, "the prog does not allow writes to packet data\n"); 12921 return -EINVAL; 12922 } 12923 } 12924 12925 if (!meta->dynptr.id) { 12926 verifier_bug(env, "no dynptr id"); 12927 return -EFAULT; 12928 } 12929 regs[BPF_REG_0].parent_id = meta->dynptr.id; 12930 } else { 12931 return 0; 12932 } 12933 12934 return 1; 12935 } 12936 12937 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12938 12939 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12940 int *insn_idx_p) 12941 { 12942 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12943 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12944 struct bpf_reg_state *regs = cur_regs(env); 12945 const char *func_name, *ptr_type_name; 12946 const struct btf_type *t, *ptr_type; 12947 struct bpf_call_arg_meta meta; 12948 struct bpf_insn_aux_data *insn_aux; 12949 int err, insn_idx = *insn_idx_p; 12950 u32 i, nargs, ptr_type_id; 12951 struct bpf_kfunc_desc *desc; 12952 struct btf *desc_btf; 12953 int id; 12954 12955 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12956 if (!insn->imm) 12957 return 0; 12958 12959 err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta); 12960 if (err == -EACCES && meta.func_name) 12961 verbose(env, "calling kernel function %s is not allowed\n", meta.func_name); 12962 if (err) 12963 return err; 12964 desc_btf = meta.btf; 12965 func_name = meta.func_name; 12966 insn_aux = &env->insn_aux_data[insn_idx]; 12967 12968 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 12969 if (!desc) { 12970 verifier_bug(env, "kfunc descriptor not found for func_id %u", insn->imm); 12971 return -EFAULT; 12972 } 12973 meta.fn = &desc->proto; 12974 12975 insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta); 12976 12977 if (!insn->off && 12978 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 12979 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 12980 struct bpf_verifier_state *branch; 12981 struct bpf_reg_state *regs; 12982 12983 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 12984 if (IS_ERR(branch)) { 12985 verbose(env, "failed to push state for failed lock acquisition\n"); 12986 return PTR_ERR(branch); 12987 } 12988 12989 regs = branch->frame[branch->curframe]->regs; 12990 12991 /* Clear r0-r5 registers in forked state */ 12992 for (i = 0; i < CALLER_SAVED_REGS; i++) 12993 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 12994 12995 mark_reg_unknown(env, regs, BPF_REG_0); 12996 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 12997 if (err) { 12998 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 12999 return err; 13000 } 13001 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 13002 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 13003 return -EFAULT; 13004 } 13005 13006 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 13007 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 13008 return -EACCES; 13009 } 13010 13011 sleepable = bpf_is_kfunc_sleepable(&meta); 13012 if (sleepable && !in_sleepable(env)) { 13013 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 13014 return -EACCES; 13015 } 13016 13017 /* Track non-sleepable context for kfuncs, same as for helpers. */ 13018 if (!in_sleepable_context(env)) 13019 insn_aux->non_sleepable = true; 13020 13021 /* Check the arguments */ 13022 err = check_kfunc_args(env, &meta, insn_idx); 13023 if (err < 0) 13024 return err; 13025 13026 if ((is_bpf_obj_drop_kfunc(meta.func_id) || 13027 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (is_tracing_prog_type(prog_type) || 13028 /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */ 13029 (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER 13030 && !env->prog->sleepable))) { 13031 struct btf_struct_meta *struct_meta; 13032 13033 struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13034 if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) { 13035 verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n", 13036 func_name); 13037 return -EINVAL; 13038 } 13039 } 13040 13041 if (is_bpf_rbtree_add_kfunc(meta.func_id)) { 13042 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13043 set_rbtree_add_callback_state); 13044 if (err) { 13045 verbose(env, "kfunc %s#%d failed callback verification\n", 13046 func_name, meta.func_id); 13047 return err; 13048 } 13049 } 13050 13051 if (is_bpf_wq_set_callback_kfunc(meta.func_id)) { 13052 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13053 set_timer_callback_state); 13054 if (err) { 13055 verbose(env, "kfunc %s#%d failed callback verification\n", 13056 func_name, meta.func_id); 13057 return err; 13058 } 13059 } 13060 13061 if (is_task_work_add_kfunc(meta.func_id)) { 13062 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13063 set_task_work_schedule_callback_state); 13064 if (err) { 13065 verbose(env, "kfunc %s#%d failed callback verification\n", 13066 func_name, meta.func_id); 13067 return err; 13068 } 13069 } 13070 13071 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 13072 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 13073 13074 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 13075 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 13076 13077 if (rcu_lock) { 13078 env->cur_state->active_rcu_locks++; 13079 } else if (rcu_unlock) { 13080 if (env->cur_state->active_rcu_locks == 0) { 13081 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 13082 return -EINVAL; 13083 } 13084 env->cur_state->active_rcu_locks--; 13085 if (!in_rcu_cs(env)) 13086 invalidate_rcu_protected_refs(env); 13087 } else if (preempt_disable) { 13088 env->cur_state->active_preempt_locks++; 13089 } else if (preempt_enable) { 13090 if (env->cur_state->active_preempt_locks == 0) { 13091 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 13092 return -EINVAL; 13093 } 13094 env->cur_state->active_preempt_locks--; 13095 if (!in_rcu_cs(env)) 13096 invalidate_rcu_protected_refs(env); 13097 } 13098 13099 if (sleepable && !in_sleepable_context(env)) { 13100 verbose(env, "kernel func %s is sleepable within %s\n", 13101 func_name, non_sleepable_context_description(env)); 13102 return -EACCES; 13103 } 13104 13105 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 13106 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 13107 return -EACCES; 13108 } 13109 13110 if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) { 13111 verbose(env, "kernel func %s requires RCU critical section protection\n", func_name); 13112 return -EACCES; 13113 } 13114 13115 /* In case of release function, we get register number of refcounted 13116 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 13117 */ 13118 if (meta.release_regno) { 13119 err = release_reg(env, ®s[meta.release_regno], false, !!meta.dynptr.id); 13120 if (err) 13121 return err; 13122 } 13123 13124 if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) { 13125 id = regs[BPF_REG_2].id; 13126 insn_aux->insert_off = regs[BPF_REG_2].var_off.value; 13127 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13128 ref_convert_owning_non_owning(env, id); 13129 } 13130 13131 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 13132 if (!bpf_jit_supports_exceptions()) { 13133 verbose(env, "JIT does not support calling kfunc %s#%d\n", 13134 func_name, meta.func_id); 13135 return -ENOTSUPP; 13136 } 13137 env->seen_exception = true; 13138 13139 /* In the case of the default callback, the cookie value passed 13140 * to bpf_throw becomes the return value of the program. 13141 */ 13142 if (!env->exception_callback_subprog) { 13143 err = check_return_code(env, BPF_REG_1, "R1"); 13144 if (err < 0) 13145 return err; 13146 } 13147 } 13148 13149 for (i = 0; i < CALLER_SAVED_REGS; i++) { 13150 u32 regno = caller_saved[i]; 13151 13152 bpf_mark_reg_not_init(env, ®s[regno]); 13153 } 13154 invalidate_outgoing_stack_args(env, cur_func(env)); 13155 13156 /* Check return type */ 13157 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13158 13159 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13160 if (meta.btf != btf_vmlinux || 13161 (!is_bpf_obj_new_kfunc(meta.func_id) && 13162 !is_bpf_percpu_obj_new_kfunc(meta.func_id) && 13163 !is_bpf_refcount_acquire_kfunc(meta.func_id))) { 13164 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13165 return -EINVAL; 13166 } 13167 } 13168 13169 if (btf_type_is_scalar(t)) { 13170 mark_reg_unknown(env, regs, BPF_REG_0); 13171 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13172 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13173 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 13174 } else if (btf_type_is_ptr(t)) { 13175 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 13176 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 13177 if (err) { 13178 if (err < 0) 13179 return err; 13180 } else if (btf_type_is_void(ptr_type)) { 13181 /* kfunc returning 'void *' is equivalent to returning scalar */ 13182 mark_reg_unknown(env, regs, BPF_REG_0); 13183 } else if (!__btf_type_is_struct(ptr_type)) { 13184 if (!meta.ret_mem.found) { 13185 __u32 sz; 13186 13187 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 13188 meta.ret_mem.found = true; 13189 meta.ret_mem.size = sz; 13190 meta.r0_rdonly = true; 13191 } 13192 13193 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 13194 meta.r0_rdonly = false; 13195 } 13196 if (!meta.ret_mem.found) { 13197 ptr_type_name = btf_name_by_offset(desc_btf, 13198 ptr_type->name_off); 13199 verbose(env, 13200 "kernel function %s returns pointer type %s %s is not supported\n", 13201 func_name, 13202 btf_type_str(ptr_type), 13203 ptr_type_name); 13204 return -EINVAL; 13205 } 13206 13207 mark_reg_known_zero(env, regs, BPF_REG_0); 13208 regs[BPF_REG_0].type = PTR_TO_MEM; 13209 regs[BPF_REG_0].mem_size = meta.ret_mem.size; 13210 13211 if (meta.r0_rdonly) 13212 regs[BPF_REG_0].type |= MEM_RDONLY; 13213 13214 /* Ensures we don't access the memory after a release_reference() */ 13215 if (meta.ref_obj.id) { 13216 err = validate_ref_obj(env, &meta.ref_obj); 13217 if (err) 13218 return err; 13219 regs[BPF_REG_0].parent_id = meta.ref_obj.id; 13220 } 13221 13222 if (is_kfunc_rcu_protected(&meta)) 13223 regs[BPF_REG_0].type |= MEM_RCU; 13224 } else { 13225 enum bpf_reg_type type = PTR_TO_BTF_ID; 13226 13227 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 13228 type |= PTR_UNTRUSTED; 13229 else if (is_kfunc_rcu_protected(&meta) || 13230 (bpf_is_iter_next_kfunc(&meta) && 13231 (get_iter_from_state(env->cur_state, &meta) 13232 ->type & MEM_RCU))) { 13233 /* 13234 * If the iterator's constructor (the _new 13235 * function e.g., bpf_iter_task_new) has been 13236 * annotated with BPF kfunc flag 13237 * KF_RCU_PROTECTED and was called within a RCU 13238 * read-side critical section, also propagate 13239 * the MEM_RCU flag to the pointer returned from 13240 * the iterator's next function (e.g., 13241 * bpf_iter_task_next). 13242 */ 13243 type |= MEM_RCU; 13244 } else { 13245 /* 13246 * Any PTR_TO_BTF_ID that is returned from a BPF 13247 * kfunc should by default be treated as 13248 * implicitly trusted. 13249 */ 13250 type |= PTR_TRUSTED; 13251 } 13252 13253 mark_reg_known_zero(env, regs, BPF_REG_0); 13254 regs[BPF_REG_0].btf = desc_btf; 13255 regs[BPF_REG_0].type = type; 13256 regs[BPF_REG_0].btf_id = ptr_type_id; 13257 } 13258 13259 if (is_kfunc_ret_null(&meta)) { 13260 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 13261 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 13262 regs[BPF_REG_0].id = ++env->id_gen; 13263 } 13264 if (is_kfunc_acquire(&meta)) { 13265 id = acquire_reference(env, insn_idx, 0); 13266 if (id < 0) 13267 return id; 13268 regs[BPF_REG_0].id = id; 13269 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 13270 ref_set_non_owning(env, ®s[BPF_REG_0]); 13271 } 13272 13273 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 13274 regs[BPF_REG_0].id = ++env->id_gen; 13275 } else if (btf_type_is_void(t)) { 13276 if (meta.btf == btf_vmlinux) { 13277 if (is_bpf_obj_drop_kfunc(meta.func_id) || 13278 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) { 13279 insn_aux->kptr_struct_meta = 13280 btf_find_struct_meta(meta.arg_btf, 13281 meta.arg_btf_id); 13282 } 13283 } 13284 } 13285 13286 if (bpf_is_kfunc_pkt_changing(&meta)) 13287 clear_all_pkt_pointers(env); 13288 13289 nargs = btf_type_vlen(meta.func_proto); 13290 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 13291 struct bpf_func_state *caller = cur_func(env); 13292 struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno]; 13293 u16 out_stack_arg_cnt = nargs - MAX_BPF_FUNC_REG_ARGS; 13294 u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt; 13295 13296 if (stack_arg_cnt > caller_info->stack_arg_cnt) 13297 caller_info->stack_arg_cnt = stack_arg_cnt; 13298 } 13299 13300 if (bpf_is_iter_next_kfunc(&meta)) { 13301 err = process_iter_next_call(env, insn_idx, &meta); 13302 if (err) 13303 return err; 13304 } 13305 13306 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 13307 env->prog->call_session_cookie = true; 13308 13309 if (bpf_is_throw_kfunc(insn)) 13310 return process_bpf_exit_full(env, NULL, true); 13311 13312 return 0; 13313 } 13314 13315 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env, 13316 const struct bpf_reg_state *reg, 13317 enum bpf_reg_type type) 13318 { 13319 bool known = tnum_is_const(reg->var_off); 13320 s64 val = reg->var_off.value; 13321 s64 smin = reg_smin(reg); 13322 13323 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13324 verbose(env, "math between %s pointer and %lld is not allowed\n", 13325 reg_type_str(env, type), val); 13326 return false; 13327 } 13328 13329 if (smin == S64_MIN) { 13330 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 13331 reg_type_str(env, type)); 13332 return false; 13333 } 13334 13335 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13336 verbose(env, "value %lld makes %s pointer be out of bounds\n", 13337 smin, reg_type_str(env, type)); 13338 return false; 13339 } 13340 13341 return true; 13342 } 13343 13344 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env, 13345 const struct bpf_reg_state *reg, 13346 enum bpf_reg_type type) 13347 { 13348 bool known = tnum_is_const(reg->var_off); 13349 s64 val = reg->var_off.value; 13350 s64 smin = reg_smin(reg); 13351 13352 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13353 verbose(env, "%s pointer offset %lld is not allowed\n", 13354 reg_type_str(env, type), val); 13355 return false; 13356 } 13357 13358 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13359 verbose(env, "%s pointer offset %lld is not allowed\n", 13360 reg_type_str(env, type), smin); 13361 return false; 13362 } 13363 13364 return true; 13365 } 13366 13367 enum { 13368 REASON_BOUNDS = -1, 13369 REASON_TYPE = -2, 13370 REASON_PATHS = -3, 13371 REASON_LIMIT = -4, 13372 REASON_STACK = -5, 13373 }; 13374 13375 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 13376 u32 *alu_limit, bool mask_to_left) 13377 { 13378 u32 max = 0, ptr_limit = 0; 13379 13380 switch (ptr_reg->type) { 13381 case PTR_TO_STACK: 13382 /* Offset 0 is out-of-bounds, but acceptable start for the 13383 * left direction, see BPF_REG_FP. Also, unknown scalar 13384 * offset where we would need to deal with min/max bounds is 13385 * currently prohibited for unprivileged. 13386 */ 13387 max = MAX_BPF_STACK + mask_to_left; 13388 ptr_limit = -ptr_reg->var_off.value; 13389 break; 13390 case PTR_TO_MAP_VALUE: 13391 max = ptr_reg->map_ptr->value_size; 13392 ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg); 13393 break; 13394 default: 13395 return REASON_TYPE; 13396 } 13397 13398 if (ptr_limit >= max) 13399 return REASON_LIMIT; 13400 *alu_limit = ptr_limit; 13401 return 0; 13402 } 13403 13404 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 13405 const struct bpf_insn *insn) 13406 { 13407 return env->bypass_spec_v1 || 13408 BPF_SRC(insn->code) == BPF_K || 13409 cur_aux(env)->nospec; 13410 } 13411 13412 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 13413 u32 alu_state, u32 alu_limit) 13414 { 13415 /* If we arrived here from different branches with different 13416 * state or limits to sanitize, then this won't work. 13417 */ 13418 if (aux->alu_state && 13419 (aux->alu_state != alu_state || 13420 aux->alu_limit != alu_limit)) 13421 return REASON_PATHS; 13422 13423 /* Corresponding fixup done in do_misc_fixups(). */ 13424 aux->alu_state = alu_state; 13425 aux->alu_limit = alu_limit; 13426 return 0; 13427 } 13428 13429 static int sanitize_val_alu(struct bpf_verifier_env *env, 13430 struct bpf_insn *insn) 13431 { 13432 struct bpf_insn_aux_data *aux = cur_aux(env); 13433 13434 if (can_skip_alu_sanitation(env, insn)) 13435 return 0; 13436 13437 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13438 } 13439 13440 static bool sanitize_needed(u8 opcode) 13441 { 13442 return opcode == BPF_ADD || opcode == BPF_SUB; 13443 } 13444 13445 struct bpf_sanitize_info { 13446 struct bpf_insn_aux_data aux; 13447 bool mask_to_left; 13448 }; 13449 13450 static int sanitize_speculative_path(struct bpf_verifier_env *env, 13451 const struct bpf_insn *insn, 13452 u32 next_idx, u32 curr_idx) 13453 { 13454 struct bpf_verifier_state *branch; 13455 struct bpf_reg_state *regs; 13456 13457 branch = push_stack(env, next_idx, curr_idx, true); 13458 if (!IS_ERR(branch) && insn) { 13459 regs = branch->frame[branch->curframe]->regs; 13460 if (BPF_SRC(insn->code) == BPF_K) { 13461 mark_reg_unknown(env, regs, insn->dst_reg); 13462 } else if (BPF_SRC(insn->code) == BPF_X) { 13463 mark_reg_unknown(env, regs, insn->dst_reg); 13464 mark_reg_unknown(env, regs, insn->src_reg); 13465 } 13466 } 13467 return PTR_ERR_OR_ZERO(branch); 13468 } 13469 13470 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13471 struct bpf_insn *insn, 13472 const struct bpf_reg_state *ptr_reg, 13473 const struct bpf_reg_state *off_reg, 13474 struct bpf_reg_state *dst_reg, 13475 struct bpf_sanitize_info *info, 13476 const bool commit_window) 13477 { 13478 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13479 struct bpf_verifier_state *vstate = env->cur_state; 13480 bool off_is_imm = tnum_is_const(off_reg->var_off); 13481 bool off_is_neg = reg_smin(off_reg) < 0; 13482 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13483 u8 opcode = BPF_OP(insn->code); 13484 u32 alu_state, alu_limit; 13485 struct bpf_reg_state tmp; 13486 int err; 13487 13488 if (can_skip_alu_sanitation(env, insn)) 13489 return 0; 13490 13491 /* We already marked aux for masking from non-speculative 13492 * paths, thus we got here in the first place. We only care 13493 * to explore bad access from here. 13494 */ 13495 if (vstate->speculative) 13496 goto do_sim; 13497 13498 if (!commit_window) { 13499 if (!tnum_is_const(off_reg->var_off) && 13500 (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0)) 13501 return REASON_BOUNDS; 13502 13503 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13504 (opcode == BPF_SUB && !off_is_neg); 13505 } 13506 13507 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13508 if (err < 0) 13509 return err; 13510 13511 if (commit_window) { 13512 /* In commit phase we narrow the masking window based on 13513 * the observed pointer move after the simulated operation. 13514 */ 13515 alu_state = info->aux.alu_state; 13516 alu_limit = abs(info->aux.alu_limit - alu_limit); 13517 } else { 13518 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13519 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13520 alu_state |= ptr_is_dst_reg ? 13521 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13522 13523 /* Limit pruning on unknown scalars to enable deep search for 13524 * potential masking differences from other program paths. 13525 */ 13526 if (!off_is_imm) 13527 env->explore_alu_limits = true; 13528 } 13529 13530 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13531 if (err < 0) 13532 return err; 13533 do_sim: 13534 /* If we're in commit phase, we're done here given we already 13535 * pushed the truncated dst_reg into the speculative verification 13536 * stack. 13537 * 13538 * Also, when register is a known constant, we rewrite register-based 13539 * operation to immediate-based, and thus do not need masking (and as 13540 * a consequence, do not need to simulate the zero-truncation either). 13541 */ 13542 if (commit_window || off_is_imm) 13543 return 0; 13544 13545 /* Simulate and find potential out-of-bounds access under 13546 * speculative execution from truncation as a result of 13547 * masking when off was not within expected range. If off 13548 * sits in dst, then we temporarily need to move ptr there 13549 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13550 * for cases where we use K-based arithmetic in one direction 13551 * and truncated reg-based in the other in order to explore 13552 * bad access. 13553 */ 13554 if (!ptr_is_dst_reg) { 13555 tmp = *dst_reg; 13556 *dst_reg = *ptr_reg; 13557 } 13558 err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx); 13559 if (err < 0) 13560 return REASON_STACK; 13561 if (!ptr_is_dst_reg) 13562 *dst_reg = tmp; 13563 return 0; 13564 } 13565 13566 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13567 { 13568 struct bpf_verifier_state *vstate = env->cur_state; 13569 13570 /* If we simulate paths under speculation, we don't update the 13571 * insn as 'seen' such that when we verify unreachable paths in 13572 * the non-speculative domain, sanitize_dead_code() can still 13573 * rewrite/sanitize them. 13574 */ 13575 if (!vstate->speculative) 13576 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13577 } 13578 13579 static int sanitize_err(struct bpf_verifier_env *env, const struct bpf_insn *insn, int reason) 13580 { 13581 static const char *err = "pointer arithmetic with it prohibited for !root"; 13582 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13583 u32 dst = insn->dst_reg, src = insn->src_reg; 13584 struct bpf_reg_state *regs = cur_regs(env); 13585 13586 switch (reason) { 13587 case REASON_BOUNDS: 13588 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13589 regs[src].type == SCALAR_VALUE ? src : dst, err); 13590 break; 13591 case REASON_TYPE: 13592 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13593 regs[src].type == SCALAR_VALUE ? dst : src, err); 13594 break; 13595 case REASON_PATHS: 13596 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13597 dst, op, err); 13598 break; 13599 case REASON_LIMIT: 13600 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13601 dst, op, err); 13602 break; 13603 case REASON_STACK: 13604 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13605 dst, err); 13606 return -ENOMEM; 13607 default: 13608 verifier_bug(env, "unknown reason (%d)", reason); 13609 break; 13610 } 13611 13612 return -EACCES; 13613 } 13614 13615 /* check that stack access falls within stack limits and that 'reg' doesn't 13616 * have a variable offset. 13617 * 13618 * Variable offset is prohibited for unprivileged mode for simplicity since it 13619 * requires corresponding support in Spectre masking for stack ALU. See also 13620 * retrieve_ptr_limit(). 13621 */ 13622 static int check_stack_access_for_ptr_arithmetic( 13623 struct bpf_verifier_env *env, 13624 int regno, 13625 const struct bpf_reg_state *reg, 13626 int off) 13627 { 13628 if (!tnum_is_const(reg->var_off)) { 13629 char tn_buf[48]; 13630 13631 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13632 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13633 regno, tn_buf, off); 13634 return -EACCES; 13635 } 13636 13637 if (off >= 0 || off < -MAX_BPF_STACK) { 13638 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13639 "prohibited for !root; off=%d\n", regno, off); 13640 return -EACCES; 13641 } 13642 13643 return 0; 13644 } 13645 13646 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13647 const struct bpf_insn *insn, 13648 struct bpf_reg_state *dst_reg) 13649 { 13650 u32 dst = insn->dst_reg; 13651 13652 /* For unprivileged we require that resulting offset must be in bounds 13653 * in order to be able to sanitize access later on. 13654 */ 13655 if (env->bypass_spec_v1) 13656 return 0; 13657 13658 switch (dst_reg->type) { 13659 case PTR_TO_STACK: 13660 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13661 dst_reg->var_off.value)) 13662 return -EACCES; 13663 break; 13664 case PTR_TO_MAP_VALUE: 13665 if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) { 13666 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13667 "prohibited for !root\n", dst); 13668 return -EACCES; 13669 } 13670 break; 13671 default: 13672 return -EOPNOTSUPP; 13673 } 13674 13675 return 0; 13676 } 13677 13678 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13679 * Caller should also handle BPF_MOV case separately. 13680 * If we return -EACCES, caller may want to try again treating pointer as a 13681 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13682 */ 13683 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13684 struct bpf_insn *insn, 13685 const struct bpf_reg_state *ptr_reg, 13686 const struct bpf_reg_state *off_reg) 13687 { 13688 struct bpf_verifier_state *vstate = env->cur_state; 13689 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13690 struct bpf_reg_state *regs = state->regs, *dst_reg; 13691 bool known = tnum_is_const(off_reg->var_off); 13692 s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg); 13693 u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg); 13694 struct bpf_sanitize_info info = {}; 13695 u8 opcode = BPF_OP(insn->code); 13696 u32 dst = insn->dst_reg; 13697 int ret, bounds_ret; 13698 13699 dst_reg = ®s[dst]; 13700 13701 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13702 smin_val > smax_val || umin_val > umax_val) { 13703 /* Taint dst register if offset had invalid bounds derived from 13704 * e.g. dead branches. 13705 */ 13706 __mark_reg_unknown(env, dst_reg); 13707 return 0; 13708 } 13709 13710 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13711 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13712 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13713 __mark_reg_unknown(env, dst_reg); 13714 return 0; 13715 } 13716 13717 verbose(env, 13718 "R%d 32-bit pointer arithmetic prohibited\n", 13719 dst); 13720 return -EACCES; 13721 } 13722 13723 if (ptr_reg->type & PTR_MAYBE_NULL) { 13724 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13725 dst, reg_type_str(env, ptr_reg->type)); 13726 return -EACCES; 13727 } 13728 13729 switch (base_type(ptr_reg->type)) { 13730 case PTR_TO_CTX: 13731 case PTR_TO_MAP_VALUE: 13732 case PTR_TO_MAP_KEY: 13733 case PTR_TO_STACK: 13734 case PTR_TO_PACKET_META: 13735 case PTR_TO_PACKET: 13736 case PTR_TO_TP_BUFFER: 13737 case PTR_TO_BTF_ID: 13738 case PTR_TO_MEM: 13739 case PTR_TO_BUF: 13740 case PTR_TO_FUNC: 13741 case CONST_PTR_TO_DYNPTR: 13742 break; 13743 case PTR_TO_FLOW_KEYS: 13744 if (known) 13745 break; 13746 fallthrough; 13747 case CONST_PTR_TO_MAP: 13748 /* smin_val represents the known value */ 13749 if (known && smin_val == 0 && opcode == BPF_ADD) 13750 break; 13751 fallthrough; 13752 default: 13753 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13754 dst, reg_type_str(env, ptr_reg->type)); 13755 return -EACCES; 13756 } 13757 13758 /* For 'scalar += pointer', dst_reg inherits the complete pointer 13759 * register state. Individual fields may be adjusted later by pointer 13760 * arithmetic. Callers guarantee that below does not overwrite off_reg. 13761 */ 13762 if (dst_reg != ptr_reg) 13763 *dst_reg = *ptr_reg; 13764 13765 /* 13766 * Accesses to untrusted PTR_TO_MEM are done through probe 13767 * instructions, hence no need to track offsets. 13768 */ 13769 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 13770 return 0; 13771 13772 if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type) || 13773 !check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) 13774 return -EINVAL; 13775 13776 /* pointer types do not carry 32-bit bounds at the moment. */ 13777 __mark_reg32_unbounded(dst_reg); 13778 13779 if (sanitize_needed(opcode)) { 13780 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13781 &info, false); 13782 if (ret < 0) 13783 return sanitize_err(env, insn, ret); 13784 } 13785 13786 switch (opcode) { 13787 case BPF_ADD: 13788 /* 13789 * dst_reg gets the pointer type and since some positive 13790 * integer value was added to the pointer, give it a new 'id' 13791 * if it's a PTR_TO_PACKET. 13792 * this creates a new 'base' pointer, off_reg (variable) gets 13793 * added into the variable offset, and we copy the fixed offset 13794 * from ptr_reg. 13795 */ 13796 dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64); 13797 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13798 dst_reg->raw = ptr_reg->raw; 13799 if (reg_is_pkt_pointer(ptr_reg)) { 13800 if (!known) 13801 dst_reg->id = ++env->id_gen; 13802 /* 13803 * Clear range for unknown addends since we can't know 13804 * where the pkt pointer ended up. Also clear AT_PKT_END / 13805 * BEYOND_PKT_END from prior comparison as any pointer 13806 * arithmetic invalidates them. 13807 */ 13808 if (!known || dst_reg->range < 0) 13809 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13810 } 13811 break; 13812 case BPF_SUB: 13813 if (dst_reg != ptr_reg) { 13814 /* scalar -= pointer. Creates an unknown scalar */ 13815 verbose(env, "R%d tried to subtract pointer from scalar\n", 13816 dst); 13817 return -EACCES; 13818 } 13819 /* We don't allow subtraction from FP, because (according to 13820 * test_verifier.c test "invalid fp arithmetic", JITs might not 13821 * be able to deal with it. 13822 */ 13823 if (ptr_reg->type == PTR_TO_STACK) { 13824 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13825 dst); 13826 return -EACCES; 13827 } 13828 dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64)); 13829 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13830 dst_reg->raw = ptr_reg->raw; 13831 if (reg_is_pkt_pointer(ptr_reg)) { 13832 if (!known) 13833 dst_reg->id = ++env->id_gen; 13834 /* 13835 * Clear range if the subtrahend may be negative since 13836 * pkt pointer could move past its bounds. A positive 13837 * subtrahend moves it backwards keeping positive range 13838 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from 13839 * prior comparison as arithmetic invalidates them. 13840 */ 13841 if ((!known && smin_val < 0) || dst_reg->range < 0) 13842 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13843 } 13844 break; 13845 case BPF_AND: 13846 case BPF_OR: 13847 case BPF_XOR: 13848 /* bitwise ops on pointers are troublesome, prohibit. */ 13849 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13850 dst, bpf_alu_string[opcode >> 4]); 13851 return -EACCES; 13852 default: 13853 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13854 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13855 dst, bpf_alu_string[opcode >> 4]); 13856 return -EACCES; 13857 } 13858 13859 if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) 13860 return -EINVAL; 13861 reg_bounds_sync(dst_reg); 13862 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 13863 if (bounds_ret == -EACCES) 13864 return bounds_ret; 13865 if (sanitize_needed(opcode)) { 13866 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13867 &info, true); 13868 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 13869 && !env->cur_state->speculative 13870 && bounds_ret 13871 && !ret, 13872 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 13873 return -EFAULT; 13874 } 13875 if (ret < 0) 13876 return sanitize_err(env, insn, ret); 13877 } 13878 13879 return 0; 13880 } 13881 13882 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13883 struct bpf_reg_state *src_reg) 13884 { 13885 dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32); 13886 } 13887 13888 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13889 struct bpf_reg_state *src_reg) 13890 { 13891 dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64); 13892 } 13893 13894 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13895 struct bpf_reg_state *src_reg) 13896 { 13897 dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32)); 13898 } 13899 13900 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13901 struct bpf_reg_state *src_reg) 13902 { 13903 dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64)); 13904 } 13905 13906 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13907 struct bpf_reg_state *src_reg) 13908 { 13909 s32 smin = reg_s32_min(dst_reg); 13910 s32 smax = reg_s32_max(dst_reg); 13911 u32 umin = reg_u32_min(dst_reg); 13912 u32 umax = reg_u32_max(dst_reg); 13913 s32 tmp_prod[4]; 13914 13915 if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) || 13916 check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) { 13917 /* Overflow possible, we know nothing */ 13918 umin = 0; 13919 umax = U32_MAX; 13920 } 13921 if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) || 13922 check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) || 13923 check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) || 13924 check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) { 13925 /* Overflow possible, we know nothing */ 13926 smin = S32_MIN; 13927 smax = S32_MAX; 13928 } else { 13929 smin = min_array(tmp_prod, 4); 13930 smax = max_array(tmp_prod, 4); 13931 } 13932 13933 dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax), 13934 cnum32_from_srange(smin, smax)); 13935 } 13936 13937 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13938 struct bpf_reg_state *src_reg) 13939 { 13940 s64 smin = reg_smin(dst_reg); 13941 s64 smax = reg_smax(dst_reg); 13942 u64 umin = reg_umin(dst_reg); 13943 u64 umax = reg_umax(dst_reg); 13944 s64 tmp_prod[4]; 13945 13946 if (check_mul_overflow(umax, reg_umax(src_reg), &umax) || 13947 check_mul_overflow(umin, reg_umin(src_reg), &umin)) { 13948 /* Overflow possible, we know nothing */ 13949 umin = 0; 13950 umax = U64_MAX; 13951 } 13952 if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) || 13953 check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) || 13954 check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) || 13955 check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) { 13956 /* Overflow possible, we know nothing */ 13957 smin = S64_MIN; 13958 smax = S64_MAX; 13959 } else { 13960 smin = min_array(tmp_prod, 4); 13961 smax = max_array(tmp_prod, 4); 13962 } 13963 13964 dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax), 13965 cnum64_from_srange(smin, smax)); 13966 } 13967 13968 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg, 13969 struct bpf_reg_state *src_reg) 13970 { 13971 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 13972 13973 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val, 13974 reg_u32_max(dst_reg) / src_val); 13975 13976 /* Reset other ranges/tnum to unbounded/unknown. */ 13977 reset_reg64_and_tnum(dst_reg); 13978 } 13979 13980 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg, 13981 struct bpf_reg_state *src_reg) 13982 { 13983 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 13984 13985 reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val), 13986 div64_u64(reg_umax(dst_reg), src_val)); 13987 13988 /* Reset other ranges/tnum to unbounded/unknown. */ 13989 reset_reg32_and_tnum(dst_reg); 13990 } 13991 13992 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg, 13993 struct bpf_reg_state *src_reg) 13994 { 13995 s32 smin = reg_s32_min(dst_reg); 13996 s32 smax = reg_s32_max(dst_reg); 13997 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 13998 s32 res1, res2; 13999 14000 /* BPF div specification: S32_MIN / -1 = S32_MIN */ 14001 if (smin == S32_MIN && src_val == -1) { 14002 /* 14003 * If the dividend range contains more than just S32_MIN, 14004 * we cannot precisely track the result, so it becomes unbounded. 14005 * e.g., [S32_MIN, S32_MIN+10]/(-1), 14006 * = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)] 14007 * = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX] 14008 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN. 14009 */ 14010 if (smax != S32_MIN) { 14011 smin = S32_MIN; 14012 smax = S32_MAX; 14013 } 14014 goto reset; 14015 } 14016 14017 res1 = smin / src_val; 14018 res2 = smax / src_val; 14019 smin = min(res1, res2); 14020 smax = max(res1, res2); 14021 14022 reset: 14023 reg_set_srange32(dst_reg, smin, smax); 14024 /* Reset other ranges/tnum to unbounded/unknown. */ 14025 reset_reg64_and_tnum(dst_reg); 14026 } 14027 14028 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg, 14029 struct bpf_reg_state *src_reg) 14030 { 14031 s64 smin = reg_smin(dst_reg); 14032 s64 smax = reg_smax(dst_reg); 14033 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14034 s64 res1, res2; 14035 14036 /* BPF div specification: S64_MIN / -1 = S64_MIN */ 14037 if (smin == S64_MIN && src_val == -1) { 14038 /* 14039 * If the dividend range contains more than just S64_MIN, 14040 * we cannot precisely track the result, so it becomes unbounded. 14041 * e.g., [S64_MIN, S64_MIN+10]/(-1), 14042 * = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)] 14043 * = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX] 14044 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN. 14045 */ 14046 if (smax != S64_MIN) { 14047 smin = S64_MIN; 14048 smax = S64_MAX; 14049 } 14050 goto reset; 14051 } 14052 14053 res1 = div64_s64(smin, src_val); 14054 res2 = div64_s64(smax, src_val); 14055 smin = min(res1, res2); 14056 smax = max(res1, res2); 14057 14058 reset: 14059 reg_set_srange64(dst_reg, smin, smax); 14060 /* Reset other ranges/tnum to unbounded/unknown. */ 14061 reset_reg32_and_tnum(dst_reg); 14062 } 14063 14064 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg, 14065 struct bpf_reg_state *src_reg) 14066 { 14067 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 14068 u32 res_max = src_val - 1; 14069 14070 /* 14071 * If dst_umax <= res_max, the result remains unchanged. 14072 * e.g., [2, 5] % 10 = [2, 5]. 14073 */ 14074 if (reg_u32_max(dst_reg) <= res_max) 14075 return; 14076 14077 reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max)); 14078 14079 /* Reset other ranges/tnum to unbounded/unknown. */ 14080 reset_reg64_and_tnum(dst_reg); 14081 } 14082 14083 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg, 14084 struct bpf_reg_state *src_reg) 14085 { 14086 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 14087 u64 res_max = src_val - 1; 14088 14089 /* 14090 * If dst_umax <= res_max, the result remains unchanged. 14091 * e.g., [2, 5] % 10 = [2, 5]. 14092 */ 14093 if (reg_umax(dst_reg) <= res_max) 14094 return; 14095 14096 reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max)); 14097 14098 /* Reset other ranges/tnum to unbounded/unknown. */ 14099 reset_reg32_and_tnum(dst_reg); 14100 } 14101 14102 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg, 14103 struct bpf_reg_state *src_reg) 14104 { 14105 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 14106 14107 /* 14108 * Safe absolute value calculation: 14109 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648. 14110 * Here use unsigned integer to avoid overflow. 14111 */ 14112 u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val; 14113 14114 /* 14115 * Calculate the maximum possible absolute value of the result. 14116 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives 14117 * 2147483647 (S32_MAX), which fits perfectly in s32. 14118 */ 14119 s32 res_max_abs = src_abs - 1; 14120 14121 /* 14122 * If the dividend is already within the result range, 14123 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14124 */ 14125 if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs) 14126 return; 14127 14128 /* General case: result has the same sign as the dividend. */ 14129 if (reg_s32_min(dst_reg) >= 0) { 14130 reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs)); 14131 } else if (reg_s32_max(dst_reg) <= 0) { 14132 reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0); 14133 } else { 14134 reg_set_srange32(dst_reg, -res_max_abs, res_max_abs); 14135 } 14136 14137 /* Reset other ranges/tnum to unbounded/unknown. */ 14138 reset_reg64_and_tnum(dst_reg); 14139 } 14140 14141 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg, 14142 struct bpf_reg_state *src_reg) 14143 { 14144 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14145 14146 /* 14147 * Safe absolute value calculation: 14148 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63. 14149 * Here use unsigned integer to avoid overflow. 14150 */ 14151 u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val; 14152 14153 /* 14154 * Calculate the maximum possible absolute value of the result. 14155 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives 14156 * 2^63 - 1 (S64_MAX), which fits perfectly in s64. 14157 */ 14158 s64 res_max_abs = src_abs - 1; 14159 14160 /* 14161 * If the dividend is already within the result range, 14162 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14163 */ 14164 if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs) 14165 return; 14166 14167 /* General case: result has the same sign as the dividend. */ 14168 if (reg_smin(dst_reg) >= 0) { 14169 reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs)); 14170 } else if (reg_smax(dst_reg) <= 0) { 14171 reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0); 14172 } else { 14173 reg_set_srange64(dst_reg, -res_max_abs, res_max_abs); 14174 } 14175 14176 /* Reset other ranges/tnum to unbounded/unknown. */ 14177 reset_reg32_and_tnum(dst_reg); 14178 } 14179 14180 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14181 struct bpf_reg_state *src_reg) 14182 { 14183 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14184 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14185 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14186 u32 umax_val = reg_u32_max(src_reg); 14187 14188 if (src_known && dst_known) { 14189 __mark_reg32_known(dst_reg, var32_off.value); 14190 return; 14191 } 14192 14193 /* We get our minimum from the var_off, since that's inherently 14194 * bitwise. Our maximum is the minimum of the operands' maxima. 14195 */ 14196 reg_set_urange32(dst_reg, 14197 var32_off.value, 14198 min(reg_u32_max(dst_reg), umax_val)); 14199 } 14200 14201 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14202 struct bpf_reg_state *src_reg) 14203 { 14204 bool src_known = tnum_is_const(src_reg->var_off); 14205 bool dst_known = tnum_is_const(dst_reg->var_off); 14206 u64 umax_val = reg_umax(src_reg); 14207 14208 if (src_known && dst_known) { 14209 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14210 return; 14211 } 14212 14213 /* We get our minimum from the var_off, since that's inherently 14214 * bitwise. Our maximum is the minimum of the operands' maxima. 14215 */ 14216 reg_set_urange64(dst_reg, 14217 dst_reg->var_off.value, 14218 min(reg_umax(dst_reg), umax_val)); 14219 14220 /* We may learn something more from the var_off */ 14221 __update_reg_bounds(dst_reg); 14222 } 14223 14224 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14225 struct bpf_reg_state *src_reg) 14226 { 14227 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14228 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14229 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14230 u32 umin_val = reg_u32_min(src_reg); 14231 14232 if (src_known && dst_known) { 14233 __mark_reg32_known(dst_reg, var32_off.value); 14234 return; 14235 } 14236 14237 /* We get our maximum from the var_off, and our minimum is the 14238 * maximum of the operands' minima 14239 */ 14240 reg_set_urange32(dst_reg, 14241 max(reg_u32_min(dst_reg), umin_val), 14242 var32_off.value | var32_off.mask); 14243 } 14244 14245 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14246 struct bpf_reg_state *src_reg) 14247 { 14248 bool src_known = tnum_is_const(src_reg->var_off); 14249 bool dst_known = tnum_is_const(dst_reg->var_off); 14250 u64 umin_val = reg_umin(src_reg); 14251 14252 if (src_known && dst_known) { 14253 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14254 return; 14255 } 14256 14257 /* We get our maximum from the var_off, and our minimum is the 14258 * maximum of the operands' minima 14259 */ 14260 reg_set_urange64(dst_reg, 14261 max(reg_umin(dst_reg), umin_val), 14262 dst_reg->var_off.value | dst_reg->var_off.mask); 14263 14264 /* We may learn something more from the var_off */ 14265 __update_reg_bounds(dst_reg); 14266 } 14267 14268 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 14269 struct bpf_reg_state *src_reg) 14270 { 14271 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14272 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14273 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14274 14275 if (src_known && dst_known) { 14276 __mark_reg32_known(dst_reg, var32_off.value); 14277 return; 14278 } 14279 14280 /* We get both minimum and maximum from the var32_off. */ 14281 reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask); 14282 } 14283 14284 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 14285 struct bpf_reg_state *src_reg) 14286 { 14287 bool src_known = tnum_is_const(src_reg->var_off); 14288 bool dst_known = tnum_is_const(dst_reg->var_off); 14289 14290 if (src_known && dst_known) { 14291 /* dst_reg->var_off.value has been updated earlier */ 14292 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14293 return; 14294 } 14295 14296 /* We get both minimum and maximum from the var_off. */ 14297 reg_set_urange64(dst_reg, 14298 dst_reg->var_off.value, 14299 dst_reg->var_off.value | dst_reg->var_off.mask); 14300 } 14301 14302 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14303 u64 umin_val, u64 umax_val) 14304 { 14305 /* If we might shift our top bit out, then we know nothing */ 14306 if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val)) 14307 reg_set_urange32(dst_reg, 0, U32_MAX); 14308 else 14309 /* We lose all sign bit information (except what we can pick 14310 * up from var_off) 14311 */ 14312 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val, 14313 reg_u32_max(dst_reg) << umax_val); 14314 } 14315 14316 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14317 struct bpf_reg_state *src_reg) 14318 { 14319 u32 umax_val = reg_u32_max(src_reg); 14320 u32 umin_val = reg_u32_min(src_reg); 14321 /* u32 alu operation will zext upper bits */ 14322 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14323 14324 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14325 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 14326 /* Not required but being careful mark reg64 bounds as unknown so 14327 * that we are forced to pick them up from tnum and zext later and 14328 * if some path skips this step we are still safe. 14329 */ 14330 __mark_reg64_unbounded(dst_reg); 14331 __update_reg32_bounds(dst_reg); 14332 } 14333 14334 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 14335 u64 umin_val, u64 umax_val) 14336 { 14337 struct cnum64 u, s; 14338 14339 /* Special case <<32 because it is a common compiler pattern to sign 14340 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct 14341 * because s32 bounds don't flip sign when shifting to the left by 14342 * 32bits. 14343 */ 14344 if (umin_val == 32 && umax_val == 32) 14345 s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32, 14346 (s64)reg_s32_max(dst_reg) << 32); 14347 else 14348 s = CNUM64_UNBOUNDED; 14349 14350 /* If we might shift our top bit out, then we know nothing */ 14351 if (reg_umax(dst_reg) > 1ULL << (63 - umax_val)) 14352 u = CNUM64_UNBOUNDED; 14353 else 14354 u = cnum64_from_urange(reg_umin(dst_reg) << umin_val, 14355 reg_umax(dst_reg) << umax_val); 14356 14357 dst_reg->r64 = cnum64_intersect(u, s); 14358 } 14359 14360 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 14361 struct bpf_reg_state *src_reg) 14362 { 14363 u64 umax_val = reg_umax(src_reg); 14364 u64 umin_val = reg_umin(src_reg); 14365 14366 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 14367 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 14368 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14369 14370 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 14371 /* We may learn something more from the var_off */ 14372 __update_reg_bounds(dst_reg); 14373 } 14374 14375 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 14376 struct bpf_reg_state *src_reg) 14377 { 14378 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14379 u32 umax_val = reg_u32_max(src_reg); 14380 u32 umin_val = reg_u32_min(src_reg); 14381 14382 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14383 * be negative, then either: 14384 * 1) src_reg might be zero, so the sign bit of the result is 14385 * unknown, so we lose our signed bounds 14386 * 2) it's known negative, thus the unsigned bounds capture the 14387 * signed bounds 14388 * 3) the signed bounds cross zero, so they tell us nothing 14389 * about the result 14390 * If the value in dst_reg is known nonnegative, then again the 14391 * unsigned bounds capture the signed bounds. 14392 * Thus, in all cases it suffices to blow away our signed bounds 14393 * and rely on inferring new ones from the unsigned bounds and 14394 * var_off of the result. 14395 */ 14396 14397 dst_reg->var_off = tnum_rshift(subreg, umin_val); 14398 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val, 14399 reg_u32_max(dst_reg) >> umin_val); 14400 14401 __mark_reg64_unbounded(dst_reg); 14402 __update_reg32_bounds(dst_reg); 14403 } 14404 14405 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 14406 struct bpf_reg_state *src_reg) 14407 { 14408 u64 umax_val = reg_umax(src_reg); 14409 u64 umin_val = reg_umin(src_reg); 14410 14411 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14412 * be negative, then either: 14413 * 1) src_reg might be zero, so the sign bit of the result is 14414 * unknown, so we lose our signed bounds 14415 * 2) it's known negative, thus the unsigned bounds capture the 14416 * signed bounds 14417 * 3) the signed bounds cross zero, so they tell us nothing 14418 * about the result 14419 * If the value in dst_reg is known nonnegative, then again the 14420 * unsigned bounds capture the signed bounds. 14421 * Thus, in all cases it suffices to blow away our signed bounds 14422 * and rely on inferring new ones from the unsigned bounds and 14423 * var_off of the result. 14424 */ 14425 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 14426 reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val, 14427 reg_umax(dst_reg) >> umin_val); 14428 14429 /* Its not easy to operate on alu32 bounds here because it depends 14430 * on bits being shifted in. Take easy way out and mark unbounded 14431 * so we can recalculate later from tnum. 14432 */ 14433 __mark_reg32_unbounded(dst_reg); 14434 __update_reg_bounds(dst_reg); 14435 } 14436 14437 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 14438 struct bpf_reg_state *src_reg) 14439 { 14440 u64 umin_val = reg_u32_min(src_reg); 14441 14442 /* Upon reaching here, src_known is true and 14443 * umax_val is equal to umin_val. 14444 * Blow away the dst_reg umin_value/umax_value and rely on 14445 * dst_reg var_off to refine the result. 14446 */ 14447 reg_set_srange32(dst_reg, 14448 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val), 14449 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val)); 14450 14451 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 14452 14453 __mark_reg64_unbounded(dst_reg); 14454 __update_reg32_bounds(dst_reg); 14455 } 14456 14457 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 14458 struct bpf_reg_state *src_reg) 14459 { 14460 u64 umin_val = reg_umin(src_reg); 14461 14462 /* Upon reaching here, src_known is true and umax_val is equal 14463 * to umin_val. 14464 */ 14465 reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val, 14466 reg_smax(dst_reg) >> umin_val); 14467 14468 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14469 14470 /* Its not easy to operate on alu32 bounds here because it depends 14471 * on bits being shifted in from upper 32-bits. Take easy way out 14472 * and mark unbounded so we can recalculate later from tnum. 14473 */ 14474 __mark_reg32_unbounded(dst_reg); 14475 __update_reg_bounds(dst_reg); 14476 } 14477 14478 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn) 14479 { 14480 /* 14481 * Byte swap operation - update var_off using tnum_bswap. 14482 * Three cases: 14483 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE) 14484 * unconditional swap 14485 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE) 14486 * swap on big-endian, truncation or no-op on little-endian 14487 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE) 14488 * swap on little-endian, truncation or no-op on big-endian 14489 */ 14490 14491 bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64; 14492 bool to_le = BPF_SRC(insn->code) == BPF_TO_LE; 14493 bool is_big_endian; 14494 #ifdef CONFIG_CPU_BIG_ENDIAN 14495 is_big_endian = true; 14496 #else 14497 is_big_endian = false; 14498 #endif 14499 /* Apply bswap if alu64 or switch between big-endian and little-endian machines */ 14500 bool need_bswap = alu64 || (to_le == is_big_endian); 14501 14502 /* 14503 * If the register is mutated, manually reset its scalar ID to break 14504 * any existing ties and avoid incorrect bounds propagation. 14505 */ 14506 if (need_bswap || insn->imm == 16 || insn->imm == 32) 14507 clear_scalar_id(dst_reg); 14508 14509 if (need_bswap) { 14510 if (insn->imm == 16) 14511 dst_reg->var_off = tnum_bswap16(dst_reg->var_off); 14512 else if (insn->imm == 32) 14513 dst_reg->var_off = tnum_bswap32(dst_reg->var_off); 14514 else if (insn->imm == 64) 14515 dst_reg->var_off = tnum_bswap64(dst_reg->var_off); 14516 /* 14517 * Byteswap scrambles the range, so we must reset bounds. 14518 * Bounds will be re-derived from the new tnum later. 14519 */ 14520 __mark_reg_unbounded(dst_reg); 14521 } 14522 /* For bswap16/32, truncate dst register to match the swapped size */ 14523 if (insn->imm == 16 || insn->imm == 32) 14524 coerce_reg_to_size(dst_reg, insn->imm / 8); 14525 } 14526 14527 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14528 const struct bpf_reg_state *src_reg) 14529 { 14530 bool src_is_const = false; 14531 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14532 14533 if (insn_bitness == 32) { 14534 if (tnum_subreg_is_const(src_reg->var_off) 14535 && reg_s32_min(src_reg) == reg_s32_max(src_reg) 14536 && reg_u32_min(src_reg) == reg_u32_max(src_reg)) 14537 src_is_const = true; 14538 } else { 14539 if (tnum_is_const(src_reg->var_off) 14540 && reg_smin(src_reg) == reg_smax(src_reg) 14541 && reg_umin(src_reg) == reg_umax(src_reg)) 14542 src_is_const = true; 14543 } 14544 14545 switch (BPF_OP(insn->code)) { 14546 case BPF_ADD: 14547 case BPF_SUB: 14548 case BPF_NEG: 14549 case BPF_AND: 14550 case BPF_XOR: 14551 case BPF_OR: 14552 case BPF_MUL: 14553 case BPF_END: 14554 return true; 14555 14556 /* 14557 * Division and modulo operators range is only safe to compute when the 14558 * divisor is a constant. 14559 */ 14560 case BPF_DIV: 14561 case BPF_MOD: 14562 return src_is_const; 14563 14564 /* Shift operators range is only computable if shift dimension operand 14565 * is a constant. Shifts greater than 31 or 63 are undefined. This 14566 * includes shifts by a negative number. 14567 */ 14568 case BPF_LSH: 14569 case BPF_RSH: 14570 case BPF_ARSH: 14571 return (src_is_const && reg_umax(src_reg) < insn_bitness); 14572 default: 14573 return false; 14574 } 14575 } 14576 14577 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn, 14578 struct bpf_reg_state *dst_reg) 14579 { 14580 struct bpf_verifier_state *branch; 14581 struct bpf_reg_state *regs; 14582 bool alu32; 14583 14584 if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0) 14585 alu32 = false; 14586 else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0) 14587 alu32 = true; 14588 else 14589 return 0; 14590 14591 branch = push_stack(env, env->insn_idx, env->insn_idx, false); 14592 if (IS_ERR(branch)) 14593 return PTR_ERR(branch); 14594 14595 regs = branch->frame[branch->curframe]->regs; 14596 if (alu32) { 14597 __mark_reg32_known(®s[insn->dst_reg], 0); 14598 __mark_reg32_known(dst_reg, -1ull); 14599 } else { 14600 __mark_reg_known(®s[insn->dst_reg], 0); 14601 __mark_reg_known(dst_reg, -1ull); 14602 } 14603 return 0; 14604 } 14605 14606 /* WARNING: This function does calculations on 64-bit values, but the actual 14607 * execution may occur on 32-bit values. Therefore, things like bitshifts 14608 * need extra checks in the 32-bit case. 14609 */ 14610 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14611 struct bpf_insn *insn, 14612 struct bpf_reg_state *dst_reg, 14613 struct bpf_reg_state src_reg) 14614 { 14615 u8 opcode = BPF_OP(insn->code); 14616 s16 off = insn->off; 14617 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14618 int ret; 14619 14620 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14621 __mark_reg_unknown(env, dst_reg); 14622 return 0; 14623 } 14624 14625 if (sanitize_needed(opcode)) { 14626 ret = sanitize_val_alu(env, insn); 14627 if (ret < 0) 14628 return sanitize_err(env, insn, ret); 14629 } 14630 14631 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14632 * There are two classes of instructions: The first class we track both 14633 * alu32 and alu64 sign/unsigned bounds independently this provides the 14634 * greatest amount of precision when alu operations are mixed with jmp32 14635 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14636 * and BPF_OR. This is possible because these ops have fairly easy to 14637 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14638 * See alu32 verifier tests for examples. The second class of 14639 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14640 * with regards to tracking sign/unsigned bounds because the bits may 14641 * cross subreg boundaries in the alu64 case. When this happens we mark 14642 * the reg unbounded in the subreg bound space and use the resulting 14643 * tnum to calculate an approximation of the sign/unsigned bounds. 14644 */ 14645 switch (opcode) { 14646 case BPF_ADD: 14647 scalar32_min_max_add(dst_reg, &src_reg); 14648 scalar_min_max_add(dst_reg, &src_reg); 14649 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14650 break; 14651 case BPF_SUB: 14652 scalar32_min_max_sub(dst_reg, &src_reg); 14653 scalar_min_max_sub(dst_reg, &src_reg); 14654 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14655 break; 14656 case BPF_NEG: 14657 env->fake_reg[0] = *dst_reg; 14658 __mark_reg_known(dst_reg, 0); 14659 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 14660 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 14661 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 14662 break; 14663 case BPF_MUL: 14664 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14665 scalar32_min_max_mul(dst_reg, &src_reg); 14666 scalar_min_max_mul(dst_reg, &src_reg); 14667 break; 14668 case BPF_DIV: 14669 /* BPF div specification: x / 0 = 0 */ 14670 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) { 14671 ___mark_reg_known(dst_reg, 0); 14672 break; 14673 } 14674 if (alu32) 14675 if (off == 1) 14676 scalar32_min_max_sdiv(dst_reg, &src_reg); 14677 else 14678 scalar32_min_max_udiv(dst_reg, &src_reg); 14679 else 14680 if (off == 1) 14681 scalar_min_max_sdiv(dst_reg, &src_reg); 14682 else 14683 scalar_min_max_udiv(dst_reg, &src_reg); 14684 break; 14685 case BPF_MOD: 14686 /* BPF mod specification: x % 0 = x */ 14687 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) 14688 break; 14689 if (alu32) 14690 if (off == 1) 14691 scalar32_min_max_smod(dst_reg, &src_reg); 14692 else 14693 scalar32_min_max_umod(dst_reg, &src_reg); 14694 else 14695 if (off == 1) 14696 scalar_min_max_smod(dst_reg, &src_reg); 14697 else 14698 scalar_min_max_umod(dst_reg, &src_reg); 14699 break; 14700 case BPF_AND: 14701 if (tnum_is_const(src_reg.var_off)) { 14702 ret = maybe_fork_scalars(env, insn, dst_reg); 14703 if (ret) 14704 return ret; 14705 } 14706 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14707 scalar32_min_max_and(dst_reg, &src_reg); 14708 scalar_min_max_and(dst_reg, &src_reg); 14709 break; 14710 case BPF_OR: 14711 if (tnum_is_const(src_reg.var_off)) { 14712 ret = maybe_fork_scalars(env, insn, dst_reg); 14713 if (ret) 14714 return ret; 14715 } 14716 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14717 scalar32_min_max_or(dst_reg, &src_reg); 14718 scalar_min_max_or(dst_reg, &src_reg); 14719 break; 14720 case BPF_XOR: 14721 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14722 scalar32_min_max_xor(dst_reg, &src_reg); 14723 scalar_min_max_xor(dst_reg, &src_reg); 14724 break; 14725 case BPF_LSH: 14726 if (alu32) 14727 scalar32_min_max_lsh(dst_reg, &src_reg); 14728 else 14729 scalar_min_max_lsh(dst_reg, &src_reg); 14730 break; 14731 case BPF_RSH: 14732 if (alu32) 14733 scalar32_min_max_rsh(dst_reg, &src_reg); 14734 else 14735 scalar_min_max_rsh(dst_reg, &src_reg); 14736 break; 14737 case BPF_ARSH: 14738 if (alu32) 14739 scalar32_min_max_arsh(dst_reg, &src_reg); 14740 else 14741 scalar_min_max_arsh(dst_reg, &src_reg); 14742 break; 14743 case BPF_END: 14744 scalar_byte_swap(dst_reg, insn); 14745 break; 14746 default: 14747 break; 14748 } 14749 14750 /* 14751 * ALU32 ops are zero extended into 64bit register. 14752 * 14753 * BPF_END is already handled inside the helper (truncation), 14754 * so skip zext here to avoid unexpected zero extension. 14755 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40 14756 * This is a 64bit byte swap operation with alu32==true, 14757 * but we should not zero extend the result. 14758 */ 14759 if (alu32 && opcode != BPF_END) 14760 zext_32_to_64(dst_reg); 14761 reg_bounds_sync(dst_reg); 14762 return 0; 14763 } 14764 14765 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14766 * and var_off. 14767 */ 14768 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14769 struct bpf_insn *insn) 14770 { 14771 struct bpf_verifier_state *vstate = env->cur_state; 14772 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14773 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14774 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14775 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14776 u8 opcode = BPF_OP(insn->code); 14777 int err; 14778 14779 dst_reg = ®s[insn->dst_reg]; 14780 if (BPF_SRC(insn->code) == BPF_X) 14781 src_reg = ®s[insn->src_reg]; 14782 else 14783 src_reg = NULL; 14784 14785 /* Case where at least one operand is an arena. */ 14786 if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) { 14787 struct bpf_insn_aux_data *aux = cur_aux(env); 14788 14789 if (dst_reg->type != PTR_TO_ARENA) 14790 *dst_reg = *src_reg; 14791 14792 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14793 /* 14794 * 32-bit operations zero upper bits automatically. 14795 * 64-bit operations need to be converted to 32. 14796 */ 14797 aux->needs_zext = true; 14798 aux->zext_dst = true; 14799 } 14800 14801 /* Any arithmetic operations are allowed on arena pointers */ 14802 return 0; 14803 } 14804 14805 if (dst_reg->type != SCALAR_VALUE) 14806 ptr_reg = dst_reg; 14807 14808 if (BPF_SRC(insn->code) == BPF_X) { 14809 if (src_reg->type != SCALAR_VALUE) { 14810 if (dst_reg->type != SCALAR_VALUE) { 14811 /* Combining two pointers by any ALU op yields 14812 * an arbitrary scalar. Disallow all math except 14813 * pointer subtraction 14814 */ 14815 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14816 mark_reg_unknown(env, regs, insn->dst_reg); 14817 return 0; 14818 } 14819 verbose(env, "R%d pointer %s pointer prohibited\n", 14820 insn->dst_reg, 14821 bpf_alu_string[opcode >> 4]); 14822 return -EACCES; 14823 } else { 14824 /* scalar += pointer 14825 * This is legal, but we have to reverse our 14826 * src/dest handling in computing the range 14827 */ 14828 err = mark_chain_precision(env, insn->dst_reg); 14829 if (err) 14830 return err; 14831 off_reg = *dst_reg; 14832 return adjust_ptr_min_max_vals(env, insn, src_reg, &off_reg); 14833 } 14834 } else if (ptr_reg) { 14835 /* pointer += scalar */ 14836 err = mark_chain_precision(env, insn->src_reg); 14837 if (err) 14838 return err; 14839 return adjust_ptr_min_max_vals(env, insn, 14840 dst_reg, src_reg); 14841 } else if (dst_reg->precise) { 14842 /* if dst_reg is precise, src_reg should be precise as well */ 14843 err = mark_chain_precision(env, insn->src_reg); 14844 if (err) 14845 return err; 14846 } 14847 } else { 14848 /* Pretend the src is a reg with a known value, since we only 14849 * need to be able to read from this state. 14850 */ 14851 off_reg.type = SCALAR_VALUE; 14852 __mark_reg_known(&off_reg, insn->imm); 14853 src_reg = &off_reg; 14854 if (ptr_reg) /* pointer += K */ 14855 return adjust_ptr_min_max_vals(env, insn, 14856 ptr_reg, src_reg); 14857 } 14858 14859 /* Got here implies adding two SCALAR_VALUEs */ 14860 if (WARN_ON_ONCE(ptr_reg)) { 14861 print_verifier_state(env, vstate, vstate->curframe, true); 14862 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14863 return -EFAULT; 14864 } 14865 if (WARN_ON(!src_reg)) { 14866 print_verifier_state(env, vstate, vstate->curframe, true); 14867 verbose(env, "verifier internal error: no src_reg\n"); 14868 return -EFAULT; 14869 } 14870 /* 14871 * For alu32 linked register tracking, we need to check dst_reg's 14872 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(), 14873 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX. 14874 */ 14875 u64 dst_umax = reg_umax(dst_reg); 14876 14877 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14878 if (err) 14879 return err; 14880 /* 14881 * Compilers can generate the code 14882 * r1 = r2 14883 * r1 += 0x1 14884 * if r2 < 1000 goto ... 14885 * use r1 in memory access 14886 * So remember constant delta between r2 and r1 and update r1 after 14887 * 'if' condition. 14888 */ 14889 if (env->bpf_capable && 14890 (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) && 14891 dst_reg->id && is_reg_const(src_reg, alu32) && 14892 !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) { 14893 u64 val = reg_const_value(src_reg, alu32); 14894 s32 off; 14895 14896 if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX)) 14897 goto clear_id; 14898 14899 if (alu32 && (dst_umax > U32_MAX)) 14900 goto clear_id; 14901 14902 off = (s32)val; 14903 14904 if (BPF_OP(insn->code) == BPF_SUB) { 14905 /* Negating S32_MIN would overflow */ 14906 if (off == S32_MIN) 14907 goto clear_id; 14908 off = -off; 14909 } 14910 14911 if (dst_reg->id & BPF_ADD_CONST) { 14912 /* 14913 * If the register already went through rX += val 14914 * we cannot accumulate another val into rx->off. 14915 */ 14916 clear_id: 14917 clear_scalar_id(dst_reg); 14918 } else { 14919 if (alu32) 14920 dst_reg->id |= BPF_ADD_CONST32; 14921 else 14922 dst_reg->id |= BPF_ADD_CONST64; 14923 dst_reg->delta = off; 14924 } 14925 } else { 14926 /* 14927 * Make sure ID is cleared otherwise dst_reg min/max could be 14928 * incorrectly propagated into other registers by sync_linked_regs() 14929 */ 14930 clear_scalar_id(dst_reg); 14931 } 14932 return 0; 14933 } 14934 14935 /* check validity of 32-bit and 64-bit arithmetic operations */ 14936 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14937 { 14938 struct bpf_reg_state *regs = cur_regs(env); 14939 u8 opcode = BPF_OP(insn->code); 14940 int err; 14941 14942 if (opcode == BPF_END || opcode == BPF_NEG) { 14943 /* check src operand */ 14944 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14945 if (err) 14946 return err; 14947 14948 if (is_pointer_value(env, insn->dst_reg)) { 14949 verbose(env, "R%d pointer arithmetic prohibited\n", 14950 insn->dst_reg); 14951 return -EACCES; 14952 } 14953 14954 /* check dest operand */ 14955 if (regs[insn->dst_reg].type == SCALAR_VALUE) { 14956 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14957 err = err ?: adjust_scalar_min_max_vals(env, insn, 14958 ®s[insn->dst_reg], 14959 regs[insn->dst_reg]); 14960 } else { 14961 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14962 } 14963 if (err) 14964 return err; 14965 14966 } else if (opcode == BPF_MOV) { 14967 14968 if (BPF_SRC(insn->code) == BPF_X) { 14969 if (insn->off == BPF_ADDR_SPACE_CAST) { 14970 if (!env->prog->aux->arena) { 14971 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14972 return -EINVAL; 14973 } 14974 } 14975 14976 /* check src operand */ 14977 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14978 if (err) 14979 return err; 14980 } 14981 14982 /* check dest operand, mark as required later */ 14983 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14984 if (err) 14985 return err; 14986 14987 if (BPF_SRC(insn->code) == BPF_X) { 14988 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14989 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14990 14991 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14992 if (insn->imm) { 14993 /* off == BPF_ADDR_SPACE_CAST */ 14994 mark_reg_unknown(env, regs, insn->dst_reg); 14995 if (insn->imm == 1) /* cast from as(1) to as(0) */ 14996 dst_reg->type = PTR_TO_ARENA; 14997 } else if (insn->off == 0) { 14998 /* case: R1 = R2 14999 * copy register state to dest reg 15000 */ 15001 assign_scalar_id_before_mov(env, src_reg); 15002 *dst_reg = *src_reg; 15003 } else { 15004 /* case: R1 = (s8, s16 s32)R2 */ 15005 if (is_pointer_value(env, insn->src_reg)) { 15006 verbose(env, 15007 "R%d sign-extension part of pointer\n", 15008 insn->src_reg); 15009 return -EACCES; 15010 } else if (src_reg->type == SCALAR_VALUE) { 15011 bool no_sext; 15012 15013 no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 15014 if (no_sext) 15015 assign_scalar_id_before_mov(env, src_reg); 15016 *dst_reg = *src_reg; 15017 if (!no_sext) 15018 clear_scalar_id(dst_reg); 15019 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 15020 } else { 15021 mark_reg_unknown(env, regs, insn->dst_reg); 15022 } 15023 } 15024 } else { 15025 /* R1 = (u32) R2 */ 15026 if (is_pointer_value(env, insn->src_reg)) { 15027 verbose(env, 15028 "R%d partial copy of pointer\n", 15029 insn->src_reg); 15030 return -EACCES; 15031 } else if (src_reg->type == SCALAR_VALUE) { 15032 if (insn->off == 0) { 15033 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 15034 15035 if (is_src_reg_u32) 15036 assign_scalar_id_before_mov(env, src_reg); 15037 *dst_reg = *src_reg; 15038 /* Make sure ID is cleared if src_reg is not in u32 15039 * range otherwise dst_reg min/max could be incorrectly 15040 * propagated into src_reg by sync_linked_regs() 15041 */ 15042 if (!is_src_reg_u32) 15043 clear_scalar_id(dst_reg); 15044 } else { 15045 /* case: W1 = (s8, s16)W2 */ 15046 bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 15047 15048 if (no_sext) 15049 assign_scalar_id_before_mov(env, src_reg); 15050 *dst_reg = *src_reg; 15051 if (!no_sext) 15052 clear_scalar_id(dst_reg); 15053 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 15054 } 15055 } else { 15056 mark_reg_unknown(env, regs, 15057 insn->dst_reg); 15058 } 15059 zext_32_to_64(dst_reg); 15060 reg_bounds_sync(dst_reg); 15061 } 15062 } else { 15063 /* case: R = imm 15064 * remember the value we stored into this reg 15065 */ 15066 /* clear any state __mark_reg_known doesn't set */ 15067 mark_reg_unknown(env, regs, insn->dst_reg); 15068 regs[insn->dst_reg].type = SCALAR_VALUE; 15069 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15070 __mark_reg_known(regs + insn->dst_reg, 15071 insn->imm); 15072 } else { 15073 __mark_reg_known(regs + insn->dst_reg, 15074 (u32)insn->imm); 15075 } 15076 } 15077 15078 } else { /* all other ALU ops: and, sub, xor, add, ... */ 15079 15080 if (BPF_SRC(insn->code) == BPF_X) { 15081 /* check src1 operand */ 15082 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15083 if (err) 15084 return err; 15085 } 15086 15087 /* check src2 operand */ 15088 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15089 if (err) 15090 return err; 15091 15092 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 15093 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 15094 verbose(env, "div by zero\n"); 15095 return -EINVAL; 15096 } 15097 15098 if ((opcode == BPF_LSH || opcode == BPF_RSH || 15099 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 15100 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 15101 15102 if (insn->imm < 0 || insn->imm >= size) { 15103 verbose(env, "invalid shift %d\n", insn->imm); 15104 return -EINVAL; 15105 } 15106 } 15107 15108 /* check dest operand */ 15109 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15110 err = err ?: adjust_reg_min_max_vals(env, insn); 15111 if (err) 15112 return err; 15113 } 15114 15115 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 15116 } 15117 15118 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 15119 struct bpf_reg_state *dst_reg, 15120 enum bpf_reg_type type, 15121 bool range_right_open) 15122 { 15123 struct bpf_func_state *state; 15124 struct bpf_reg_state *reg; 15125 int new_range; 15126 15127 if (reg_umax(dst_reg) == 0 && range_right_open) 15128 /* This doesn't give us any range */ 15129 return; 15130 15131 if (reg_umax(dst_reg) > MAX_PACKET_OFF) 15132 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15133 * than pkt_end, but that's because it's also less than pkt. 15134 */ 15135 return; 15136 15137 new_range = reg_umax(dst_reg); 15138 if (range_right_open) 15139 new_range++; 15140 15141 /* Examples for register markings: 15142 * 15143 * pkt_data in dst register: 15144 * 15145 * r2 = r3; 15146 * r2 += 8; 15147 * if (r2 > pkt_end) goto <handle exception> 15148 * <access okay> 15149 * 15150 * r2 = r3; 15151 * r2 += 8; 15152 * if (r2 < pkt_end) goto <access okay> 15153 * <handle exception> 15154 * 15155 * Where: 15156 * r2 == dst_reg, pkt_end == src_reg 15157 * r2=pkt(id=n,off=8,r=0) 15158 * r3=pkt(id=n,off=0,r=0) 15159 * 15160 * pkt_data in src register: 15161 * 15162 * r2 = r3; 15163 * r2 += 8; 15164 * if (pkt_end >= r2) goto <access okay> 15165 * <handle exception> 15166 * 15167 * r2 = r3; 15168 * r2 += 8; 15169 * if (pkt_end <= r2) goto <handle exception> 15170 * <access okay> 15171 * 15172 * Where: 15173 * pkt_end == dst_reg, r2 == src_reg 15174 * r2=pkt(id=n,off=8,r=0) 15175 * r3=pkt(id=n,off=0,r=0) 15176 * 15177 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15178 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15179 * and [r3, r3 + 8-1) respectively is safe to access depending on 15180 * the check. 15181 */ 15182 15183 /* If our ids match, then we must have the same max_value. And we 15184 * don't care about the other reg's fixed offset, since if it's too big 15185 * the range won't allow anything. 15186 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16. 15187 */ 15188 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15189 if (reg->type == type && reg->id == dst_reg->id) 15190 /* keep the maximum range already checked */ 15191 reg->range = max(reg->range, new_range); 15192 })); 15193 } 15194 15195 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15196 u8 opcode, bool is_jmp32); 15197 static u8 rev_opcode(u8 opcode); 15198 15199 /* 15200 * Learn more information about live branches by simulating refinement on both branches. 15201 * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means 15202 * that branch is dead. 15203 */ 15204 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32) 15205 { 15206 /* Fallthrough (FALSE) branch */ 15207 regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32); 15208 reg_bounds_sync(&env->false_reg1); 15209 reg_bounds_sync(&env->false_reg2); 15210 /* 15211 * If there is a range bounds violation in *any* of the abstract values in either 15212 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only 15213 * TRUE branch will be taken. 15214 */ 15215 if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2)) 15216 return 1; 15217 15218 /* Jump (TRUE) branch */ 15219 regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32); 15220 reg_bounds_sync(&env->true_reg1); 15221 reg_bounds_sync(&env->true_reg2); 15222 /* 15223 * If there is a range bounds violation in *any* of the abstract values in either 15224 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead. 15225 * Only FALSE branch will be taken. 15226 */ 15227 if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2)) 15228 return 0; 15229 15230 /* Both branches are possible, we can't determine which one will be taken. */ 15231 return -1; 15232 } 15233 15234 /* 15235 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15236 */ 15237 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15238 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15239 { 15240 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15241 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15242 u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1); 15243 u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1); 15244 s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1); 15245 s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1); 15246 u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2); 15247 u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2); 15248 s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2); 15249 s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2); 15250 15251 if (reg1 == reg2) { 15252 switch (opcode) { 15253 case BPF_JGE: 15254 case BPF_JLE: 15255 case BPF_JSGE: 15256 case BPF_JSLE: 15257 case BPF_JEQ: 15258 return 1; 15259 case BPF_JGT: 15260 case BPF_JLT: 15261 case BPF_JSGT: 15262 case BPF_JSLT: 15263 case BPF_JNE: 15264 return 0; 15265 case BPF_JSET: 15266 if (tnum_is_const(t1)) 15267 return t1.value != 0; 15268 else 15269 return (smin1 <= 0 && smax1 >= 0) ? -1 : 1; 15270 default: 15271 return -1; 15272 } 15273 } 15274 15275 switch (opcode) { 15276 case BPF_JEQ: 15277 /* constants, umin/umax and smin/smax checks would be 15278 * redundant in this case because they all should match 15279 */ 15280 if (tnum_is_const(t1) && tnum_is_const(t2)) 15281 return t1.value == t2.value; 15282 if (!tnum_overlap(t1, t2)) 15283 return 0; 15284 /* non-overlapping ranges */ 15285 if (umin1 > umax2 || umax1 < umin2) 15286 return 0; 15287 if (smin1 > smax2 || smax1 < smin2) 15288 return 0; 15289 if (!is_jmp32) { 15290 /* if 64-bit ranges are inconclusive, see if we can 15291 * utilize 32-bit subrange knowledge to eliminate 15292 * branches that can't be taken a priori 15293 */ 15294 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15295 reg_u32_max(reg1) < reg_u32_min(reg2)) 15296 return 0; 15297 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15298 reg_s32_max(reg1) < reg_s32_min(reg2)) 15299 return 0; 15300 } 15301 break; 15302 case BPF_JNE: 15303 /* constants, umin/umax and smin/smax checks would be 15304 * redundant in this case because they all should match 15305 */ 15306 if (tnum_is_const(t1) && tnum_is_const(t2)) 15307 return t1.value != t2.value; 15308 if (!tnum_overlap(t1, t2)) 15309 return 1; 15310 /* non-overlapping ranges */ 15311 if (umin1 > umax2 || umax1 < umin2) 15312 return 1; 15313 if (smin1 > smax2 || smax1 < smin2) 15314 return 1; 15315 if (!is_jmp32) { 15316 /* if 64-bit ranges are inconclusive, see if we can 15317 * utilize 32-bit subrange knowledge to eliminate 15318 * branches that can't be taken a priori 15319 */ 15320 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15321 reg_u32_max(reg1) < reg_u32_min(reg2)) 15322 return 1; 15323 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15324 reg_s32_max(reg1) < reg_s32_min(reg2)) 15325 return 1; 15326 } 15327 break; 15328 case BPF_JSET: 15329 if (!is_reg_const(reg2, is_jmp32)) { 15330 swap(reg1, reg2); 15331 swap(t1, t2); 15332 } 15333 if (!is_reg_const(reg2, is_jmp32)) 15334 return -1; 15335 if ((~t1.mask & t1.value) & t2.value) 15336 return 1; 15337 if (!((t1.mask | t1.value) & t2.value)) 15338 return 0; 15339 break; 15340 case BPF_JGT: 15341 if (umin1 > umax2) 15342 return 1; 15343 else if (umax1 <= umin2) 15344 return 0; 15345 break; 15346 case BPF_JSGT: 15347 if (smin1 > smax2) 15348 return 1; 15349 else if (smax1 <= smin2) 15350 return 0; 15351 break; 15352 case BPF_JLT: 15353 if (umax1 < umin2) 15354 return 1; 15355 else if (umin1 >= umax2) 15356 return 0; 15357 break; 15358 case BPF_JSLT: 15359 if (smax1 < smin2) 15360 return 1; 15361 else if (smin1 >= smax2) 15362 return 0; 15363 break; 15364 case BPF_JGE: 15365 if (umin1 >= umax2) 15366 return 1; 15367 else if (umax1 < umin2) 15368 return 0; 15369 break; 15370 case BPF_JSGE: 15371 if (smin1 >= smax2) 15372 return 1; 15373 else if (smax1 < smin2) 15374 return 0; 15375 break; 15376 case BPF_JLE: 15377 if (umax1 <= umin2) 15378 return 1; 15379 else if (umin1 > umax2) 15380 return 0; 15381 break; 15382 case BPF_JSLE: 15383 if (smax1 <= smin2) 15384 return 1; 15385 else if (smin1 > smax2) 15386 return 0; 15387 break; 15388 } 15389 15390 return simulate_both_branches_taken(env, opcode, is_jmp32); 15391 } 15392 15393 static int flip_opcode(u32 opcode) 15394 { 15395 /* How can we transform "a <op> b" into "b <op> a"? */ 15396 static const u8 opcode_flip[16] = { 15397 /* these stay the same */ 15398 [BPF_JEQ >> 4] = BPF_JEQ, 15399 [BPF_JNE >> 4] = BPF_JNE, 15400 [BPF_JSET >> 4] = BPF_JSET, 15401 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 15402 [BPF_JGE >> 4] = BPF_JLE, 15403 [BPF_JGT >> 4] = BPF_JLT, 15404 [BPF_JLE >> 4] = BPF_JGE, 15405 [BPF_JLT >> 4] = BPF_JGT, 15406 [BPF_JSGE >> 4] = BPF_JSLE, 15407 [BPF_JSGT >> 4] = BPF_JSLT, 15408 [BPF_JSLE >> 4] = BPF_JSGE, 15409 [BPF_JSLT >> 4] = BPF_JSGT 15410 }; 15411 return opcode_flip[opcode >> 4]; 15412 } 15413 15414 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 15415 struct bpf_reg_state *src_reg, 15416 u8 opcode) 15417 { 15418 struct bpf_reg_state *pkt; 15419 15420 if (src_reg->type == PTR_TO_PACKET_END) { 15421 pkt = dst_reg; 15422 } else if (dst_reg->type == PTR_TO_PACKET_END) { 15423 pkt = src_reg; 15424 opcode = flip_opcode(opcode); 15425 } else { 15426 return -1; 15427 } 15428 15429 if (pkt->range >= 0) 15430 return -1; 15431 15432 switch (opcode) { 15433 case BPF_JLE: 15434 /* pkt <= pkt_end */ 15435 fallthrough; 15436 case BPF_JGT: 15437 /* pkt > pkt_end */ 15438 if (pkt->range == BEYOND_PKT_END) 15439 /* pkt has at last one extra byte beyond pkt_end */ 15440 return opcode == BPF_JGT; 15441 break; 15442 case BPF_JLT: 15443 /* pkt < pkt_end */ 15444 fallthrough; 15445 case BPF_JGE: 15446 /* pkt >= pkt_end */ 15447 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 15448 return opcode == BPF_JGE; 15449 break; 15450 } 15451 return -1; 15452 } 15453 15454 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 15455 * and return: 15456 * 1 - branch will be taken and "goto target" will be executed 15457 * 0 - branch will not be taken and fall-through to next insn 15458 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 15459 * range [0,10] 15460 */ 15461 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15462 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15463 { 15464 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 15465 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 15466 15467 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 15468 u64 val; 15469 15470 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 15471 if (!is_reg_const(reg2, is_jmp32)) { 15472 opcode = flip_opcode(opcode); 15473 swap(reg1, reg2); 15474 } 15475 /* and ensure that reg2 is a constant */ 15476 if (!is_reg_const(reg2, is_jmp32)) 15477 return -1; 15478 15479 if (!reg_not_null(env, reg1)) 15480 return -1; 15481 15482 /* If pointer is valid tests against zero will fail so we can 15483 * use this to direct branch taken. 15484 */ 15485 val = reg_const_value(reg2, is_jmp32); 15486 if (val != 0) 15487 return -1; 15488 15489 switch (opcode) { 15490 case BPF_JEQ: 15491 return 0; 15492 case BPF_JNE: 15493 return 1; 15494 default: 15495 return -1; 15496 } 15497 } 15498 15499 /* now deal with two scalars, but not necessarily constants */ 15500 return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32); 15501 } 15502 15503 /* Opcode that corresponds to a *false* branch condition. 15504 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 15505 */ 15506 static u8 rev_opcode(u8 opcode) 15507 { 15508 switch (opcode) { 15509 case BPF_JEQ: return BPF_JNE; 15510 case BPF_JNE: return BPF_JEQ; 15511 /* JSET doesn't have it's reverse opcode in BPF, so add 15512 * BPF_X flag to denote the reverse of that operation 15513 */ 15514 case BPF_JSET: return BPF_JSET | BPF_X; 15515 case BPF_JSET | BPF_X: return BPF_JSET; 15516 case BPF_JGE: return BPF_JLT; 15517 case BPF_JGT: return BPF_JLE; 15518 case BPF_JLE: return BPF_JGT; 15519 case BPF_JLT: return BPF_JGE; 15520 case BPF_JSGE: return BPF_JSLT; 15521 case BPF_JSGT: return BPF_JSLE; 15522 case BPF_JSLE: return BPF_JSGT; 15523 case BPF_JSLT: return BPF_JSGE; 15524 default: return 0; 15525 } 15526 } 15527 15528 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 15529 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15530 u8 opcode, bool is_jmp32) 15531 { 15532 struct tnum t; 15533 u64 val; 15534 15535 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 15536 switch (opcode) { 15537 case BPF_JGE: 15538 case BPF_JGT: 15539 case BPF_JSGE: 15540 case BPF_JSGT: 15541 opcode = flip_opcode(opcode); 15542 swap(reg1, reg2); 15543 break; 15544 default: 15545 break; 15546 } 15547 15548 switch (opcode) { 15549 case BPF_JEQ: 15550 if (is_jmp32) { 15551 reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32); 15552 reg2->r32 = reg1->r32; 15553 15554 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 15555 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15556 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 15557 } else { 15558 reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64); 15559 reg2->r64 = reg1->r64; 15560 15561 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 15562 reg2->var_off = reg1->var_off; 15563 } 15564 break; 15565 case BPF_JNE: 15566 if (!is_reg_const(reg2, is_jmp32)) 15567 swap(reg1, reg2); 15568 if (!is_reg_const(reg2, is_jmp32)) 15569 break; 15570 15571 /* try to recompute the bound of reg1 if reg2 is a const and 15572 * is exactly the edge of reg1. 15573 */ 15574 val = reg_const_value(reg2, is_jmp32); 15575 if (is_jmp32) { 15576 /* Complement of the range [val, val] as cnum32. */ 15577 cnum32_intersect_with(®1->r32, (struct cnum32){ val + 1, U32_MAX - 1 }); 15578 } else { 15579 /* Complement of the range [val, val] as cnum64. */ 15580 cnum64_intersect_with(®1->r64, (struct cnum64){ val + 1, U64_MAX - 1 }); 15581 } 15582 break; 15583 case BPF_JSET: 15584 if (!is_reg_const(reg2, is_jmp32)) 15585 swap(reg1, reg2); 15586 if (!is_reg_const(reg2, is_jmp32)) 15587 break; 15588 val = reg_const_value(reg2, is_jmp32); 15589 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 15590 * requires single bit to learn something useful. E.g., if we 15591 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 15592 * are actually set? We can learn something definite only if 15593 * it's a single-bit value to begin with. 15594 * 15595 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 15596 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 15597 * bit 1 is set, which we can readily use in adjustments. 15598 */ 15599 if (!is_power_of_2(val)) 15600 break; 15601 if (is_jmp32) { 15602 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 15603 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15604 } else { 15605 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 15606 } 15607 break; 15608 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 15609 if (!is_reg_const(reg2, is_jmp32)) 15610 swap(reg1, reg2); 15611 if (!is_reg_const(reg2, is_jmp32)) 15612 break; 15613 val = reg_const_value(reg2, is_jmp32); 15614 /* Forget the ranges before narrowing tnums, to avoid invariant 15615 * violations if we're on a dead branch. 15616 */ 15617 __mark_reg_unbounded(reg1); 15618 if (is_jmp32) { 15619 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 15620 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15621 } else { 15622 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15623 } 15624 break; 15625 case BPF_JLE: 15626 if (is_jmp32) { 15627 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2)); 15628 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1), U32_MAX); 15629 } else { 15630 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2)); 15631 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1), U64_MAX); 15632 } 15633 break; 15634 case BPF_JLT: 15635 if (is_jmp32) { 15636 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2) - 1); 15637 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1) + 1, U32_MAX); 15638 } else { 15639 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2) - 1); 15640 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1) + 1, U64_MAX); 15641 } 15642 break; 15643 case BPF_JSLE: 15644 if (is_jmp32) { 15645 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2)); 15646 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1), S32_MAX); 15647 } else { 15648 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2)); 15649 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1), S64_MAX); 15650 } 15651 break; 15652 case BPF_JSLT: 15653 if (is_jmp32) { 15654 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2) - 1); 15655 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1) + 1, S32_MAX); 15656 } else { 15657 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2) - 1); 15658 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1) + 1, S64_MAX); 15659 } 15660 break; 15661 default: 15662 return; 15663 } 15664 } 15665 15666 /* Check for invariant violations on the registers for both branches of a condition */ 15667 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env) 15668 { 15669 int err; 15670 15671 err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1"); 15672 err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2"); 15673 err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1"); 15674 err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2"); 15675 return err; 15676 } 15677 15678 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 15679 struct bpf_reg_state *reg, u32 id, 15680 bool is_null) 15681 { 15682 if (type_may_be_null(reg->type) && reg->id == id && 15683 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 15684 /* Old offset should have been known-zero, because we don't 15685 * allow pointer arithmetic on pointers that might be NULL. 15686 * If we see this happening, don't convert the register. 15687 * 15688 * But in some cases, some helpers that return local kptrs 15689 * advance offset for the returned pointer. In those cases, 15690 * it is fine to expect to see reg->var_off. 15691 */ 15692 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 15693 WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0))) 15694 return; 15695 if (is_null) { 15696 /* We don't need id from this point 15697 * onwards anymore, thus we should better reset it, 15698 * so that state pruning has chances to take effect. 15699 */ 15700 __mark_reg_known_zero(reg); 15701 reg->type = SCALAR_VALUE; 15702 15703 return; 15704 } 15705 15706 mark_ptr_not_null_reg(reg); 15707 15708 /* 15709 * reg->id is preserved for object relationship tracking 15710 * and spin_lock lock state tracking 15711 */ 15712 } 15713 } 15714 15715 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15716 * be folded together at some point. 15717 */ 15718 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15719 bool is_null) 15720 { 15721 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15722 struct bpf_reg_state *regs = state->regs, *reg; 15723 u32 id = regs[regno].id; 15724 15725 if (is_null && find_reference_state(vstate, id)) 15726 /* regs[regno] is in the " == NULL" branch. 15727 * No one could have freed the reference state before 15728 * doing the NULL check. 15729 */ 15730 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 15731 15732 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15733 mark_ptr_or_null_reg(state, reg, id, is_null); 15734 })); 15735 } 15736 15737 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15738 struct bpf_reg_state *dst_reg, 15739 struct bpf_reg_state *src_reg, 15740 struct bpf_verifier_state *this_branch, 15741 struct bpf_verifier_state *other_branch) 15742 { 15743 if (BPF_SRC(insn->code) != BPF_X) 15744 return false; 15745 15746 /* Pointers are always 64-bit. */ 15747 if (BPF_CLASS(insn->code) == BPF_JMP32) 15748 return false; 15749 15750 switch (BPF_OP(insn->code)) { 15751 case BPF_JGT: 15752 if ((dst_reg->type == PTR_TO_PACKET && 15753 src_reg->type == PTR_TO_PACKET_END) || 15754 (dst_reg->type == PTR_TO_PACKET_META && 15755 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15756 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15757 find_good_pkt_pointers(this_branch, dst_reg, 15758 dst_reg->type, false); 15759 mark_pkt_end(other_branch, insn->dst_reg, true); 15760 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15761 src_reg->type == PTR_TO_PACKET) || 15762 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15763 src_reg->type == PTR_TO_PACKET_META)) { 15764 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15765 find_good_pkt_pointers(other_branch, src_reg, 15766 src_reg->type, true); 15767 mark_pkt_end(this_branch, insn->src_reg, false); 15768 } else { 15769 return false; 15770 } 15771 break; 15772 case BPF_JLT: 15773 if ((dst_reg->type == PTR_TO_PACKET && 15774 src_reg->type == PTR_TO_PACKET_END) || 15775 (dst_reg->type == PTR_TO_PACKET_META && 15776 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15777 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15778 find_good_pkt_pointers(other_branch, dst_reg, 15779 dst_reg->type, true); 15780 mark_pkt_end(this_branch, insn->dst_reg, false); 15781 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15782 src_reg->type == PTR_TO_PACKET) || 15783 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15784 src_reg->type == PTR_TO_PACKET_META)) { 15785 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15786 find_good_pkt_pointers(this_branch, src_reg, 15787 src_reg->type, false); 15788 mark_pkt_end(other_branch, insn->src_reg, true); 15789 } else { 15790 return false; 15791 } 15792 break; 15793 case BPF_JGE: 15794 if ((dst_reg->type == PTR_TO_PACKET && 15795 src_reg->type == PTR_TO_PACKET_END) || 15796 (dst_reg->type == PTR_TO_PACKET_META && 15797 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15798 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15799 find_good_pkt_pointers(this_branch, dst_reg, 15800 dst_reg->type, true); 15801 mark_pkt_end(other_branch, insn->dst_reg, false); 15802 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15803 src_reg->type == PTR_TO_PACKET) || 15804 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15805 src_reg->type == PTR_TO_PACKET_META)) { 15806 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15807 find_good_pkt_pointers(other_branch, src_reg, 15808 src_reg->type, false); 15809 mark_pkt_end(this_branch, insn->src_reg, true); 15810 } else { 15811 return false; 15812 } 15813 break; 15814 case BPF_JLE: 15815 if ((dst_reg->type == PTR_TO_PACKET && 15816 src_reg->type == PTR_TO_PACKET_END) || 15817 (dst_reg->type == PTR_TO_PACKET_META && 15818 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15819 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15820 find_good_pkt_pointers(other_branch, dst_reg, 15821 dst_reg->type, false); 15822 mark_pkt_end(this_branch, insn->dst_reg, true); 15823 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15824 src_reg->type == PTR_TO_PACKET) || 15825 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15826 src_reg->type == PTR_TO_PACKET_META)) { 15827 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15828 find_good_pkt_pointers(this_branch, src_reg, 15829 src_reg->type, true); 15830 mark_pkt_end(other_branch, insn->src_reg, false); 15831 } else { 15832 return false; 15833 } 15834 break; 15835 default: 15836 return false; 15837 } 15838 15839 return true; 15840 } 15841 15842 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 15843 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 15844 { 15845 struct linked_reg *e; 15846 15847 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 15848 return; 15849 15850 e = linked_regs_push(reg_set); 15851 if (e) { 15852 e->frameno = frameno; 15853 e->is_reg = is_reg; 15854 e->regno = spi_or_reg; 15855 } else { 15856 clear_scalar_id(reg); 15857 } 15858 } 15859 15860 /* For all R being scalar registers or spilled scalar registers 15861 * in verifier state, save R in linked_regs if R->id == id. 15862 * If there are too many Rs sharing same id, reset id for leftover Rs. 15863 */ 15864 static void collect_linked_regs(struct bpf_verifier_env *env, 15865 struct bpf_verifier_state *vstate, 15866 u32 id, 15867 struct linked_regs *linked_regs) 15868 { 15869 struct bpf_insn_aux_data *aux = env->insn_aux_data; 15870 struct bpf_func_state *func; 15871 struct bpf_reg_state *reg; 15872 u16 live_regs; 15873 int i, j; 15874 15875 id = id & ~BPF_ADD_CONST; 15876 for (i = vstate->curframe; i >= 0; i--) { 15877 live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before; 15878 func = vstate->frame[i]; 15879 for (j = 0; j < BPF_REG_FP; j++) { 15880 if (!(live_regs & BIT(j))) 15881 continue; 15882 reg = &func->regs[j]; 15883 __collect_linked_regs(linked_regs, reg, id, i, j, true); 15884 } 15885 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 15886 if (!bpf_is_spilled_reg(&func->stack[j])) 15887 continue; 15888 reg = &func->stack[j].spilled_ptr; 15889 __collect_linked_regs(linked_regs, reg, id, i, j, false); 15890 } 15891 } 15892 } 15893 15894 /* For all R in linked_regs, copy known_reg range into R 15895 * if R->id == known_reg->id. 15896 */ 15897 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate, 15898 struct bpf_reg_state *known_reg, struct linked_regs *linked_regs) 15899 { 15900 struct bpf_reg_state fake_reg; 15901 struct bpf_reg_state *reg; 15902 struct linked_reg *e; 15903 int i; 15904 15905 for (i = 0; i < linked_regs->cnt; ++i) { 15906 e = &linked_regs->entries[i]; 15907 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 15908 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 15909 if (reg->type != SCALAR_VALUE || reg == known_reg) 15910 continue; 15911 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15912 continue; 15913 /* 15914 * Skip mixed 32/64-bit links: the delta relationship doesn't 15915 * hold across different ALU widths. 15916 */ 15917 if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST) 15918 continue; 15919 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15920 reg->delta == known_reg->delta) { 15921 *reg = *known_reg; 15922 } else { 15923 s32 saved_off = reg->delta; 15924 u32 saved_id = reg->id; 15925 15926 fake_reg.type = SCALAR_VALUE; 15927 __mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta); 15928 15929 /* reg = known_reg; reg += delta */ 15930 *reg = *known_reg; 15931 /* 15932 * Must preserve off and id, otherwise another sync_linked_regs() 15933 * will be incorrect. 15934 */ 15935 reg->delta = saved_off; 15936 reg->id = saved_id; 15937 15938 scalar32_min_max_add(reg, &fake_reg); 15939 scalar_min_max_add(reg, &fake_reg); 15940 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15941 if ((reg->id | known_reg->id) & BPF_ADD_CONST32) 15942 zext_32_to_64(reg); 15943 reg_bounds_sync(reg); 15944 } 15945 if (e->is_reg) 15946 mark_reg_scratched(env, e->regno); 15947 else 15948 mark_stack_slot_scratched(env, e->spi); 15949 } 15950 } 15951 15952 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15953 struct bpf_insn *insn, int *insn_idx) 15954 { 15955 struct bpf_verifier_state *this_branch = env->cur_state; 15956 struct bpf_verifier_state *other_branch; 15957 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15958 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15959 struct bpf_reg_state *eq_branch_regs; 15960 struct linked_regs linked_regs = {}; 15961 u8 opcode = BPF_OP(insn->code); 15962 int insn_flags = 0; 15963 bool is_jmp32; 15964 int pred = -1; 15965 int err; 15966 15967 /* Only conditional jumps are expected to reach here. */ 15968 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15969 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15970 return -EINVAL; 15971 } 15972 15973 if (opcode == BPF_JCOND) { 15974 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15975 int idx = *insn_idx; 15976 15977 prev_st = find_prev_entry(env, cur_st->parent, idx); 15978 15979 /* branch out 'fallthrough' insn as a new state to explore */ 15980 queued_st = push_stack(env, idx + 1, idx, false); 15981 if (IS_ERR(queued_st)) 15982 return PTR_ERR(queued_st); 15983 15984 queued_st->may_goto_depth++; 15985 if (prev_st) 15986 widen_imprecise_scalars(env, prev_st, queued_st); 15987 *insn_idx += insn->off; 15988 return 0; 15989 } 15990 15991 /* check src2 operand */ 15992 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15993 if (err) 15994 return err; 15995 15996 dst_reg = ®s[insn->dst_reg]; 15997 if (BPF_SRC(insn->code) == BPF_X) { 15998 /* check src1 operand */ 15999 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16000 if (err) 16001 return err; 16002 16003 src_reg = ®s[insn->src_reg]; 16004 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 16005 is_pointer_value(env, insn->src_reg)) { 16006 verbose(env, "R%d pointer comparison prohibited\n", 16007 insn->src_reg); 16008 return -EACCES; 16009 } 16010 16011 if (src_reg->type == PTR_TO_STACK) 16012 insn_flags |= INSN_F_SRC_REG_STACK; 16013 if (dst_reg->type == PTR_TO_STACK) 16014 insn_flags |= INSN_F_DST_REG_STACK; 16015 } else { 16016 src_reg = &env->fake_reg[0]; 16017 memset(src_reg, 0, sizeof(*src_reg)); 16018 src_reg->type = SCALAR_VALUE; 16019 __mark_reg_known(src_reg, insn->imm); 16020 16021 if (dst_reg->type == PTR_TO_STACK) 16022 insn_flags |= INSN_F_DST_REG_STACK; 16023 } 16024 16025 if (insn_flags) { 16026 err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, 0); 16027 if (err) 16028 return err; 16029 } 16030 16031 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 16032 env->false_reg1 = *dst_reg; 16033 env->false_reg2 = *src_reg; 16034 env->true_reg1 = *dst_reg; 16035 env->true_reg2 = *src_reg; 16036 pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32); 16037 if (pred >= 0) { 16038 /* If we get here with a dst_reg pointer type it is because 16039 * above is_branch_taken() special cased the 0 comparison. 16040 */ 16041 if (!__is_pointer_value(false, dst_reg)) 16042 err = mark_chain_precision(env, insn->dst_reg); 16043 if (BPF_SRC(insn->code) == BPF_X && !err && 16044 !__is_pointer_value(false, src_reg)) 16045 err = mark_chain_precision(env, insn->src_reg); 16046 if (err) 16047 return err; 16048 } 16049 16050 if (pred == 1) { 16051 /* Only follow the goto, ignore fall-through. If needed, push 16052 * the fall-through branch for simulation under speculative 16053 * execution. 16054 */ 16055 if (!env->bypass_spec_v1) { 16056 err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx); 16057 if (err < 0) 16058 return err; 16059 } 16060 if (env->log.level & BPF_LOG_LEVEL) 16061 print_insn_state(env, this_branch, this_branch->curframe); 16062 *insn_idx += insn->off; 16063 return 0; 16064 } else if (pred == 0) { 16065 /* Only follow the fall-through branch, since that's where the 16066 * program will go. If needed, push the goto branch for 16067 * simulation under speculative execution. 16068 */ 16069 if (!env->bypass_spec_v1) { 16070 err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1, 16071 *insn_idx); 16072 if (err < 0) 16073 return err; 16074 } 16075 if (env->log.level & BPF_LOG_LEVEL) 16076 print_insn_state(env, this_branch, this_branch->curframe); 16077 return 0; 16078 } 16079 16080 /* Push scalar registers sharing same ID to jump history, 16081 * do this before creating 'other_branch', so that both 16082 * 'this_branch' and 'other_branch' share this history 16083 * if parent state is created. 16084 */ 16085 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 16086 collect_linked_regs(env, this_branch, src_reg->id, &linked_regs); 16087 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 16088 collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs); 16089 if (linked_regs.cnt > 1) { 16090 err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, linked_regs_pack(&linked_regs)); 16091 if (err) 16092 return err; 16093 } 16094 16095 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); 16096 if (IS_ERR(other_branch)) 16097 return PTR_ERR(other_branch); 16098 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 16099 16100 err = regs_bounds_sanity_check_branches(env); 16101 if (err) 16102 return err; 16103 16104 *dst_reg = env->false_reg1; 16105 *src_reg = env->false_reg2; 16106 other_branch_regs[insn->dst_reg] = env->true_reg1; 16107 if (BPF_SRC(insn->code) == BPF_X) 16108 other_branch_regs[insn->src_reg] = env->true_reg2; 16109 16110 if (BPF_SRC(insn->code) == BPF_X && 16111 src_reg->type == SCALAR_VALUE && src_reg->id && 16112 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 16113 sync_linked_regs(env, this_branch, src_reg, &linked_regs); 16114 sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg], 16115 &linked_regs); 16116 } 16117 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 16118 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 16119 sync_linked_regs(env, this_branch, dst_reg, &linked_regs); 16120 sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg], 16121 &linked_regs); 16122 } 16123 16124 /* if one pointer register is compared to another pointer 16125 * register check if PTR_MAYBE_NULL could be lifted. 16126 * E.g. register A - maybe null 16127 * register B - not null 16128 * for JNE A, B, ... - A is not null in the false branch; 16129 * for JEQ A, B, ... - A is not null in the true branch. 16130 * 16131 * Since PTR_TO_BTF_ID points to a kernel struct that does 16132 * not need to be null checked by the BPF program, i.e., 16133 * could be null even without PTR_MAYBE_NULL marking, so 16134 * only propagate nullness when neither reg is that type. 16135 */ 16136 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16137 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16138 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16139 base_type(src_reg->type) != PTR_TO_BTF_ID && 16140 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16141 eq_branch_regs = NULL; 16142 switch (opcode) { 16143 case BPF_JEQ: 16144 eq_branch_regs = other_branch_regs; 16145 break; 16146 case BPF_JNE: 16147 eq_branch_regs = regs; 16148 break; 16149 default: 16150 /* do nothing */ 16151 break; 16152 } 16153 if (eq_branch_regs) { 16154 if (type_may_be_null(src_reg->type)) 16155 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16156 else 16157 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16158 } 16159 } 16160 16161 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16162 * Also does the same detection for a register whose the value is 16163 * known to be 0. 16164 * NOTE: these optimizations below are related with pointer comparison 16165 * which will never be JMP32. 16166 */ 16167 if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16168 type_may_be_null(dst_reg->type) && 16169 ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) || 16170 (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) { 16171 /* Mark all identical registers in each branch as either 16172 * safe or unknown depending R == 0 or R != 0 conditional. 16173 */ 16174 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16175 opcode == BPF_JNE); 16176 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16177 opcode == BPF_JEQ); 16178 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16179 this_branch, other_branch) && 16180 is_pointer_value(env, insn->dst_reg)) { 16181 verbose(env, "R%d pointer comparison prohibited\n", 16182 insn->dst_reg); 16183 return -EACCES; 16184 } 16185 if (env->log.level & BPF_LOG_LEVEL) 16186 print_insn_state(env, this_branch, this_branch->curframe); 16187 return 0; 16188 } 16189 16190 /* verify BPF_LD_IMM64 instruction */ 16191 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16192 { 16193 struct bpf_insn_aux_data *aux = cur_aux(env); 16194 struct bpf_reg_state *regs = cur_regs(env); 16195 struct bpf_reg_state *dst_reg; 16196 struct bpf_map *map; 16197 int err; 16198 16199 if (BPF_SIZE(insn->code) != BPF_DW) { 16200 verbose(env, "invalid BPF_LD_IMM insn\n"); 16201 return -EINVAL; 16202 } 16203 16204 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16205 if (err) 16206 return err; 16207 16208 dst_reg = ®s[insn->dst_reg]; 16209 if (insn->src_reg == 0) { 16210 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16211 16212 dst_reg->type = SCALAR_VALUE; 16213 __mark_reg_known(®s[insn->dst_reg], imm); 16214 return 0; 16215 } 16216 16217 /* All special src_reg cases are listed below. From this point onwards 16218 * we either succeed and assign a corresponding dst_reg->type after 16219 * zeroing the offset, or fail and reject the program. 16220 */ 16221 mark_reg_known_zero(env, regs, insn->dst_reg); 16222 16223 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16224 dst_reg->type = aux->btf_var.reg_type; 16225 switch (base_type(dst_reg->type)) { 16226 case PTR_TO_MEM: 16227 dst_reg->mem_size = aux->btf_var.mem_size; 16228 break; 16229 case PTR_TO_BTF_ID: 16230 dst_reg->btf = aux->btf_var.btf; 16231 dst_reg->btf_id = aux->btf_var.btf_id; 16232 break; 16233 default: 16234 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 16235 return -EFAULT; 16236 } 16237 return 0; 16238 } 16239 16240 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16241 struct bpf_prog_aux *aux = env->prog->aux; 16242 u32 subprogno = bpf_find_subprog(env, 16243 env->insn_idx + insn->imm + 1); 16244 16245 if (!aux->func_info) { 16246 verbose(env, "missing btf func_info\n"); 16247 return -EINVAL; 16248 } 16249 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16250 verbose(env, "callback function not static\n"); 16251 return -EINVAL; 16252 } 16253 16254 dst_reg->type = PTR_TO_FUNC; 16255 dst_reg->subprogno = subprogno; 16256 return 0; 16257 } 16258 16259 map = env->used_maps[aux->map_index]; 16260 16261 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16262 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16263 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16264 __mark_reg_unknown(env, dst_reg); 16265 dst_reg->map_ptr = map; 16266 return 0; 16267 } 16268 __mark_reg_known(dst_reg, aux->map_off); 16269 dst_reg->type = PTR_TO_MAP_VALUE; 16270 dst_reg->map_ptr = map; 16271 WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY && 16272 map->max_entries != 1); 16273 /* We want reg->id to be same (0) as map_value is not distinct */ 16274 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16275 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16276 dst_reg->type = CONST_PTR_TO_MAP; 16277 dst_reg->map_ptr = map; 16278 } else { 16279 verifier_bug(env, "unexpected src reg value for ldimm64"); 16280 return -EFAULT; 16281 } 16282 16283 return 0; 16284 } 16285 16286 static bool may_access_skb(enum bpf_prog_type type) 16287 { 16288 switch (type) { 16289 case BPF_PROG_TYPE_SOCKET_FILTER: 16290 case BPF_PROG_TYPE_SCHED_CLS: 16291 case BPF_PROG_TYPE_SCHED_ACT: 16292 return true; 16293 default: 16294 return false; 16295 } 16296 } 16297 16298 /* verify safety of LD_ABS|LD_IND instructions: 16299 * - they can only appear in the programs where ctx == skb 16300 * - since they are wrappers of function calls, they scratch R1-R5 registers, 16301 * preserve R6-R9, and store return value into R0 16302 * 16303 * Implicit input: 16304 * ctx == skb == R6 == CTX 16305 * 16306 * Explicit input: 16307 * SRC == any register 16308 * IMM == 32-bit immediate 16309 * 16310 * Output: 16311 * R0 - 8/16/32-bit skb data converted to cpu endianness 16312 */ 16313 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 16314 { 16315 struct bpf_reg_state *regs = cur_regs(env); 16316 static const int ctx_reg = BPF_REG_6; 16317 u8 mode = BPF_MODE(insn->code); 16318 int i, err; 16319 16320 if (!may_access_skb(resolve_prog_type(env->prog))) { 16321 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 16322 return -EINVAL; 16323 } 16324 16325 if (!env->ops->gen_ld_abs) { 16326 verifier_bug(env, "gen_ld_abs is null"); 16327 return -EFAULT; 16328 } 16329 16330 /* check whether implicit source operand (register R6) is readable */ 16331 err = check_reg_arg(env, ctx_reg, SRC_OP); 16332 if (err) 16333 return err; 16334 16335 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 16336 * gen_ld_abs() may terminate the program at runtime, leading to 16337 * reference leak. 16338 */ 16339 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 16340 if (err) 16341 return err; 16342 16343 if (regs[ctx_reg].type != PTR_TO_CTX) { 16344 verbose(env, 16345 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 16346 return -EINVAL; 16347 } 16348 16349 if (mode == BPF_IND) { 16350 /* check explicit source operand */ 16351 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16352 if (err) 16353 return err; 16354 } 16355 16356 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 16357 if (err < 0) 16358 return err; 16359 16360 /* reset caller saved regs to unreadable */ 16361 for (i = 0; i < CALLER_SAVED_REGS; i++) { 16362 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 16363 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 16364 } 16365 16366 /* mark destination R0 register as readable, since it contains 16367 * the value fetched from the packet. 16368 * Already marked as written above. 16369 */ 16370 mark_reg_unknown(env, regs, BPF_REG_0); 16371 /* 16372 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0 16373 * which must be explored by the verifier when in a subprog. 16374 */ 16375 if (env->cur_state->curframe) { 16376 struct bpf_verifier_state *branch; 16377 16378 mark_reg_scratched(env, BPF_REG_0); 16379 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 16380 if (IS_ERR(branch)) 16381 return PTR_ERR(branch); 16382 mark_reg_known_zero(env, regs, BPF_REG_0); 16383 err = prepare_func_exit(env, &env->insn_idx); 16384 if (err) 16385 return err; 16386 env->insn_idx--; 16387 } 16388 return 0; 16389 } 16390 16391 16392 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range) 16393 { 16394 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16395 16396 /* Default return value range. */ 16397 *range = retval_range(0, 1); 16398 16399 switch (prog_type) { 16400 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 16401 switch (env->prog->expected_attach_type) { 16402 case BPF_CGROUP_UDP4_RECVMSG: 16403 case BPF_CGROUP_UDP6_RECVMSG: 16404 case BPF_CGROUP_UNIX_RECVMSG: 16405 case BPF_CGROUP_INET4_GETPEERNAME: 16406 case BPF_CGROUP_INET6_GETPEERNAME: 16407 case BPF_CGROUP_UNIX_GETPEERNAME: 16408 case BPF_CGROUP_INET4_GETSOCKNAME: 16409 case BPF_CGROUP_INET6_GETSOCKNAME: 16410 case BPF_CGROUP_UNIX_GETSOCKNAME: 16411 *range = retval_range(1, 1); 16412 break; 16413 case BPF_CGROUP_INET4_BIND: 16414 case BPF_CGROUP_INET6_BIND: 16415 *range = retval_range(0, 3); 16416 break; 16417 default: 16418 break; 16419 } 16420 break; 16421 case BPF_PROG_TYPE_CGROUP_SKB: 16422 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) 16423 *range = retval_range(0, 3); 16424 break; 16425 case BPF_PROG_TYPE_CGROUP_SOCK: 16426 case BPF_PROG_TYPE_SOCK_OPS: 16427 case BPF_PROG_TYPE_CGROUP_DEVICE: 16428 case BPF_PROG_TYPE_CGROUP_SYSCTL: 16429 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 16430 break; 16431 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16432 if (!env->prog->aux->attach_btf_id) 16433 return false; 16434 *range = retval_range(0, 0); 16435 break; 16436 case BPF_PROG_TYPE_TRACING: 16437 switch (env->prog->expected_attach_type) { 16438 case BPF_TRACE_FENTRY: 16439 case BPF_TRACE_FEXIT: 16440 case BPF_TRACE_FSESSION: 16441 case BPF_TRACE_FENTRY_MULTI: 16442 case BPF_TRACE_FEXIT_MULTI: 16443 case BPF_TRACE_FSESSION_MULTI: 16444 *range = retval_range(0, 0); 16445 break; 16446 case BPF_TRACE_RAW_TP: 16447 case BPF_MODIFY_RETURN: 16448 return false; 16449 case BPF_TRACE_ITER: 16450 default: 16451 break; 16452 } 16453 break; 16454 case BPF_PROG_TYPE_KPROBE: 16455 switch (env->prog->expected_attach_type) { 16456 case BPF_TRACE_KPROBE_SESSION: 16457 case BPF_TRACE_UPROBE_SESSION: 16458 break; 16459 default: 16460 return false; 16461 } 16462 break; 16463 case BPF_PROG_TYPE_SK_LOOKUP: 16464 *range = retval_range(SK_DROP, SK_PASS); 16465 break; 16466 16467 case BPF_PROG_TYPE_LSM: 16468 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 16469 /* no range found, any return value is allowed */ 16470 if (!get_func_retval_range(env->prog, range)) 16471 return false; 16472 /* no restricted range, any return value is allowed */ 16473 if (range->minval == S32_MIN && range->maxval == S32_MAX) 16474 return false; 16475 range->return_32bit = true; 16476 } else if (!env->prog->aux->attach_func_proto->type) { 16477 /* Make sure programs that attach to void 16478 * hooks don't try to modify return value. 16479 */ 16480 *range = retval_range(1, 1); 16481 } 16482 break; 16483 16484 case BPF_PROG_TYPE_NETFILTER: 16485 *range = retval_range(NF_DROP, NF_ACCEPT); 16486 break; 16487 case BPF_PROG_TYPE_STRUCT_OPS: 16488 *range = retval_range(0, 0); 16489 break; 16490 case BPF_PROG_TYPE_EXT: 16491 /* freplace program can return anything as its return value 16492 * depends on the to-be-replaced kernel func or bpf program. 16493 */ 16494 default: 16495 return false; 16496 } 16497 16498 /* Continue calculating. */ 16499 16500 return true; 16501 } 16502 16503 static bool program_returns_void(struct bpf_verifier_env *env) 16504 { 16505 const struct bpf_prog *prog = env->prog; 16506 enum bpf_prog_type prog_type = prog->type; 16507 16508 switch (prog_type) { 16509 case BPF_PROG_TYPE_LSM: 16510 /* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */ 16511 if (prog->expected_attach_type != BPF_LSM_CGROUP && 16512 !prog->aux->attach_func_proto->type) 16513 return true; 16514 break; 16515 case BPF_PROG_TYPE_STRUCT_OPS: 16516 if (!prog->aux->attach_func_proto->type) 16517 return true; 16518 break; 16519 case BPF_PROG_TYPE_EXT: 16520 /* 16521 * If the actual program is an extension, let it 16522 * return void - attaching will succeed only if the 16523 * program being replaced also returns void, and since 16524 * it has passed verification its actual type doesn't matter. 16525 */ 16526 if (subprog_returns_void(env, 0)) 16527 return true; 16528 break; 16529 default: 16530 break; 16531 } 16532 return false; 16533 } 16534 16535 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 16536 { 16537 const char *exit_ctx = "At program exit"; 16538 struct tnum enforce_attach_type_range = tnum_unknown; 16539 const struct bpf_prog *prog = env->prog; 16540 struct bpf_reg_state *reg = reg_state(env, regno); 16541 struct bpf_retval_range range = retval_range(0, 1); 16542 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16543 struct bpf_func_state *frame = env->cur_state->frame[0]; 16544 const struct btf_type *reg_type, *ret_type = NULL; 16545 int err; 16546 16547 /* LSM and struct_ops func-ptr's return type could be "void" */ 16548 if (!frame->in_async_callback_fn && program_returns_void(env)) 16549 return 0; 16550 16551 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) { 16552 /* Allow a struct_ops program to return a referenced kptr if it 16553 * matches the operator's return type and is in its unmodified 16554 * form. A scalar zero (i.e., a null pointer) is also allowed. 16555 */ 16556 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 16557 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 16558 prog->aux->attach_func_proto->type, 16559 NULL); 16560 if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg)) 16561 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 16562 } 16563 16564 /* eBPF calling convention is such that R0 is used 16565 * to return the value from eBPF program. 16566 * Make sure that it's readable at this time 16567 * of bpf_exit, which means that program wrote 16568 * something into it earlier 16569 */ 16570 err = check_reg_arg(env, regno, SRC_OP); 16571 if (err) 16572 return err; 16573 16574 if (is_pointer_value(env, regno)) { 16575 verbose(env, "R%d leaks addr as return value\n", regno); 16576 return -EACCES; 16577 } 16578 16579 if (frame->in_async_callback_fn) { 16580 exit_ctx = "At async callback return"; 16581 range = frame->callback_ret_range; 16582 goto enforce_retval; 16583 } 16584 16585 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type) 16586 return 0; 16587 16588 if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)) 16589 enforce_attach_type_range = tnum_range(2, 3); 16590 16591 if (!return_retval_range(env, &range)) 16592 return 0; 16593 16594 enforce_retval: 16595 if (reg->type != SCALAR_VALUE) { 16596 verbose(env, "%s the register R%d is not a known value (%s)\n", 16597 exit_ctx, regno, reg_type_str(env, reg->type)); 16598 return -EINVAL; 16599 } 16600 16601 err = mark_chain_precision(env, regno); 16602 if (err) 16603 return err; 16604 16605 if (!retval_range_within(range, reg)) { 16606 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 16607 if (prog->expected_attach_type == BPF_LSM_CGROUP && 16608 prog_type == BPF_PROG_TYPE_LSM && 16609 !prog->aux->attach_func_proto->type) 16610 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 16611 return -EINVAL; 16612 } 16613 16614 if (!tnum_is_unknown(enforce_attach_type_range) && 16615 tnum_in(enforce_attach_type_range, reg->var_off)) 16616 env->prog->enforce_expected_attach_type = 1; 16617 return 0; 16618 } 16619 16620 static int check_global_subprog_return_code(struct bpf_verifier_env *env) 16621 { 16622 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 16623 struct bpf_func_state *cur_frame = cur_func(env); 16624 int err; 16625 16626 if (subprog_returns_void(env, cur_frame->subprogno)) 16627 return 0; 16628 16629 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 16630 if (err) 16631 return err; 16632 16633 /* Pointers to arena are safe to pass between subprograms. */ 16634 if (is_arena_reg(env, BPF_REG_0)) 16635 return 0; 16636 16637 if (is_pointer_value(env, BPF_REG_0)) { 16638 verbose(env, "R%d leaks addr as return value\n", BPF_REG_0); 16639 return -EACCES; 16640 } 16641 16642 if (reg->type != SCALAR_VALUE) { 16643 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 16644 reg_type_str(env, reg->type)); 16645 return -EINVAL; 16646 } 16647 16648 return 0; 16649 } 16650 16651 /* Bitmask with 1s for all caller saved registers */ 16652 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16653 16654 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16655 * replacement patch is presumed to follow bpf_fastcall contract 16656 * (see mark_fastcall_pattern_for_call() below). 16657 */ 16658 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 16659 { 16660 switch (imm) { 16661 #ifdef CONFIG_X86_64 16662 case BPF_FUNC_get_smp_processor_id: 16663 #ifdef CONFIG_SMP 16664 case BPF_FUNC_get_current_task_btf: 16665 case BPF_FUNC_get_current_task: 16666 #endif 16667 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 16668 #endif 16669 default: 16670 return false; 16671 } 16672 } 16673 16674 /* If @call is a kfunc or helper call, fills @cs and returns true, 16675 * otherwise returns false. 16676 */ 16677 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 16678 struct bpf_call_summary *cs) 16679 { 16680 struct bpf_call_arg_meta meta; 16681 const struct bpf_func_proto *fn; 16682 int i; 16683 16684 if (bpf_helper_call(call)) { 16685 if (bpf_get_helper_proto(env, call->imm, &fn) < 0) 16686 /* error would be reported later */ 16687 return false; 16688 cs->fastcall = fn->allow_fastcall && 16689 (bpf_verifier_inlines_helper_call(env, call->imm) || 16690 bpf_jit_inlines_helper_call(call->imm)); 16691 cs->is_void = fn->ret_type == RET_VOID; 16692 cs->num_params = 0; 16693 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 16694 if (fn->arg_type[i] == ARG_DONTCARE) 16695 break; 16696 cs->num_params++; 16697 } 16698 return true; 16699 } 16700 16701 if (bpf_pseudo_kfunc_call(call)) { 16702 int err; 16703 16704 err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta); 16705 if (err < 0) 16706 /* error would be reported later */ 16707 return false; 16708 cs->num_params = btf_type_vlen(meta.func_proto); 16709 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 16710 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 16711 return true; 16712 } 16713 16714 return false; 16715 } 16716 16717 /* LLVM define a bpf_fastcall function attribute. 16718 * This attribute means that function scratches only some of 16719 * the caller saved registers defined by ABI. 16720 * For BPF the set of such registers could be defined as follows: 16721 * - R0 is scratched only if function is non-void; 16722 * - R1-R5 are scratched only if corresponding parameter type is defined 16723 * in the function prototype. 16724 * 16725 * The contract between kernel and clang allows to simultaneously use 16726 * such functions and maintain backwards compatibility with old 16727 * kernels that don't understand bpf_fastcall calls: 16728 * 16729 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 16730 * registers are not scratched by the call; 16731 * 16732 * - as a post-processing step, clang visits each bpf_fastcall call and adds 16733 * spill/fill for every live r0-r5; 16734 * 16735 * - stack offsets used for the spill/fill are allocated as lowest 16736 * stack offsets in whole function and are not used for any other 16737 * purposes; 16738 * 16739 * - when kernel loads a program, it looks for such patterns 16740 * (bpf_fastcall function surrounded by spills/fills) and checks if 16741 * spill/fill stack offsets are used exclusively in fastcall patterns; 16742 * 16743 * - if so, and if verifier or current JIT inlines the call to the 16744 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 16745 * spill/fill pairs; 16746 * 16747 * - when old kernel loads a program, presence of spill/fill pairs 16748 * keeps BPF program valid, albeit slightly less efficient. 16749 * 16750 * For example: 16751 * 16752 * r1 = 1; 16753 * r2 = 2; 16754 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16755 * *(u64 *)(r10 - 16) = r2; r2 = 2; 16756 * call %[to_be_inlined] --> call %[to_be_inlined] 16757 * r2 = *(u64 *)(r10 - 16); r0 = r1; 16758 * r1 = *(u64 *)(r10 - 8); r0 += r2; 16759 * r0 = r1; exit; 16760 * r0 += r2; 16761 * exit; 16762 * 16763 * The purpose of mark_fastcall_pattern_for_call is to: 16764 * - look for such patterns; 16765 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 16766 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 16767 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 16768 * at which bpf_fastcall spill/fill stack slots start; 16769 * - update env->subprog_info[*]->keep_fastcall_stack. 16770 * 16771 * The .fastcall_pattern and .fastcall_stack_off are used by 16772 * check_fastcall_stack_contract() to check if every stack access to 16773 * fastcall spill/fill stack slot originates from spill/fill 16774 * instructions, members of fastcall patterns. 16775 * 16776 * If such condition holds true for a subprogram, fastcall patterns could 16777 * be rewritten by remove_fastcall_spills_fills(). 16778 * Otherwise bpf_fastcall patterns are not changed in the subprogram 16779 * (code, presumably, generated by an older clang version). 16780 * 16781 * For example, it is *not* safe to remove spill/fill below: 16782 * 16783 * r1 = 1; 16784 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16785 * call %[to_be_inlined] --> call %[to_be_inlined] 16786 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 16787 * r0 = *(u64 *)(r10 - 8); r0 += r1; 16788 * r0 += r1; exit; 16789 * exit; 16790 */ 16791 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 16792 struct bpf_subprog_info *subprog, 16793 int insn_idx, s16 lowest_off) 16794 { 16795 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 16796 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 16797 u32 clobbered_regs_mask; 16798 struct bpf_call_summary cs; 16799 u32 expected_regs_mask; 16800 s16 off; 16801 int i; 16802 16803 if (!bpf_get_call_summary(env, call, &cs)) 16804 return; 16805 16806 /* A bitmask specifying which caller saved registers are clobbered 16807 * by a call to a helper/kfunc *as if* this helper/kfunc follows 16808 * bpf_fastcall contract: 16809 * - includes R0 if function is non-void; 16810 * - includes R1-R5 if corresponding parameter has is described 16811 * in the function prototype. 16812 */ 16813 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 16814 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 16815 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 16816 16817 /* match pairs of form: 16818 * 16819 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 16820 * ... 16821 * call %[to_be_inlined] 16822 * ... 16823 * rX = *(u64 *)(r10 - Y) 16824 */ 16825 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 16826 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 16827 break; 16828 stx = &insns[insn_idx - i]; 16829 ldx = &insns[insn_idx + i]; 16830 /* must be a stack spill/fill pair */ 16831 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 16832 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 16833 stx->dst_reg != BPF_REG_10 || 16834 ldx->src_reg != BPF_REG_10) 16835 break; 16836 /* must be a spill/fill for the same reg */ 16837 if (stx->src_reg != ldx->dst_reg) 16838 break; 16839 /* must be one of the previously unseen registers */ 16840 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 16841 break; 16842 /* must be a spill/fill for the same expected offset, 16843 * no need to check offset alignment, BPF_DW stack access 16844 * is always 8-byte aligned. 16845 */ 16846 if (stx->off != off || ldx->off != off) 16847 break; 16848 expected_regs_mask &= ~BIT(stx->src_reg); 16849 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 16850 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 16851 } 16852 if (i == 1) 16853 return; 16854 16855 /* Conditionally set 'fastcall_spills_num' to allow forward 16856 * compatibility when more helper functions are marked as 16857 * bpf_fastcall at compile time than current kernel supports, e.g: 16858 * 16859 * 1: *(u64 *)(r10 - 8) = r1 16860 * 2: call A ;; assume A is bpf_fastcall for current kernel 16861 * 3: r1 = *(u64 *)(r10 - 8) 16862 * 4: *(u64 *)(r10 - 8) = r1 16863 * 5: call B ;; assume B is not bpf_fastcall for current kernel 16864 * 6: r1 = *(u64 *)(r10 - 8) 16865 * 16866 * There is no need to block bpf_fastcall rewrite for such program. 16867 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 16868 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 16869 * does not remove spill/fill pair {4,6}. 16870 */ 16871 if (cs.fastcall) 16872 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 16873 else 16874 subprog->keep_fastcall_stack = 1; 16875 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 16876 } 16877 16878 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 16879 { 16880 struct bpf_subprog_info *subprog = env->subprog_info; 16881 struct bpf_insn *insn; 16882 s16 lowest_off; 16883 int s, i; 16884 16885 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 16886 /* find lowest stack spill offset used in this subprog */ 16887 lowest_off = 0; 16888 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16889 insn = env->prog->insnsi + i; 16890 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 16891 insn->dst_reg != BPF_REG_10) 16892 continue; 16893 lowest_off = min(lowest_off, insn->off); 16894 } 16895 /* use this offset to find fastcall patterns */ 16896 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16897 insn = env->prog->insnsi + i; 16898 if (insn->code != (BPF_JMP | BPF_CALL)) 16899 continue; 16900 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 16901 } 16902 } 16903 return 0; 16904 } 16905 16906 static void adjust_btf_func(struct bpf_verifier_env *env) 16907 { 16908 struct bpf_prog_aux *aux = env->prog->aux; 16909 int i; 16910 16911 if (!aux->func_info) 16912 return; 16913 16914 /* func_info is not available for hidden subprogs */ 16915 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16916 aux->func_info[i].insn_off = env->subprog_info[i].start; 16917 } 16918 16919 /* Find id in idset and increment its count, or add new entry */ 16920 static void idset_cnt_inc(struct bpf_idset *idset, u32 id) 16921 { 16922 u32 i; 16923 16924 for (i = 0; i < idset->num_ids; i++) { 16925 if (idset->entries[i].id == id) { 16926 idset->entries[i].cnt++; 16927 return; 16928 } 16929 } 16930 /* New id */ 16931 if (idset->num_ids < BPF_ID_MAP_SIZE) { 16932 idset->entries[idset->num_ids].id = id; 16933 idset->entries[idset->num_ids].cnt = 1; 16934 idset->num_ids++; 16935 } 16936 } 16937 16938 /* Find id in idset and return its count, or 0 if not found */ 16939 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id) 16940 { 16941 u32 i; 16942 16943 for (i = 0; i < idset->num_ids; i++) { 16944 if (idset->entries[i].id == id) 16945 return idset->entries[i].cnt; 16946 } 16947 return 0; 16948 } 16949 16950 /* 16951 * Clear singular scalar ids in a state. 16952 * A register with a non-zero id is called singular if no other register shares 16953 * the same base id. Such registers can be treated as independent (id=0). 16954 */ 16955 void bpf_clear_singular_ids(struct bpf_verifier_env *env, 16956 struct bpf_verifier_state *st) 16957 { 16958 struct bpf_idset *idset = &env->idset_scratch; 16959 struct bpf_func_state *func; 16960 struct bpf_reg_state *reg; 16961 16962 idset->num_ids = 0; 16963 16964 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16965 if (reg->type != SCALAR_VALUE) 16966 continue; 16967 if (!reg->id) 16968 continue; 16969 idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST); 16970 })); 16971 16972 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16973 if (reg->type != SCALAR_VALUE) 16974 continue; 16975 if (!reg->id) 16976 continue; 16977 if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1) 16978 clear_scalar_id(reg); 16979 })); 16980 } 16981 16982 /* Return true if it's OK to have the same insn return a different type. */ 16983 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16984 { 16985 switch (base_type(type)) { 16986 case PTR_TO_CTX: 16987 case PTR_TO_SOCKET: 16988 case PTR_TO_SOCK_COMMON: 16989 case PTR_TO_TCP_SOCK: 16990 case PTR_TO_XDP_SOCK: 16991 case PTR_TO_BTF_ID: 16992 case PTR_TO_ARENA: 16993 return false; 16994 default: 16995 return true; 16996 } 16997 } 16998 16999 /* If an instruction was previously used with particular pointer types, then we 17000 * need to be careful to avoid cases such as the below, where it may be ok 17001 * for one branch accessing the pointer, but not ok for the other branch: 17002 * 17003 * R1 = sock_ptr 17004 * goto X; 17005 * ... 17006 * R1 = some_other_valid_ptr; 17007 * goto X; 17008 * ... 17009 * R2 = *(u32 *)(R1 + 0); 17010 */ 17011 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17012 { 17013 return src != prev && (!reg_type_mismatch_ok(src) || 17014 !reg_type_mismatch_ok(prev)); 17015 } 17016 17017 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type) 17018 { 17019 switch (base_type(type)) { 17020 case PTR_TO_MEM: 17021 case PTR_TO_BTF_ID: 17022 return true; 17023 default: 17024 return false; 17025 } 17026 } 17027 17028 static bool is_ptr_to_mem(enum bpf_reg_type type) 17029 { 17030 return base_type(type) == PTR_TO_MEM; 17031 } 17032 17033 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17034 bool allow_trust_mismatch) 17035 { 17036 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17037 enum bpf_reg_type merged_type; 17038 17039 if (*prev_type == NOT_INIT) { 17040 /* Saw a valid insn 17041 * dst_reg = *(u32 *)(src_reg + off) 17042 * save type to validate intersecting paths 17043 */ 17044 *prev_type = type; 17045 } else if (reg_type_mismatch(type, *prev_type)) { 17046 /* Abuser program is trying to use the same insn 17047 * dst_reg = *(u32*) (src_reg + off) 17048 * with different pointer types: 17049 * src_reg == ctx in one branch and 17050 * src_reg == stack|map in some other branch. 17051 * Reject it. 17052 */ 17053 if (allow_trust_mismatch && 17054 is_ptr_to_mem_or_btf_id(type) && 17055 is_ptr_to_mem_or_btf_id(*prev_type)) { 17056 /* 17057 * Have to support a use case when one path through 17058 * the program yields TRUSTED pointer while another 17059 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17060 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17061 * Same behavior of MEM_RDONLY flag. 17062 */ 17063 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type)) 17064 merged_type = PTR_TO_MEM; 17065 else 17066 merged_type = PTR_TO_BTF_ID; 17067 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED)) 17068 merged_type |= PTR_UNTRUSTED; 17069 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY)) 17070 merged_type |= MEM_RDONLY; 17071 *prev_type = merged_type; 17072 } else { 17073 verbose(env, "same insn cannot be used with different pointers\n"); 17074 return -EINVAL; 17075 } 17076 } 17077 17078 return 0; 17079 } 17080 17081 enum { 17082 PROCESS_BPF_EXIT = 1, 17083 INSN_IDX_UPDATED = 2, 17084 }; 17085 17086 static int process_bpf_exit_full(struct bpf_verifier_env *env, 17087 bool *do_print_state, 17088 bool exception_exit) 17089 { 17090 struct bpf_func_state *cur_frame = cur_func(env); 17091 17092 /* We must do check_reference_leak here before 17093 * prepare_func_exit to handle the case when 17094 * state->curframe > 0, it may be a callback function, 17095 * for which reference_state must match caller reference 17096 * state when it exits. 17097 */ 17098 int err = check_resource_leak(env, exception_exit, 17099 exception_exit || !env->cur_state->curframe, 17100 exception_exit ? "bpf_throw" : 17101 "BPF_EXIT instruction in main prog"); 17102 if (err) 17103 return err; 17104 17105 /* The side effect of the prepare_func_exit which is 17106 * being skipped is that it frees bpf_func_state. 17107 * Typically, process_bpf_exit will only be hit with 17108 * outermost exit. copy_verifier_state in pop_stack will 17109 * handle freeing of any extra bpf_func_state left over 17110 * from not processing all nested function exits. We 17111 * also skip return code checks as they are not needed 17112 * for exceptional exits. 17113 */ 17114 if (exception_exit) 17115 return PROCESS_BPF_EXIT; 17116 17117 if (env->cur_state->curframe) { 17118 /* exit from nested function */ 17119 err = prepare_func_exit(env, &env->insn_idx); 17120 if (err) 17121 return err; 17122 *do_print_state = true; 17123 return INSN_IDX_UPDATED; 17124 } 17125 17126 /* 17127 * Return from a regular global subprogram differs from return 17128 * from the main program or async/exception callback. 17129 * Main program exit implies return code restrictions 17130 * that depend on program type. 17131 * Exit from exception callback is equivalent to main program exit. 17132 * Exit from async callback implies return code restrictions 17133 * that depend on async scheduling mechanism. 17134 */ 17135 if (cur_frame->subprogno && 17136 !cur_frame->in_async_callback_fn && 17137 !cur_frame->in_exception_callback_fn) 17138 err = check_global_subprog_return_code(env); 17139 else 17140 err = check_return_code(env, BPF_REG_0, "R0"); 17141 if (err) 17142 return err; 17143 return PROCESS_BPF_EXIT; 17144 } 17145 17146 static int indirect_jump_min_max_index(struct bpf_verifier_env *env, 17147 int regno, 17148 struct bpf_map *map, 17149 u32 *pmin_index, u32 *pmax_index) 17150 { 17151 struct bpf_reg_state *reg = reg_state(env, regno); 17152 u64 min_index = reg_umin(reg); 17153 u64 max_index = reg_umax(reg); 17154 const u32 size = 8; 17155 17156 if (min_index > (u64) U32_MAX * size) { 17157 verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg)); 17158 return -ERANGE; 17159 } 17160 if (max_index > (u64) U32_MAX * size) { 17161 verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg)); 17162 return -ERANGE; 17163 } 17164 17165 min_index /= size; 17166 max_index /= size; 17167 17168 if (max_index >= map->max_entries) { 17169 verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n", 17170 regno, min_index, max_index, map->max_entries); 17171 return -EINVAL; 17172 } 17173 17174 *pmin_index = min_index; 17175 *pmax_index = max_index; 17176 return 0; 17177 } 17178 17179 /* gotox *dst_reg */ 17180 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn) 17181 { 17182 struct bpf_verifier_state *other_branch; 17183 struct bpf_reg_state *dst_reg; 17184 struct bpf_map *map; 17185 u32 min_index, max_index; 17186 int err = 0; 17187 int n; 17188 int i; 17189 17190 dst_reg = reg_state(env, insn->dst_reg); 17191 if (dst_reg->type != PTR_TO_INSN) { 17192 verbose(env, "R%d has type %s, expected PTR_TO_INSN\n", 17193 insn->dst_reg, reg_type_str(env, dst_reg->type)); 17194 return -EINVAL; 17195 } 17196 17197 map = dst_reg->map_ptr; 17198 if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg)) 17199 return -EFAULT; 17200 17201 if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env, 17202 "R%d has incorrect map type %d", insn->dst_reg, map->map_type)) 17203 return -EFAULT; 17204 17205 err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index); 17206 if (err) 17207 return err; 17208 17209 /* Ensure that the buffer is large enough */ 17210 if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) { 17211 env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf, 17212 max_index - min_index + 1); 17213 if (!env->gotox_tmp_buf) 17214 return -ENOMEM; 17215 } 17216 17217 n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items); 17218 if (n < 0) 17219 return n; 17220 if (n == 0) { 17221 verbose(env, "register R%d doesn't point to any offset in map id=%d\n", 17222 insn->dst_reg, map->id); 17223 return -EINVAL; 17224 } 17225 17226 for (i = 0; i < n - 1; i++) { 17227 mark_indirect_target(env, env->gotox_tmp_buf->items[i]); 17228 other_branch = push_stack(env, env->gotox_tmp_buf->items[i], 17229 env->insn_idx, env->cur_state->speculative); 17230 if (IS_ERR(other_branch)) 17231 return PTR_ERR(other_branch); 17232 } 17233 env->insn_idx = env->gotox_tmp_buf->items[n-1]; 17234 mark_indirect_target(env, env->insn_idx); 17235 return INSN_IDX_UPDATED; 17236 } 17237 17238 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 17239 { 17240 int err; 17241 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 17242 u8 class = BPF_CLASS(insn->code); 17243 17244 switch (class) { 17245 case BPF_ALU: 17246 case BPF_ALU64: 17247 return check_alu_op(env, insn); 17248 17249 case BPF_LDX: 17250 return check_load_mem(env, insn, false, 17251 BPF_MODE(insn->code) == BPF_MEMSX, 17252 true, "ldx"); 17253 17254 case BPF_STX: 17255 if (BPF_MODE(insn->code) == BPF_ATOMIC) 17256 return check_atomic(env, insn); 17257 return check_store_reg(env, insn, false); 17258 17259 case BPF_ST: { 17260 /* Handle stack arg write (store immediate) */ 17261 if (is_stack_arg_st(insn)) { 17262 struct bpf_verifier_state *vstate = env->cur_state; 17263 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 17264 17265 return check_stack_arg_write(env, state, insn->off, NULL); 17266 } 17267 17268 enum bpf_reg_type dst_reg_type; 17269 17270 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17271 if (err) 17272 return err; 17273 17274 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 17275 17276 err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg, argno_from_reg(insn->dst_reg), 17277 insn->off, BPF_SIZE(insn->code), 17278 BPF_WRITE, -1, false, false); 17279 if (err) 17280 return err; 17281 17282 return save_aux_ptr_type(env, dst_reg_type, false); 17283 } 17284 case BPF_JMP: 17285 case BPF_JMP32: { 17286 u8 opcode = BPF_OP(insn->code); 17287 17288 env->jmps_processed++; 17289 if (opcode == BPF_CALL) { 17290 if (env->cur_state->active_locks) { 17291 if ((insn->src_reg == BPF_REG_0 && 17292 insn->imm != BPF_FUNC_spin_unlock && 17293 insn->imm != BPF_FUNC_kptr_xchg) || 17294 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17295 !kfunc_spin_allowed(env, insn->imm, insn->off))) { 17296 verbose(env, 17297 "function calls are not allowed while holding a lock\n"); 17298 return -EINVAL; 17299 } 17300 } 17301 mark_reg_scratched(env, BPF_REG_0); 17302 if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno])) 17303 cur_func(env)->no_stack_arg_load = true; 17304 if (insn->src_reg == BPF_PSEUDO_CALL) 17305 return check_func_call(env, insn, &env->insn_idx); 17306 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17307 return check_kfunc_call(env, insn, &env->insn_idx); 17308 return check_helper_call(env, insn, &env->insn_idx); 17309 } else if (opcode == BPF_JA) { 17310 if (BPF_SRC(insn->code) == BPF_X) 17311 return check_indirect_jump(env, insn); 17312 17313 if (class == BPF_JMP) 17314 env->insn_idx += insn->off + 1; 17315 else 17316 env->insn_idx += insn->imm + 1; 17317 return INSN_IDX_UPDATED; 17318 } else if (opcode == BPF_EXIT) { 17319 return process_bpf_exit_full(env, do_print_state, false); 17320 } 17321 return check_cond_jmp_op(env, insn, &env->insn_idx); 17322 } 17323 case BPF_LD: { 17324 u8 mode = BPF_MODE(insn->code); 17325 17326 if (mode == BPF_ABS || mode == BPF_IND) 17327 return check_ld_abs(env, insn); 17328 17329 if (mode == BPF_IMM) { 17330 err = check_ld_imm(env, insn); 17331 if (err) 17332 return err; 17333 17334 env->insn_idx++; 17335 sanitize_mark_insn_seen(env); 17336 } 17337 return 0; 17338 } 17339 } 17340 /* all class values are handled above. silence compiler warning */ 17341 return -EFAULT; 17342 } 17343 17344 static int do_check(struct bpf_verifier_env *env) 17345 { 17346 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17347 struct bpf_verifier_state *state = env->cur_state; 17348 struct bpf_insn *insns = env->prog->insnsi; 17349 int insn_cnt = env->prog->len; 17350 bool do_print_state = false; 17351 int prev_insn_idx = -1; 17352 17353 for (;;) { 17354 struct bpf_insn *insn; 17355 struct bpf_insn_aux_data *insn_aux; 17356 int err; 17357 17358 /* reset current history entry on each new instruction */ 17359 env->cur_hist_ent = NULL; 17360 17361 env->prev_insn_idx = prev_insn_idx; 17362 if (env->insn_idx >= insn_cnt) { 17363 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17364 env->insn_idx, insn_cnt); 17365 return -EFAULT; 17366 } 17367 17368 insn = &insns[env->insn_idx]; 17369 insn_aux = &env->insn_aux_data[env->insn_idx]; 17370 17371 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17372 verbose(env, 17373 "BPF program is too large. Processed %d insn\n", 17374 env->insn_processed); 17375 return -E2BIG; 17376 } 17377 17378 state->last_insn_idx = env->prev_insn_idx; 17379 state->insn_idx = env->insn_idx; 17380 17381 if (bpf_is_prune_point(env, env->insn_idx)) { 17382 err = bpf_is_state_visited(env, env->insn_idx); 17383 if (err < 0) 17384 return err; 17385 if (err == 1) { 17386 /* found equivalent state, can prune the search */ 17387 if (env->log.level & BPF_LOG_LEVEL) { 17388 if (do_print_state) 17389 verbose(env, "\nfrom %d to %d%s: safe\n", 17390 env->prev_insn_idx, env->insn_idx, 17391 env->cur_state->speculative ? 17392 " (speculative execution)" : ""); 17393 else 17394 verbose(env, "%d: safe\n", env->insn_idx); 17395 } 17396 goto process_bpf_exit; 17397 } 17398 } 17399 17400 if (bpf_is_jmp_point(env, env->insn_idx)) { 17401 err = bpf_push_jmp_history(env, state, 0, 0, 0, 0); 17402 if (err) 17403 return err; 17404 } 17405 17406 if (signal_pending(current)) 17407 return -EAGAIN; 17408 17409 if (need_resched()) 17410 cond_resched(); 17411 17412 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17413 verbose(env, "\nfrom %d to %d%s:", 17414 env->prev_insn_idx, env->insn_idx, 17415 env->cur_state->speculative ? 17416 " (speculative execution)" : ""); 17417 print_verifier_state(env, state, state->curframe, true); 17418 do_print_state = false; 17419 } 17420 17421 if (env->log.level & BPF_LOG_LEVEL) { 17422 if (verifier_state_scratched(env)) 17423 print_insn_state(env, state, state->curframe); 17424 17425 verbose_linfo(env, env->insn_idx, "; "); 17426 env->prev_log_pos = env->log.end_pos; 17427 verbose(env, "%d: ", env->insn_idx); 17428 bpf_verbose_insn(env, insn); 17429 verbose(env, "\n"); 17430 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17431 env->prev_log_pos = env->log.end_pos; 17432 } 17433 17434 if (bpf_prog_is_offloaded(env->prog->aux)) { 17435 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17436 env->prev_insn_idx); 17437 if (err) 17438 return err; 17439 } 17440 17441 sanitize_mark_insn_seen(env); 17442 prev_insn_idx = env->insn_idx; 17443 17444 /* Sanity check: precomputed constants must match verifier state */ 17445 if (!state->speculative && insn_aux->const_reg_mask) { 17446 struct bpf_reg_state *regs = cur_regs(env); 17447 u16 mask = insn_aux->const_reg_mask; 17448 17449 for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) { 17450 u32 cval = insn_aux->const_reg_vals[r]; 17451 17452 if (!(mask & BIT(r))) 17453 continue; 17454 if (regs[r].type != SCALAR_VALUE) 17455 continue; 17456 if (!tnum_is_const(regs[r].var_off)) 17457 continue; 17458 if (verifier_bug_if((u32)regs[r].var_off.value != cval, 17459 env, "const R%d: %u != %llu", 17460 r, cval, regs[r].var_off.value)) 17461 return -EFAULT; 17462 } 17463 } 17464 17465 /* Reduce verification complexity by stopping speculative path 17466 * verification when a nospec is encountered. 17467 */ 17468 if (state->speculative && insn_aux->nospec) 17469 goto process_bpf_exit; 17470 17471 err = do_check_insn(env, &do_print_state); 17472 if (error_recoverable_with_nospec(err) && state->speculative) { 17473 /* Prevent this speculative path from ever reaching the 17474 * insn that would have been unsafe to execute. 17475 */ 17476 insn_aux->nospec = true; 17477 /* If it was an ADD/SUB insn, potentially remove any 17478 * markings for alu sanitization. 17479 */ 17480 insn_aux->alu_state = 0; 17481 goto process_bpf_exit; 17482 } else if (err < 0) { 17483 return err; 17484 } else if (err == PROCESS_BPF_EXIT) { 17485 goto process_bpf_exit; 17486 } else if (err == INSN_IDX_UPDATED) { 17487 } else if (err == 0) { 17488 env->insn_idx++; 17489 } 17490 17491 if (state->speculative && insn_aux->nospec_result) { 17492 /* If we are on a path that performed a jump-op, this 17493 * may skip a nospec patched-in after the jump. This can 17494 * currently never happen because nospec_result is only 17495 * used for the write-ops 17496 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper 17497 * calls. These must never skip the following insn 17498 * (i.e., bpf_insn_successors()'s opcode_info.can_jump 17499 * is false). Still, add a warning to document this in 17500 * case nospec_result is used elsewhere in the future. 17501 * 17502 * All non-branch instructions have a single 17503 * fall-through edge. For these, nospec_result should 17504 * already work. 17505 */ 17506 if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP || 17507 BPF_CLASS(insn->code) == BPF_JMP32) && 17508 BPF_OP(insn->code) != BPF_CALL, env, 17509 "speculation barrier after jump instruction may not have the desired effect")) 17510 return -EFAULT; 17511 process_bpf_exit: 17512 mark_verifier_state_scratched(env); 17513 err = bpf_update_branch_counts(env, env->cur_state); 17514 if (err) 17515 return err; 17516 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 17517 pop_log); 17518 if (err < 0) { 17519 if (err != -ENOENT) 17520 return err; 17521 break; 17522 } else { 17523 do_print_state = true; 17524 continue; 17525 } 17526 } 17527 } 17528 17529 return 0; 17530 } 17531 17532 static int find_btf_percpu_datasec(struct btf *btf) 17533 { 17534 const struct btf_type *t; 17535 const char *tname; 17536 int i, n; 17537 17538 /* 17539 * Both vmlinux and module each have their own ".data..percpu" 17540 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17541 * types to look at only module's own BTF types. 17542 */ 17543 n = btf_nr_types(btf); 17544 for (i = btf_named_start_id(btf, true); i < n; i++) { 17545 t = btf_type_by_id(btf, i); 17546 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17547 continue; 17548 17549 tname = btf_name_by_offset(btf, t->name_off); 17550 if (!strcmp(tname, ".data..percpu")) 17551 return i; 17552 } 17553 17554 return -ENOENT; 17555 } 17556 17557 /* 17558 * Add btf to the env->used_btfs array. If needed, refcount the 17559 * corresponding kernel module. To simplify caller's logic 17560 * in case of error or if btf was added before the function 17561 * decreases the btf refcount. 17562 */ 17563 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 17564 { 17565 struct btf_mod_pair *btf_mod; 17566 int ret = 0; 17567 int i; 17568 17569 /* check whether we recorded this BTF (and maybe module) already */ 17570 for (i = 0; i < env->used_btf_cnt; i++) 17571 if (env->used_btfs[i].btf == btf) 17572 goto ret_put; 17573 17574 if (env->signature) { 17575 verbose(env, "signed program cannot bind any BTF\n"); 17576 ret = -EACCES; 17577 goto ret_put; 17578 } 17579 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17580 verbose(env, "The total number of btfs per program has reached the limit of %u\n", 17581 MAX_USED_BTFS); 17582 ret = -E2BIG; 17583 goto ret_put; 17584 } 17585 17586 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17587 btf_mod->btf = btf; 17588 btf_mod->module = NULL; 17589 17590 /* if we reference variables from kernel module, bump its refcount */ 17591 if (btf_is_module(btf)) { 17592 btf_mod->module = btf_try_get_module(btf); 17593 if (!btf_mod->module) { 17594 ret = -ENXIO; 17595 goto ret_put; 17596 } 17597 } 17598 17599 env->used_btf_cnt++; 17600 return 0; 17601 17602 ret_put: 17603 /* Either error or this BTF was already added */ 17604 btf_put(btf); 17605 return ret; 17606 } 17607 17608 /* replace pseudo btf_id with kernel symbol address */ 17609 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 17610 struct bpf_insn *insn, 17611 struct bpf_insn_aux_data *aux, 17612 struct btf *btf) 17613 { 17614 const struct btf_var_secinfo *vsi; 17615 const struct btf_type *datasec; 17616 const struct btf_type *t; 17617 const char *sym_name; 17618 bool percpu = false; 17619 u32 type, id = insn->imm; 17620 s32 datasec_id; 17621 u64 addr; 17622 int i; 17623 17624 t = btf_type_by_id(btf, id); 17625 if (!t) { 17626 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17627 return -ENOENT; 17628 } 17629 17630 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17631 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17632 return -EINVAL; 17633 } 17634 17635 sym_name = btf_name_by_offset(btf, t->name_off); 17636 addr = kallsyms_lookup_name(sym_name); 17637 if (!addr) { 17638 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17639 sym_name); 17640 return -ENOENT; 17641 } 17642 insn[0].imm = (u32)addr; 17643 insn[1].imm = addr >> 32; 17644 17645 if (btf_type_is_func(t)) { 17646 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17647 aux->btf_var.mem_size = 0; 17648 return 0; 17649 } 17650 17651 datasec_id = find_btf_percpu_datasec(btf); 17652 if (datasec_id > 0) { 17653 datasec = btf_type_by_id(btf, datasec_id); 17654 for_each_vsi(i, datasec, vsi) { 17655 if (vsi->type == id) { 17656 percpu = true; 17657 break; 17658 } 17659 } 17660 } 17661 17662 type = t->type; 17663 t = btf_type_skip_modifiers(btf, type, NULL); 17664 if (percpu) { 17665 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17666 aux->btf_var.btf = btf; 17667 aux->btf_var.btf_id = type; 17668 } else if (!btf_type_is_struct(t)) { 17669 const struct btf_type *ret; 17670 const char *tname; 17671 u32 tsize; 17672 17673 /* resolve the type size of ksym. */ 17674 ret = btf_resolve_size(btf, t, &tsize); 17675 if (IS_ERR(ret)) { 17676 tname = btf_name_by_offset(btf, t->name_off); 17677 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17678 tname, PTR_ERR(ret)); 17679 return -EINVAL; 17680 } 17681 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17682 aux->btf_var.mem_size = tsize; 17683 } else { 17684 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17685 aux->btf_var.btf = btf; 17686 aux->btf_var.btf_id = type; 17687 } 17688 17689 return 0; 17690 } 17691 17692 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17693 struct bpf_insn *insn, 17694 struct bpf_insn_aux_data *aux) 17695 { 17696 struct btf *btf; 17697 int btf_fd; 17698 int err; 17699 17700 btf_fd = insn[1].imm; 17701 if (btf_fd) { 17702 btf = btf_get_by_fd(btf_fd); 17703 if (IS_ERR(btf)) { 17704 verbose(env, "invalid module BTF object FD specified.\n"); 17705 return -EINVAL; 17706 } 17707 } else { 17708 if (!btf_vmlinux) { 17709 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17710 return -EINVAL; 17711 } 17712 btf_get(btf_vmlinux); 17713 btf = btf_vmlinux; 17714 } 17715 17716 err = __check_pseudo_btf_id(env, insn, aux, btf); 17717 if (err) { 17718 btf_put(btf); 17719 return err; 17720 } 17721 17722 return __add_used_btf(env, btf); 17723 } 17724 17725 static bool is_tracing_prog_type(enum bpf_prog_type type) 17726 { 17727 switch (type) { 17728 case BPF_PROG_TYPE_KPROBE: 17729 case BPF_PROG_TYPE_TRACEPOINT: 17730 case BPF_PROG_TYPE_PERF_EVENT: 17731 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17732 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17733 return true; 17734 default: 17735 return false; 17736 } 17737 } 17738 17739 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17740 { 17741 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17742 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17743 } 17744 17745 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17746 struct bpf_map *map, 17747 struct bpf_prog *prog) 17748 17749 { 17750 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17751 17752 if (map->excl_prog_sha && 17753 memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) { 17754 verbose(env, "program's hash doesn't match map's excl_prog_hash\n"); 17755 return -EACCES; 17756 } 17757 17758 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17759 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17760 if (is_tracing_prog_type(prog_type)) { 17761 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17762 return -EINVAL; 17763 } 17764 } 17765 17766 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 17767 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17768 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17769 return -EINVAL; 17770 } 17771 } 17772 17773 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 17774 if (is_tracing_prog_type(prog_type)) { 17775 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17776 return -EINVAL; 17777 } 17778 } 17779 17780 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17781 !bpf_offload_prog_map_match(prog, map)) { 17782 verbose(env, "offload device mismatch between prog and map\n"); 17783 return -EINVAL; 17784 } 17785 17786 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17787 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17788 return -EINVAL; 17789 } 17790 17791 if (prog->sleepable) 17792 switch (map->map_type) { 17793 case BPF_MAP_TYPE_HASH: 17794 case BPF_MAP_TYPE_RHASH: 17795 case BPF_MAP_TYPE_LRU_HASH: 17796 case BPF_MAP_TYPE_ARRAY: 17797 case BPF_MAP_TYPE_PERCPU_HASH: 17798 case BPF_MAP_TYPE_PERCPU_ARRAY: 17799 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17800 case BPF_MAP_TYPE_LPM_TRIE: 17801 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17802 case BPF_MAP_TYPE_HASH_OF_MAPS: 17803 case BPF_MAP_TYPE_RINGBUF: 17804 case BPF_MAP_TYPE_USER_RINGBUF: 17805 case BPF_MAP_TYPE_INODE_STORAGE: 17806 case BPF_MAP_TYPE_SK_STORAGE: 17807 case BPF_MAP_TYPE_TASK_STORAGE: 17808 case BPF_MAP_TYPE_CGRP_STORAGE: 17809 case BPF_MAP_TYPE_QUEUE: 17810 case BPF_MAP_TYPE_STACK: 17811 case BPF_MAP_TYPE_ARENA: 17812 case BPF_MAP_TYPE_INSN_ARRAY: 17813 case BPF_MAP_TYPE_PROG_ARRAY: 17814 break; 17815 default: 17816 verbose(env, 17817 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17818 return -EINVAL; 17819 } 17820 17821 if (bpf_map_is_cgroup_storage(map) && 17822 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17823 verbose(env, "only one cgroup storage of each type is allowed\n"); 17824 return -EBUSY; 17825 } 17826 17827 if (map->map_type == BPF_MAP_TYPE_ARENA) { 17828 if (env->prog->aux->arena) { 17829 verbose(env, "Only one arena per program\n"); 17830 return -EBUSY; 17831 } 17832 if (!env->allow_ptr_leaks || !env->bpf_capable) { 17833 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 17834 return -EPERM; 17835 } 17836 if (!env->prog->jit_requested) { 17837 verbose(env, "JIT is required to use arena\n"); 17838 return -EOPNOTSUPP; 17839 } 17840 if (!bpf_jit_supports_arena()) { 17841 verbose(env, "JIT doesn't support arena\n"); 17842 return -EOPNOTSUPP; 17843 } 17844 env->prog->aux->arena = (void *)map; 17845 env->prog->jit_required = true; 17846 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 17847 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 17848 return -EINVAL; 17849 } 17850 } 17851 17852 return 0; 17853 } 17854 17855 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 17856 { 17857 int i, err; 17858 17859 /* check whether we recorded this map already */ 17860 for (i = 0; i < env->used_map_cnt; i++) 17861 if (env->used_maps[i] == map) 17862 return i; 17863 17864 if (env->signature && 17865 env->prog->aux->sig.verdict == BPF_SIG_VERIFIED) { 17866 verbose(env, "signed program cannot bind map '%s' not covered by the signature\n", 17867 map->name); 17868 return -EACCES; 17869 } 17870 if (env->used_map_cnt >= MAX_USED_MAPS) { 17871 verbose(env, "The total number of maps per program has reached the limit of %u\n", 17872 MAX_USED_MAPS); 17873 return -E2BIG; 17874 } 17875 17876 err = check_map_prog_compatibility(env, map, env->prog); 17877 if (err) 17878 return err; 17879 17880 if (env->prog->sleepable) 17881 atomic64_inc(&map->sleepable_refcnt); 17882 17883 /* hold the map. If the program is rejected by verifier, 17884 * the map will be released by release_maps() or it 17885 * will be used by the valid program until it's unloaded 17886 * and all maps are released in bpf_free_used_maps() 17887 */ 17888 bpf_map_inc(map); 17889 17890 env->used_maps[env->used_map_cnt++] = map; 17891 17892 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 17893 err = bpf_insn_array_init(map, env->prog); 17894 if (err) { 17895 verbose(env, "Failed to properly initialize insn array\n"); 17896 return err; 17897 } 17898 env->insn_array_maps[env->insn_array_map_cnt++] = map; 17899 env->prog->jit_required = true; 17900 } 17901 17902 return env->used_map_cnt - 1; 17903 } 17904 17905 /* Add map behind fd to used maps list, if it's not already there, and return 17906 * its index. 17907 * Returns <0 on error, or >= 0 index, on success. 17908 */ 17909 static int add_used_map(struct bpf_verifier_env *env, int fd) 17910 { 17911 struct bpf_map *map; 17912 CLASS(fd, f)(fd); 17913 17914 map = __bpf_map_get(f); 17915 if (IS_ERR(map)) { 17916 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 17917 return PTR_ERR(map); 17918 } 17919 17920 return __add_used_map(env, map); 17921 } 17922 17923 static int fd_array_get_map_idx_continuous(struct bpf_verifier_env *env, u32 idx) 17924 { 17925 struct bpf_map *map; 17926 17927 if (idx >= env->fd_array_cnt) { 17928 verbose(env, "fd_idx %u out of bounds, fd_array_cnt %u\n", 17929 idx, env->fd_array_cnt); 17930 return -EINVAL; 17931 } 17932 map = fd_slot_map(env->fd_array[idx]); 17933 if (!map) { 17934 verbose(env, "fd_idx %u is not a map\n", idx); 17935 return -EINVAL; 17936 } 17937 return __add_used_map(env, map); 17938 } 17939 17940 static int fd_array_get_map_idx_sparse(struct bpf_verifier_env *env, u32 idx) 17941 { 17942 int fd; 17943 17944 if (copy_from_bpfptr_offset(&fd, env->fd_array_raw, 17945 (size_t)idx * sizeof(fd), sizeof(fd))) 17946 return -EFAULT; 17947 return add_used_map(env, fd); 17948 } 17949 17950 static int fd_array_get_map_idx(struct bpf_verifier_env *env, u32 idx) 17951 { 17952 if (env->fd_array) 17953 return fd_array_get_map_idx_continuous(env, idx); 17954 if (env->signature) { 17955 verbose(env, "signed program must bind maps via a continuous fd_array (fd_array_cnt)\n"); 17956 return -EACCES; 17957 } 17958 if (!bpfptr_is_null(env->fd_array_raw)) 17959 return fd_array_get_map_idx_sparse(env, idx); 17960 17961 verbose(env, "fd_idx without fd_array is invalid\n"); 17962 return -EPROTO; 17963 } 17964 17965 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17966 { 17967 u8 class = BPF_CLASS(insn->code); 17968 u8 opcode = BPF_OP(insn->code); 17969 17970 switch (opcode) { 17971 case BPF_NEG: 17972 if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 || 17973 insn->off != 0 || insn->imm != 0) { 17974 verbose(env, "BPF_NEG uses reserved fields\n"); 17975 return -EINVAL; 17976 } 17977 return 0; 17978 case BPF_END: 17979 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 17980 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 17981 (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) { 17982 verbose(env, "BPF_END uses reserved fields\n"); 17983 return -EINVAL; 17984 } 17985 return 0; 17986 case BPF_MOV: 17987 if (BPF_SRC(insn->code) == BPF_X) { 17988 if (class == BPF_ALU) { 17989 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 17990 insn->imm) { 17991 verbose(env, "BPF_MOV uses reserved fields\n"); 17992 return -EINVAL; 17993 } 17994 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 17995 if (insn->imm != 1 && insn->imm != 1u << 16) { 17996 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 17997 return -EINVAL; 17998 } 17999 } else if ((insn->off != 0 && insn->off != 8 && 18000 insn->off != 16 && insn->off != 32) || insn->imm) { 18001 verbose(env, "BPF_MOV uses reserved fields\n"); 18002 return -EINVAL; 18003 } 18004 } else if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 18005 verbose(env, "BPF_MOV uses reserved fields\n"); 18006 return -EINVAL; 18007 } 18008 return 0; 18009 case BPF_ADD: 18010 case BPF_SUB: 18011 case BPF_AND: 18012 case BPF_OR: 18013 case BPF_XOR: 18014 case BPF_LSH: 18015 case BPF_RSH: 18016 case BPF_ARSH: 18017 case BPF_MUL: 18018 case BPF_DIV: 18019 case BPF_MOD: 18020 if (BPF_SRC(insn->code) == BPF_X) { 18021 if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) || 18022 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 18023 verbose(env, "BPF_ALU uses reserved fields\n"); 18024 return -EINVAL; 18025 } 18026 } else if (insn->src_reg != BPF_REG_0 || 18027 (insn->off != 0 && insn->off != 1) || 18028 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 18029 verbose(env, "BPF_ALU uses reserved fields\n"); 18030 return -EINVAL; 18031 } 18032 return 0; 18033 default: 18034 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 18035 return -EINVAL; 18036 } 18037 } 18038 18039 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 18040 { 18041 u8 class = BPF_CLASS(insn->code); 18042 u8 opcode = BPF_OP(insn->code); 18043 18044 switch (opcode) { 18045 case BPF_CALL: 18046 if (BPF_SRC(insn->code) != BPF_K || 18047 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) || 18048 (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL && 18049 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 18050 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 18051 verbose(env, "BPF_CALL uses reserved fields\n"); 18052 return -EINVAL; 18053 } 18054 return 0; 18055 case BPF_JA: 18056 if (BPF_SRC(insn->code) == BPF_X) { 18057 if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) { 18058 verbose(env, "BPF_JA|BPF_X uses reserved fields\n"); 18059 return -EINVAL; 18060 } 18061 } else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 18062 (class == BPF_JMP && insn->imm != 0) || 18063 (class == BPF_JMP32 && insn->off != 0)) { 18064 verbose(env, "BPF_JA uses reserved fields\n"); 18065 return -EINVAL; 18066 } 18067 return 0; 18068 case BPF_EXIT: 18069 if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || 18070 insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 18071 class == BPF_JMP32) { 18072 verbose(env, "BPF_EXIT uses reserved fields\n"); 18073 return -EINVAL; 18074 } 18075 return 0; 18076 case BPF_JCOND: 18077 if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO || 18078 insn->dst_reg || insn->imm) { 18079 verbose(env, "invalid may_goto imm %d\n", insn->imm); 18080 return -EINVAL; 18081 } 18082 return 0; 18083 default: 18084 if (BPF_SRC(insn->code) == BPF_X) { 18085 if (insn->imm != 0) { 18086 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18087 return -EINVAL; 18088 } 18089 } else if (insn->src_reg != BPF_REG_0) { 18090 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18091 return -EINVAL; 18092 } 18093 return 0; 18094 } 18095 } 18096 18097 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 18098 { 18099 switch (BPF_CLASS(insn->code)) { 18100 case BPF_ALU: 18101 case BPF_ALU64: 18102 return check_alu_fields(env, insn); 18103 case BPF_LDX: 18104 if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18105 insn->imm != 0) { 18106 verbose(env, "BPF_LDX uses reserved fields\n"); 18107 return -EINVAL; 18108 } 18109 return 0; 18110 case BPF_STX: 18111 if (BPF_MODE(insn->code) == BPF_ATOMIC) 18112 return 0; 18113 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 18114 verbose(env, "BPF_STX uses reserved fields\n"); 18115 return -EINVAL; 18116 } 18117 return 0; 18118 case BPF_ST: 18119 if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { 18120 verbose(env, "BPF_ST uses reserved fields\n"); 18121 return -EINVAL; 18122 } 18123 return 0; 18124 case BPF_JMP: 18125 case BPF_JMP32: 18126 return check_jmp_fields(env, insn); 18127 case BPF_LD: { 18128 u8 mode = BPF_MODE(insn->code); 18129 18130 if (mode == BPF_ABS || mode == BPF_IND) { 18131 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 18132 BPF_SIZE(insn->code) == BPF_DW || 18133 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 18134 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 18135 return -EINVAL; 18136 } 18137 } else if (mode != BPF_IMM) { 18138 verbose(env, "invalid BPF_LD mode\n"); 18139 return -EINVAL; 18140 } 18141 return 0; 18142 } 18143 default: 18144 verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code)); 18145 return -EINVAL; 18146 } 18147 } 18148 18149 /* 18150 * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions: 18151 * 18152 * 1. if it accesses map FD, replace it with actual map pointer. 18153 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18154 * 18155 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18156 */ 18157 static int check_and_resolve_insns(struct bpf_verifier_env *env) 18158 { 18159 struct bpf_insn *insn = env->prog->insnsi; 18160 int insn_cnt = env->prog->len; 18161 int i, err; 18162 18163 err = bpf_prog_calc_tag(env->prog); 18164 if (err) 18165 return err; 18166 18167 for (i = 0; i < insn_cnt; i++, insn++) { 18168 if (insn->dst_reg >= MAX_BPF_REG && 18169 !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) { 18170 verbose(env, "R%d is invalid\n", insn->dst_reg); 18171 return -EINVAL; 18172 } 18173 if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) { 18174 verbose(env, "R%d is invalid\n", insn->src_reg); 18175 return -EINVAL; 18176 } 18177 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18178 struct bpf_insn_aux_data *aux; 18179 struct bpf_map *map; 18180 int map_idx; 18181 u64 addr; 18182 18183 if (i == insn_cnt - 1 || insn[1].code != 0 || 18184 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18185 insn[1].off != 0) { 18186 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18187 return -EINVAL; 18188 } 18189 18190 if (insn[0].off != 0) { 18191 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 18192 return -EINVAL; 18193 } 18194 18195 if (insn[0].src_reg == 0) 18196 /* valid generic load 64-bit imm */ 18197 goto next_insn; 18198 18199 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18200 aux = &env->insn_aux_data[i]; 18201 err = check_pseudo_btf_id(env, insn, aux); 18202 if (err) 18203 return err; 18204 goto next_insn; 18205 } 18206 18207 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18208 aux = &env->insn_aux_data[i]; 18209 aux->ptr_type = PTR_TO_FUNC; 18210 goto next_insn; 18211 } 18212 18213 /* In final convert_pseudo_ld_imm64() step, this is 18214 * converted into regular 64-bit imm load insn. 18215 */ 18216 switch (insn[0].src_reg) { 18217 case BPF_PSEUDO_MAP_VALUE: 18218 case BPF_PSEUDO_MAP_IDX_VALUE: 18219 break; 18220 case BPF_PSEUDO_MAP_FD: 18221 case BPF_PSEUDO_MAP_IDX: 18222 if (insn[1].imm == 0) 18223 break; 18224 fallthrough; 18225 default: 18226 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18227 return -EINVAL; 18228 } 18229 18230 switch (insn[0].src_reg) { 18231 case BPF_PSEUDO_MAP_IDX_VALUE: 18232 case BPF_PSEUDO_MAP_IDX: 18233 map_idx = fd_array_get_map_idx(env, insn[0].imm); 18234 break; 18235 default: 18236 if (env->signature) { 18237 verbose(env, "signed program cannot reference a map by fd, only via fd_array index\n"); 18238 return -EINVAL; 18239 } 18240 map_idx = add_used_map(env, insn[0].imm); 18241 break; 18242 } 18243 18244 if (map_idx < 0) 18245 return map_idx; 18246 map = env->used_maps[map_idx]; 18247 18248 aux = &env->insn_aux_data[i]; 18249 aux->map_index = map_idx; 18250 18251 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18252 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18253 addr = (unsigned long)map; 18254 } else { 18255 u32 off = insn[1].imm; 18256 18257 if (!map->ops->map_direct_value_addr) { 18258 verbose(env, "no direct value access support for this map type\n"); 18259 return -EINVAL; 18260 } 18261 18262 err = map->ops->map_direct_value_addr(map, &addr, off); 18263 if (err) { 18264 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18265 map->value_size, off); 18266 return err; 18267 } 18268 18269 aux->map_off = off; 18270 addr += off; 18271 } 18272 18273 insn[0].imm = (u32)addr; 18274 insn[1].imm = addr >> 32; 18275 18276 next_insn: 18277 insn++; 18278 i++; 18279 continue; 18280 } 18281 18282 /* Basic sanity check before we invest more work here. */ 18283 if (!bpf_opcode_in_insntable(insn->code)) { 18284 verbose(env, "unknown opcode %02x\n", insn->code); 18285 return -EINVAL; 18286 } 18287 18288 err = check_insn_fields(env, insn); 18289 if (err) 18290 return err; 18291 } 18292 18293 /* now all pseudo BPF_LD_IMM64 instructions load valid 18294 * 'struct bpf_map *' into a register instead of user map_fd. 18295 * These pointers will be used later by verifier to validate map access. 18296 */ 18297 return 0; 18298 } 18299 18300 /* drop refcnt of maps used by the rejected program */ 18301 static void release_maps(struct bpf_verifier_env *env) 18302 { 18303 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18304 env->used_map_cnt); 18305 } 18306 18307 /* drop refcnt of maps used by the rejected program */ 18308 static void release_btfs(struct bpf_verifier_env *env) 18309 { 18310 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 18311 } 18312 18313 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18314 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18315 { 18316 struct bpf_insn *insn = env->prog->insnsi; 18317 int insn_cnt = env->prog->len; 18318 int i; 18319 18320 for (i = 0; i < insn_cnt; i++, insn++) { 18321 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18322 continue; 18323 if (insn->src_reg == BPF_PSEUDO_FUNC) 18324 continue; 18325 insn->src_reg = 0; 18326 } 18327 } 18328 18329 static void release_insn_arrays(struct bpf_verifier_env *env) 18330 { 18331 int i; 18332 18333 for (i = 0; i < env->insn_array_map_cnt; i++) 18334 bpf_insn_array_release(env->insn_array_maps[i]); 18335 } 18336 18337 18338 18339 /* The verifier does more data flow analysis than llvm and will not 18340 * explore branches that are dead at run time. Malicious programs can 18341 * have dead code too. Therefore replace all dead at-run-time code 18342 * with 'ja -1'. 18343 * 18344 * Just nops are not optimal, e.g. if they would sit at the end of the 18345 * program and through another bug we would manage to jump there, then 18346 * we'd execute beyond program memory otherwise. Returning exception 18347 * code also wouldn't work since we can have subprogs where the dead 18348 * code could be located. 18349 */ 18350 static void sanitize_dead_code(struct bpf_verifier_env *env) 18351 { 18352 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18353 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18354 struct bpf_insn *insn = env->prog->insnsi; 18355 const int insn_cnt = env->prog->len; 18356 int i; 18357 18358 for (i = 0; i < insn_cnt; i++) { 18359 if (aux_data[i].seen) 18360 continue; 18361 memcpy(insn + i, &trap, sizeof(trap)); 18362 aux_data[i].zext_dst = false; 18363 } 18364 } 18365 18366 18367 18368 static void free_states(struct bpf_verifier_env *env) 18369 { 18370 struct bpf_verifier_state_list *sl; 18371 struct list_head *head, *pos, *tmp; 18372 struct bpf_scc_info *info; 18373 int i, j; 18374 18375 bpf_free_verifier_state(env->cur_state, true); 18376 env->cur_state = NULL; 18377 while (!pop_stack(env, NULL, NULL, false)); 18378 18379 list_for_each_safe(pos, tmp, &env->free_list) { 18380 sl = container_of(pos, struct bpf_verifier_state_list, node); 18381 bpf_free_verifier_state(&sl->state, false); 18382 kfree(sl); 18383 } 18384 INIT_LIST_HEAD(&env->free_list); 18385 18386 for (i = 0; i < env->scc_cnt; ++i) { 18387 info = env->scc_info[i]; 18388 if (!info) 18389 continue; 18390 for (j = 0; j < info->num_visits; j++) 18391 bpf_free_backedges(&info->visits[j]); 18392 kvfree(info); 18393 env->scc_info[i] = NULL; 18394 } 18395 18396 if (!env->explored_states) 18397 return; 18398 18399 for (i = 0; i < state_htab_size(env); i++) { 18400 head = &env->explored_states[i]; 18401 18402 list_for_each_safe(pos, tmp, head) { 18403 sl = container_of(pos, struct bpf_verifier_state_list, node); 18404 bpf_free_verifier_state(&sl->state, false); 18405 kfree(sl); 18406 } 18407 INIT_LIST_HEAD(&env->explored_states[i]); 18408 } 18409 } 18410 18411 static int do_check_common(struct bpf_verifier_env *env, int subprog) 18412 { 18413 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18414 struct bpf_subprog_info *sub = subprog_info(env, subprog); 18415 struct bpf_prog_aux *aux = env->prog->aux; 18416 struct bpf_verifier_state *state; 18417 struct bpf_reg_state *regs; 18418 int ret, i; 18419 18420 env->prev_linfo = NULL; 18421 env->pass_cnt++; 18422 18423 state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT); 18424 if (!state) 18425 return -ENOMEM; 18426 state->curframe = 0; 18427 state->speculative = false; 18428 state->branches = 1; 18429 state->in_sleepable = env->prog->sleepable; 18430 state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT); 18431 if (!state->frame[0]) { 18432 kfree(state); 18433 return -ENOMEM; 18434 } 18435 env->cur_state = state; 18436 init_func_state(env, state->frame[0], 18437 BPF_MAIN_FUNC /* callsite */, 18438 0 /* frameno */, 18439 subprog); 18440 state->first_insn_idx = env->subprog_info[subprog].start; 18441 state->last_insn_idx = -1; 18442 18443 regs = state->frame[state->curframe]->regs; 18444 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 18445 const char *sub_name = subprog_name(env, subprog); 18446 struct bpf_subprog_arg_info *arg; 18447 struct bpf_reg_state *reg; 18448 18449 if (env->log.level & BPF_LOG_LEVEL) 18450 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 18451 ret = btf_prepare_func_args(env, subprog); 18452 if (ret) 18453 goto out; 18454 18455 if (subprog_is_exc_cb(env, subprog)) { 18456 state->frame[0]->in_exception_callback_fn = true; 18457 18458 /* 18459 * Global functions are scalar or void, make sure 18460 * we return a scalar. 18461 */ 18462 if (subprog_returns_void(env, subprog)) { 18463 verbose(env, "exception cb cannot return void\n"); 18464 ret = -EINVAL; 18465 goto out; 18466 } 18467 18468 /* Also ensure the callback only has a single scalar argument. */ 18469 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 18470 verbose(env, "exception cb only supports single integer argument\n"); 18471 ret = -EINVAL; 18472 goto out; 18473 } 18474 } 18475 for (i = BPF_REG_1; i <= min_t(u32, sub->arg_cnt, MAX_BPF_FUNC_REG_ARGS); i++) { 18476 arg = &sub->args[i - BPF_REG_1]; 18477 reg = ®s[i]; 18478 18479 if (arg->arg_type == ARG_PTR_TO_CTX) { 18480 reg->type = PTR_TO_CTX; 18481 mark_reg_known_zero(env, regs, i); 18482 } else if (arg->arg_type == ARG_ANYTHING) { 18483 reg->type = SCALAR_VALUE; 18484 mark_reg_unknown(env, regs, i); 18485 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 18486 /* assume unspecial LOCAL dynptr type */ 18487 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen, 0); 18488 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 18489 reg->type = PTR_TO_MEM; 18490 reg->type |= arg->arg_type & 18491 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 18492 mark_reg_known_zero(env, regs, i); 18493 reg->mem_size = arg->mem_size; 18494 if (arg->arg_type & PTR_MAYBE_NULL) 18495 reg->id = ++env->id_gen; 18496 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 18497 reg->type = PTR_TO_BTF_ID; 18498 if (arg->arg_type & PTR_MAYBE_NULL) 18499 reg->type |= PTR_MAYBE_NULL; 18500 if (arg->arg_type & PTR_UNTRUSTED) 18501 reg->type |= PTR_UNTRUSTED; 18502 if (arg->arg_type & PTR_TRUSTED) 18503 reg->type |= PTR_TRUSTED; 18504 mark_reg_known_zero(env, regs, i); 18505 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 18506 reg->btf_id = arg->btf_id; 18507 reg->id = ++env->id_gen; 18508 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 18509 /* caller can pass either PTR_TO_ARENA or SCALAR */ 18510 mark_reg_unknown(env, regs, i); 18511 } else { 18512 verifier_bug(env, "unhandled arg#%d type %d", 18513 i - BPF_REG_1 + 1, arg->arg_type); 18514 ret = -EFAULT; 18515 goto out; 18516 } 18517 } 18518 if (env->prog->type == BPF_PROG_TYPE_EXT && sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS) { 18519 verbose(env, "freplace programs with >%d args not supported yet\n", 18520 MAX_BPF_FUNC_REG_ARGS); 18521 ret = -EINVAL; 18522 goto out; 18523 } 18524 } else { 18525 /* if main BPF program has associated BTF info, validate that 18526 * it's matching expected signature, and otherwise mark BTF 18527 * info for main program as unreliable 18528 */ 18529 if (env->prog->aux->func_info_aux) { 18530 ret = btf_prepare_func_args(env, 0); 18531 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) { 18532 env->prog->aux->func_info_aux[0].unreliable = true; 18533 sub->arg_cnt = 1; 18534 sub->stack_arg_cnt = 0; 18535 } 18536 } 18537 18538 /* 1st arg to a function */ 18539 regs[BPF_REG_1].type = PTR_TO_CTX; 18540 mark_reg_known_zero(env, regs, BPF_REG_1); 18541 } 18542 18543 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 18544 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 18545 for (i = 0; i < aux->ctx_arg_info_size; i++) { 18546 ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0; 18547 if (ret < 0) 18548 goto out; 18549 18550 aux->ctx_arg_info[i].ref_id = ret; 18551 } 18552 } 18553 18554 ret = do_check(env); 18555 out: 18556 if (!ret && pop_log) 18557 bpf_vlog_reset(&env->log, 0); 18558 free_states(env); 18559 return ret; 18560 } 18561 18562 /* Lazily verify all global functions based on their BTF, if they are called 18563 * from main BPF program or any of subprograms transitively. 18564 * BPF global subprogs called from dead code are not validated. 18565 * All callable global functions must pass verification. 18566 * Otherwise the whole program is rejected. 18567 * Consider: 18568 * int bar(int); 18569 * int foo(int f) 18570 * { 18571 * return bar(f); 18572 * } 18573 * int bar(int b) 18574 * { 18575 * ... 18576 * } 18577 * foo() will be verified first for R1=any_scalar_value. During verification it 18578 * will be assumed that bar() already verified successfully and call to bar() 18579 * from foo() will be checked for type match only. Later bar() will be verified 18580 * independently to check that it's safe for R1=any_scalar_value. 18581 */ 18582 static int do_check_subprogs(struct bpf_verifier_env *env) 18583 { 18584 struct bpf_prog_aux *aux = env->prog->aux; 18585 struct bpf_func_info_aux *sub_aux; 18586 int i, ret, new_cnt; 18587 u32 insn_processed; 18588 18589 if (!aux->func_info) 18590 return 0; 18591 18592 /* exception callback is presumed to be always called */ 18593 if (env->exception_callback_subprog) 18594 subprog_aux(env, env->exception_callback_subprog)->called = true; 18595 18596 again: 18597 new_cnt = 0; 18598 for (i = 1; i < env->subprog_cnt; i++) { 18599 if (!bpf_subprog_is_global(env, i)) 18600 continue; 18601 18602 insn_processed = env->insn_processed; 18603 18604 sub_aux = subprog_aux(env, i); 18605 if (!sub_aux->called || sub_aux->verified) 18606 continue; 18607 18608 env->insn_idx = env->subprog_info[i].start; 18609 WARN_ON_ONCE(env->insn_idx == 0); 18610 ret = do_check_common(env, i); 18611 env->subprog_info[i].insn_processed = env->insn_processed - insn_processed; 18612 if (ret) { 18613 return ret; 18614 } else if (env->log.level & BPF_LOG_LEVEL) { 18615 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 18616 i, subprog_name(env, i)); 18617 } 18618 18619 /* We verified new global subprog, it might have called some 18620 * more global subprogs that we haven't verified yet, so we 18621 * need to do another pass over subprogs to verify those. 18622 */ 18623 sub_aux->verified = true; 18624 new_cnt++; 18625 } 18626 18627 /* We can't loop forever as we verify at least one global subprog on 18628 * each pass. 18629 */ 18630 if (new_cnt) 18631 goto again; 18632 18633 return 0; 18634 } 18635 18636 static int do_check_main(struct bpf_verifier_env *env) 18637 { 18638 u32 insn_processed = env->insn_processed; 18639 int ret; 18640 18641 env->insn_idx = 0; 18642 ret = do_check_common(env, 0); 18643 env->subprog_info[0].insn_processed = env->insn_processed - insn_processed; 18644 if (!ret) 18645 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18646 return ret; 18647 } 18648 18649 18650 static void print_verification_stats(struct bpf_verifier_env *env) 18651 { 18652 /* Skip over hidden subprogs which are not verified. */ 18653 int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18654 18655 if (env->log.level & BPF_LOG_STATS) { 18656 verbose(env, "verification time %lld usec\n", 18657 div_u64(env->verification_time, 1000)); 18658 verbose(env, "stack depth %d", env->subprog_info[0].stack_depth); 18659 for (i = 1; i < subprog_cnt; i++) 18660 verbose(env, "+%d", env->subprog_info[i].stack_depth); 18661 verbose(env, " max %d\n", env->max_stack_depth); 18662 verbose(env, "insns processed %d", env->subprog_info[0].insn_processed); 18663 for (i = 1; i < subprog_cnt; i++) 18664 if (bpf_subprog_is_global(env, i)) 18665 verbose(env, "+%d", env->subprog_info[i].insn_processed); 18666 verbose(env, "\n"); 18667 } 18668 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 18669 "total_states %d peak_states %d mark_read %d\n", 18670 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 18671 env->max_states_per_insn, env->total_states, 18672 env->peak_states, env->longest_mark_read_walk); 18673 } 18674 18675 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 18676 const struct bpf_ctx_arg_aux *info, u32 cnt) 18677 { 18678 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 18679 prog->aux->ctx_arg_info_size = cnt; 18680 18681 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 18682 } 18683 18684 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 18685 { 18686 const struct btf_type *t, *func_proto; 18687 const struct bpf_struct_ops_desc *st_ops_desc; 18688 const struct bpf_struct_ops_arg_info *arg_info; 18689 const struct bpf_struct_ops *st_ops; 18690 const struct btf_member *member; 18691 struct bpf_prog *prog = env->prog; 18692 bool has_refcounted_arg = false; 18693 u32 btf_id, member_idx, member_off; 18694 struct btf *btf; 18695 const char *mname; 18696 int i, err; 18697 18698 if (!prog->gpl_compatible) { 18699 verbose(env, "struct ops programs must have a GPL compatible license\n"); 18700 return -EINVAL; 18701 } 18702 18703 if (!prog->aux->attach_btf_id) 18704 return -ENOTSUPP; 18705 18706 btf = prog->aux->attach_btf; 18707 if (btf_is_module(btf)) { 18708 /* Make sure st_ops is valid through the lifetime of env */ 18709 env->attach_btf_mod = btf_try_get_module(btf); 18710 if (!env->attach_btf_mod) { 18711 verbose(env, "struct_ops module %s is not found\n", 18712 btf_get_name(btf)); 18713 return -ENOTSUPP; 18714 } 18715 } 18716 18717 btf_id = prog->aux->attach_btf_id; 18718 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 18719 if (!st_ops_desc) { 18720 verbose(env, "attach_btf_id %u is not a supported struct\n", 18721 btf_id); 18722 return -ENOTSUPP; 18723 } 18724 st_ops = st_ops_desc->st_ops; 18725 18726 t = st_ops_desc->type; 18727 member_idx = prog->expected_attach_type; 18728 if (member_idx >= btf_type_vlen(t)) { 18729 verbose(env, "attach to invalid member idx %u of struct %s\n", 18730 member_idx, st_ops->name); 18731 return -EINVAL; 18732 } 18733 18734 member = &btf_type_member(t)[member_idx]; 18735 mname = btf_name_by_offset(btf, member->name_off); 18736 func_proto = btf_type_resolve_func_ptr(btf, member->type, 18737 NULL); 18738 if (!func_proto) { 18739 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 18740 mname, member_idx, st_ops->name); 18741 return -EINVAL; 18742 } 18743 18744 member_off = __btf_member_bit_offset(t, member) / 8; 18745 err = bpf_struct_ops_supported(st_ops, member_off); 18746 if (err) { 18747 verbose(env, "attach to unsupported member %s of struct %s\n", 18748 mname, st_ops->name); 18749 return err; 18750 } 18751 18752 if (st_ops->check_member) { 18753 err = st_ops->check_member(t, member, prog); 18754 18755 if (err) { 18756 verbose(env, "attach to unsupported member %s of struct %s\n", 18757 mname, st_ops->name); 18758 return err; 18759 } 18760 } 18761 18762 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 18763 verbose(env, "Private stack not supported by jit\n"); 18764 return -EACCES; 18765 } 18766 18767 arg_info = &st_ops_desc->arg_info[member_idx]; 18768 for (i = 0; i < arg_info->cnt; i++) { 18769 const struct bpf_ctx_arg_aux *info = &arg_info->info[i]; 18770 18771 if (info->refcounted) 18772 has_refcounted_arg = true; 18773 if (base_type(info->reg_type) == PTR_TO_ARENA) { 18774 if (!bpf_jit_supports_arena_args()) { 18775 verbose(env, "JIT does not support arena arguments\n"); 18776 return -ENOTSUPP; 18777 } 18778 if (!prog->aux->arena) { 18779 verbose(env, 18780 "arena argument of %s requires a program with an associated arena\n", 18781 mname); 18782 return -EINVAL; 18783 } 18784 } 18785 } 18786 18787 /* Tail call is not allowed for programs with refcounted arguments since we 18788 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 18789 */ 18790 for (i = 0; i < env->subprog_cnt; i++) { 18791 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 18792 verbose(env, "program with __ref argument cannot tail call\n"); 18793 return -EINVAL; 18794 } 18795 } 18796 18797 prog->aux->st_ops = st_ops; 18798 prog->aux->attach_st_ops_member_off = member_off; 18799 18800 prog->aux->attach_func_proto = func_proto; 18801 prog->aux->attach_func_name = mname; 18802 env->ops = st_ops->verifier_ops; 18803 18804 return bpf_prog_ctx_arg_info_init(prog, arg_info->info, arg_info->cnt); 18805 } 18806 #define SECURITY_PREFIX "security_" 18807 18808 #ifdef CONFIG_FUNCTION_ERROR_INJECTION 18809 18810 /* list of non-sleepable functions that are otherwise on 18811 * ALLOW_ERROR_INJECTION list 18812 */ 18813 BTF_SET_START(btf_non_sleepable_error_inject) 18814 /* Three functions below can be called from sleepable and non-sleepable context. 18815 * Assume non-sleepable from bpf safety point of view. 18816 */ 18817 BTF_ID(func, __filemap_add_folio) 18818 #ifdef CONFIG_FAIL_PAGE_ALLOC 18819 BTF_ID(func, should_fail_alloc_page) 18820 #endif 18821 #ifdef CONFIG_FAILSLAB 18822 BTF_ID(func, should_failslab) 18823 #endif 18824 BTF_SET_END(btf_non_sleepable_error_inject) 18825 18826 static int check_non_sleepable_error_inject(u32 btf_id) 18827 { 18828 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 18829 } 18830 18831 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18832 { 18833 /* fentry/fexit/fmod_ret progs can be sleepable if they are 18834 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 18835 */ 18836 if (!check_non_sleepable_error_inject(btf_id) && 18837 within_error_injection_list(addr)) 18838 return 0; 18839 18840 return -EINVAL; 18841 } 18842 18843 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18844 { 18845 if (within_error_injection_list(addr) || 18846 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18847 return 0; 18848 18849 return -EINVAL; 18850 } 18851 18852 #else 18853 18854 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code 18855 * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name() 18856 * but that just compares two concrete function names. 18857 */ 18858 static bool has_arch_syscall_prefix(const char *func_name) 18859 { 18860 #if defined(__x86_64__) 18861 return !strncmp(func_name, "__x64_", 6); 18862 #elif defined(__i386__) 18863 return !strncmp(func_name, "__ia32_", 7); 18864 #elif defined(__s390x__) 18865 return !strncmp(func_name, "__s390x_", 8); 18866 #elif defined(__aarch64__) 18867 return !strncmp(func_name, "__arm64_", 8); 18868 #elif defined(__riscv) 18869 return !strncmp(func_name, "__riscv_", 8); 18870 #elif defined(__powerpc__) || defined(__powerpc64__) 18871 return !strncmp(func_name, "sys_", 4); 18872 #elif defined(__loongarch__) 18873 return !strncmp(func_name, "sys_", 4); 18874 #else 18875 return false; 18876 #endif 18877 } 18878 18879 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */ 18880 18881 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18882 { 18883 if (has_arch_syscall_prefix(func_name)) 18884 return 0; 18885 18886 return -EINVAL; 18887 } 18888 18889 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18890 { 18891 if (has_arch_syscall_prefix(func_name) || 18892 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18893 return 0; 18894 18895 return -EINVAL; 18896 } 18897 18898 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */ 18899 18900 static bool is_tracing_multi_id(const struct bpf_prog *prog, u32 btf_id) 18901 { 18902 return is_tracing_multi(prog->expected_attach_type) && bpf_multi_func_btf_id[0] == btf_id; 18903 } 18904 18905 static int btf_id_allow_sleepable(u32 btf_id, unsigned long addr, const struct bpf_prog *prog, 18906 const struct btf *btf) 18907 { 18908 const struct btf_type *t; 18909 const char *tname; 18910 18911 if (!btf_is_kernel(btf)) 18912 return -EINVAL; 18913 18914 switch (prog->type) { 18915 case BPF_PROG_TYPE_TRACING: 18916 t = btf_type_by_id(btf, btf_id); 18917 if (!t) 18918 return -EINVAL; 18919 tname = btf_name_by_offset(btf, t->name_off); 18920 if (!tname) 18921 return -EINVAL; 18922 18923 /* 18924 * *.multi sleepable programs will pass initial sleepable check, 18925 * the actual attached btf ids are checked later during the link 18926 * attachment. 18927 */ 18928 if (is_tracing_multi_id(prog, btf_id)) 18929 return 0; 18930 if (!check_attach_sleepable(btf_id, addr, tname)) 18931 return 0; 18932 /* 18933 * fentry/fexit/fmod_ret progs can also be sleepable if they are 18934 * in the fmodret id set with the KF_SLEEPABLE flag. 18935 */ 18936 else { 18937 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog); 18938 18939 if (flags && (*flags & KF_SLEEPABLE)) 18940 return 0; 18941 } 18942 break; 18943 case BPF_PROG_TYPE_LSM: 18944 /* 18945 * LSM progs check that they are attached to bpf_lsm_*() funcs. 18946 * Only some of them are sleepable. 18947 */ 18948 if (bpf_lsm_is_sleepable_hook(btf_id)) 18949 return 0; 18950 break; 18951 default: 18952 break; 18953 } 18954 return -EINVAL; 18955 } 18956 18957 /* 18958 * Resolve the prototype describing a trace target's real ABI. A 18959 * KF_IMPLICIT_ARGS kfunc has its injected args stripped from the public 18960 * prototype, so use the _impl prototype; other targets use their own. 18961 */ 18962 static const struct btf_type * 18963 btf_attach_func_proto(struct bpf_verifier_log *log, struct btf *btf, u32 func_id) 18964 { 18965 const struct btf_type *func; 18966 struct module *mod = NULL; 18967 const char *name; 18968 int implicit; 18969 18970 func = btf_type_by_id(btf, func_id); 18971 if (!func || !btf_type_is_func(func)) 18972 return NULL; 18973 name = btf_name_by_offset(btf, func->name_off); 18974 18975 /* 18976 * btf_kfunc_check_flag() reads kfunc_set_tab, which for a module is 18977 * stable only once it is live; hold a module ref across the read to 18978 * exclude a concurrent module load. 18979 */ 18980 if (btf_is_module(btf)) { 18981 mod = btf_try_get_module(btf); 18982 if (!mod) 18983 return NULL; 18984 } 18985 implicit = btf_kfunc_check_flag(btf, func_id, KF_IMPLICIT_ARGS); 18986 module_put(mod); 18987 18988 if (implicit == -EINVAL) { 18989 bpf_log(log, "kfunc %s has inconsistent KF_IMPLICIT_ARGS\n", name); 18990 return NULL; 18991 } 18992 if (implicit > 0) 18993 return find_kfunc_impl_proto(log, btf, name); 18994 18995 return btf_type_by_id(btf, func->type); 18996 } 18997 18998 static bool attach_uses_trampoline_retval(enum bpf_attach_type type) 18999 { 19000 switch (type) { 19001 case BPF_MODIFY_RETURN: 19002 case BPF_TRACE_FEXIT: 19003 case BPF_TRACE_FEXIT_MULTI: 19004 case BPF_TRACE_FSESSION: 19005 case BPF_TRACE_FSESSION_MULTI: 19006 return true; 19007 default: 19008 return false; 19009 } 19010 } 19011 19012 int bpf_check_attach_target(struct bpf_verifier_log *log, 19013 const struct bpf_prog *prog, 19014 const struct bpf_prog *tgt_prog, 19015 u32 btf_id, 19016 struct bpf_attach_target_info *tgt_info) 19017 { 19018 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 19019 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 19020 char trace_symbol[KSYM_SYMBOL_LEN]; 19021 const char prefix[] = "btf_trace_"; 19022 struct bpf_raw_event_map *btp; 19023 int ret = 0, subprog = -1, i; 19024 const struct btf_type *t; 19025 bool conservative = true; 19026 const char *tname, *fname; 19027 struct btf *btf; 19028 long addr = 0; 19029 struct module *mod = NULL; 19030 19031 if (!btf_id) { 19032 bpf_log(log, "Tracing programs must provide btf_id\n"); 19033 return -EINVAL; 19034 } 19035 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 19036 if (!btf) { 19037 bpf_log(log, 19038 "Tracing program can only be attached to another program annotated with BTF\n"); 19039 return -EINVAL; 19040 } 19041 t = btf_type_by_id(btf, btf_id); 19042 if (!t) { 19043 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 19044 return -EINVAL; 19045 } 19046 tname = btf_name_by_offset(btf, t->name_off); 19047 if (!tname) { 19048 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 19049 return -EINVAL; 19050 } 19051 if (tgt_prog) { 19052 struct bpf_prog_aux *aux = tgt_prog->aux; 19053 bool tgt_changes_pkt_data; 19054 bool tgt_might_sleep; 19055 19056 if (bpf_prog_is_dev_bound(prog->aux) && 19057 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 19058 bpf_log(log, "Target program bound device mismatch"); 19059 return -EINVAL; 19060 } 19061 19062 for (i = 0; i < aux->func_info_cnt; i++) 19063 if (aux->func_info[i].type_id == btf_id) { 19064 subprog = i; 19065 break; 19066 } 19067 if (subprog == -1) { 19068 bpf_log(log, "Subprog %s doesn't exist\n", tname); 19069 return -EINVAL; 19070 } 19071 /* 19072 * A struct_ops indirect trampoline converts arena arguments 19073 * before invoking its program. A tracing or extension program 19074 * attached to the main program would see the converted offset as a 19075 * regular BTF pointer. 19076 */ 19077 if (subprog == 0 && bpf_prog_has_arena_ctx_arg(tgt_prog)) { 19078 bpf_log(log, "Cannot attach to a target with arena context arguments\n"); 19079 return -EOPNOTSUPP; 19080 } 19081 if (aux->func && aux->func[subprog]->aux->exception_cb) { 19082 bpf_log(log, 19083 "%s programs cannot attach to exception callback\n", 19084 prog_extension ? "Extension" : "Tracing"); 19085 return -EINVAL; 19086 } 19087 conservative = aux->func_info_aux[subprog].unreliable; 19088 if (prog_extension) { 19089 if (conservative) { 19090 bpf_log(log, 19091 "Cannot replace static functions\n"); 19092 return -EINVAL; 19093 } 19094 if (!prog->jit_requested) { 19095 bpf_log(log, 19096 "Extension programs should be JITed\n"); 19097 return -EINVAL; 19098 } 19099 tgt_changes_pkt_data = aux->func 19100 ? aux->func[subprog]->aux->changes_pkt_data 19101 : aux->changes_pkt_data; 19102 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 19103 bpf_log(log, 19104 "Extension program changes packet data, while original does not\n"); 19105 return -EINVAL; 19106 } 19107 19108 tgt_might_sleep = aux->func 19109 ? aux->func[subprog]->aux->might_sleep 19110 : aux->might_sleep; 19111 if (prog->aux->might_sleep && !tgt_might_sleep) { 19112 bpf_log(log, 19113 "Extension program may sleep, while original does not\n"); 19114 return -EINVAL; 19115 } 19116 } 19117 if (!tgt_prog->jited) { 19118 bpf_log(log, "Can attach to only JITed progs\n"); 19119 return -EINVAL; 19120 } 19121 if (prog_tracing) { 19122 if (aux->attach_tracing_prog) { 19123 /* 19124 * Target program is an fentry/fexit which is already attached 19125 * to another tracing program. More levels of nesting 19126 * attachment are not allowed. 19127 */ 19128 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 19129 return -EINVAL; 19130 } 19131 } else if (tgt_prog->type == prog->type) { 19132 /* 19133 * To avoid potential call chain cycles, prevent attaching of a 19134 * program extension to another extension. It's ok to attach 19135 * fentry/fexit to extension program. 19136 */ 19137 bpf_log(log, "Cannot recursively attach\n"); 19138 return -EINVAL; 19139 } 19140 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19141 prog_extension && 19142 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19143 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT || 19144 tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI || 19145 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || 19146 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION || 19147 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19148 /* Program extensions can extend all program types 19149 * except fentry/fexit. The reason is the following. 19150 * The fentry/fexit programs are used for performance 19151 * analysis, stats and can be attached to any program 19152 * type. When extension program is replacing XDP function 19153 * it is necessary to allow performance analysis of all 19154 * functions. Both original XDP program and its program 19155 * extension. Hence attaching fentry/fexit to 19156 * BPF_PROG_TYPE_EXT is allowed. If extending of 19157 * fentry/fexit was allowed it would be possible to create 19158 * long call chain fentry->extension->fentry->extension 19159 * beyond reasonable stack size. Hence extending fentry 19160 * is not allowed. 19161 */ 19162 bpf_log(log, "Cannot extend fentry/fexit/fsession\n"); 19163 return -EINVAL; 19164 } 19165 } else { 19166 if (prog_extension) { 19167 bpf_log(log, "Cannot replace kernel functions\n"); 19168 return -EINVAL; 19169 } 19170 } 19171 19172 switch (prog->expected_attach_type) { 19173 case BPF_TRACE_RAW_TP: 19174 if (tgt_prog) { 19175 bpf_log(log, 19176 "Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n"); 19177 return -EINVAL; 19178 } 19179 if (!btf_type_is_typedef(t)) { 19180 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19181 btf_id); 19182 return -EINVAL; 19183 } 19184 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19185 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19186 btf_id, tname); 19187 return -EINVAL; 19188 } 19189 tname += sizeof(prefix) - 1; 19190 19191 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 19192 * names. Thus using bpf_raw_event_map to get argument names. 19193 */ 19194 btp = bpf_get_raw_tracepoint(tname); 19195 if (!btp) 19196 return -EINVAL; 19197 if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) { 19198 bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n", 19199 tname); 19200 bpf_put_raw_tracepoint(btp); 19201 return -EINVAL; 19202 } 19203 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 19204 trace_symbol); 19205 bpf_put_raw_tracepoint(btp); 19206 19207 if (fname) 19208 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 19209 19210 if (!fname || ret < 0) { 19211 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 19212 prefix, tname); 19213 t = btf_type_by_id(btf, t->type); 19214 if (!btf_type_is_ptr(t)) 19215 /* should never happen in valid vmlinux build */ 19216 return -EINVAL; 19217 } else { 19218 t = btf_type_by_id(btf, ret); 19219 if (!btf_type_is_func(t)) 19220 /* should never happen in valid vmlinux build */ 19221 return -EINVAL; 19222 } 19223 19224 t = btf_type_by_id(btf, t->type); 19225 if (!btf_type_is_func_proto(t)) 19226 /* should never happen in valid vmlinux build */ 19227 return -EINVAL; 19228 19229 break; 19230 case BPF_TRACE_ITER: 19231 if (!btf_type_is_func(t)) { 19232 bpf_log(log, "attach_btf_id %u is not a function\n", 19233 btf_id); 19234 return -EINVAL; 19235 } 19236 t = btf_type_by_id(btf, t->type); 19237 if (!btf_type_is_func_proto(t)) 19238 return -EINVAL; 19239 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19240 if (ret) 19241 return ret; 19242 break; 19243 default: 19244 if (!prog_extension) 19245 return -EINVAL; 19246 fallthrough; 19247 case BPF_MODIFY_RETURN: 19248 case BPF_LSM_MAC: 19249 case BPF_LSM_CGROUP: 19250 case BPF_TRACE_FENTRY: 19251 case BPF_TRACE_FEXIT: 19252 case BPF_TRACE_FSESSION: 19253 case BPF_TRACE_FSESSION_MULTI: 19254 case BPF_TRACE_FENTRY_MULTI: 19255 case BPF_TRACE_FEXIT_MULTI: 19256 if ((prog->expected_attach_type == BPF_TRACE_FSESSION || 19257 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) && 19258 !bpf_jit_supports_fsession()) { 19259 bpf_log(log, "JIT does not support fsession\n"); 19260 return -EOPNOTSUPP; 19261 } 19262 if (!btf_type_is_func(t)) { 19263 bpf_log(log, "attach_btf_id %u is not a function\n", 19264 btf_id); 19265 return -EINVAL; 19266 } 19267 if (prog_extension && 19268 btf_check_type_match(log, prog, btf, t)) 19269 return -EINVAL; 19270 t = btf_attach_func_proto(log, btf, btf_id); 19271 if (!t || !btf_type_is_func_proto(t)) 19272 return -EINVAL; 19273 19274 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 19275 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 19276 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 19277 return -EINVAL; 19278 19279 if (tgt_prog && conservative) 19280 t = NULL; 19281 19282 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19283 if (ret < 0) 19284 return ret; 19285 19286 if (tgt_info->fmodel.ret_size > 8 && 19287 attach_uses_trampoline_retval(prog->expected_attach_type)) { 19288 bpf_log(log, 19289 "Attach to function %s with a >8 byte return value is not supported for this attach type\n", 19290 tname); 19291 return -EOPNOTSUPP; 19292 } 19293 19294 /* 19295 * *.multi programs don't need an address during program 19296 * verification, we just take the module ref if needed. 19297 */ 19298 if (is_tracing_multi_id(prog, btf_id)) { 19299 if (btf_is_module(btf)) { 19300 mod = btf_try_get_module(btf); 19301 if (!mod) 19302 return -ENOENT; 19303 } 19304 addr = 0; 19305 } else if (tgt_prog) { 19306 if (subprog == 0) 19307 addr = (long) tgt_prog->bpf_func; 19308 else 19309 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 19310 } else { 19311 if (btf_is_module(btf)) { 19312 mod = btf_try_get_module(btf); 19313 if (mod) 19314 addr = find_kallsyms_symbol_value(mod, tname); 19315 else 19316 addr = 0; 19317 } else { 19318 addr = kallsyms_lookup_name(tname); 19319 } 19320 if (!addr) { 19321 module_put(mod); 19322 bpf_log(log, 19323 "The address of function %s cannot be found\n", 19324 tname); 19325 return -ENOENT; 19326 } 19327 } 19328 19329 if (prog->sleepable) { 19330 ret = btf_id_allow_sleepable(btf_id, addr, prog, btf); 19331 if (ret) { 19332 module_put(mod); 19333 bpf_log(log, "%s is not sleepable\n", tname); 19334 return ret; 19335 } 19336 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19337 if (tgt_prog) { 19338 module_put(mod); 19339 bpf_log(log, "can't modify return codes of BPF programs\n"); 19340 return -EINVAL; 19341 } 19342 ret = -EINVAL; 19343 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19344 !check_attach_modify_return(addr, tname)) 19345 ret = 0; 19346 if (ret) { 19347 module_put(mod); 19348 bpf_log(log, "%s() is not modifiable\n", tname); 19349 return ret; 19350 } 19351 } 19352 19353 break; 19354 } 19355 tgt_info->tgt_addr = addr; 19356 tgt_info->tgt_name = tname; 19357 tgt_info->tgt_type = t; 19358 tgt_info->tgt_mod = mod; 19359 return 0; 19360 } 19361 19362 BTF_SET_START(btf_id_deny) 19363 BTF_ID_UNUSED 19364 #ifdef CONFIG_SMP 19365 BTF_ID(func, ___migrate_enable) 19366 BTF_ID(func, migrate_disable) 19367 BTF_ID(func, migrate_enable) 19368 #endif 19369 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19370 BTF_ID(func, rcu_read_unlock_strict) 19371 #endif 19372 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19373 BTF_ID(func, preempt_count_add) 19374 BTF_ID(func, preempt_count_sub) 19375 #endif 19376 #ifdef CONFIG_PREEMPT_RCU 19377 BTF_ID(func, __rcu_read_lock) 19378 BTF_ID(func, __rcu_read_unlock) 19379 #endif 19380 BTF_SET_END(btf_id_deny) 19381 19382 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 19383 * Currently, we must manually list all __noreturn functions here. Once a more 19384 * robust solution is implemented, this workaround can be removed. 19385 */ 19386 BTF_SET_START(noreturn_deny) 19387 #ifdef CONFIG_IA32_EMULATION 19388 BTF_ID(func, __ia32_sys_exit) 19389 BTF_ID(func, __ia32_sys_exit_group) 19390 #endif 19391 #ifdef CONFIG_KUNIT 19392 BTF_ID(func, __kunit_abort) 19393 BTF_ID(func, kunit_try_catch_throw) 19394 #endif 19395 #ifdef CONFIG_MODULES 19396 BTF_ID(func, __module_put_and_kthread_exit) 19397 #endif 19398 #ifdef CONFIG_X86_64 19399 BTF_ID(func, __x64_sys_exit) 19400 BTF_ID(func, __x64_sys_exit_group) 19401 #endif 19402 BTF_ID(func, do_exit) 19403 BTF_ID(func, do_group_exit) 19404 BTF_ID(func, kthread_complete_and_exit) 19405 BTF_ID(func, make_task_dead) 19406 BTF_SET_END(noreturn_deny) 19407 19408 static bool can_be_sleepable(struct bpf_prog *prog) 19409 { 19410 if (prog->type == BPF_PROG_TYPE_TRACING) { 19411 switch (prog->expected_attach_type) { 19412 case BPF_TRACE_FENTRY: 19413 case BPF_TRACE_FEXIT: 19414 case BPF_MODIFY_RETURN: 19415 case BPF_TRACE_ITER: 19416 case BPF_TRACE_FSESSION: 19417 case BPF_TRACE_RAW_TP: 19418 case BPF_TRACE_FENTRY_MULTI: 19419 case BPF_TRACE_FEXIT_MULTI: 19420 case BPF_TRACE_FSESSION_MULTI: 19421 return true; 19422 default: 19423 return false; 19424 } 19425 } 19426 if (prog->type == BPF_PROG_TYPE_LSM) 19427 return prog->expected_attach_type != BPF_LSM_CGROUP; 19428 19429 return prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 19430 prog->type == BPF_PROG_TYPE_STRUCT_OPS || 19431 prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT || 19432 prog->type == BPF_PROG_TYPE_TRACEPOINT; 19433 } 19434 19435 static int check_attach_btf_id(struct bpf_verifier_env *env) 19436 { 19437 struct bpf_prog *prog = env->prog; 19438 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 19439 struct bpf_attach_target_info tgt_info = {}; 19440 u32 btf_id = prog->aux->attach_btf_id; 19441 struct bpf_trampoline *tr; 19442 int ret; 19443 u64 key; 19444 19445 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 19446 if (prog->sleepable) 19447 /* attach_btf_id checked to be zero already */ 19448 return 0; 19449 verbose(env, "Syscall programs can only be sleepable\n"); 19450 return -EINVAL; 19451 } 19452 19453 if (prog->sleepable && !can_be_sleepable(prog)) { 19454 verbose(env, "Program of this type cannot be sleepable\n"); 19455 return -EINVAL; 19456 } 19457 19458 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 19459 return check_struct_ops_btf_id(env); 19460 19461 if (prog->type != BPF_PROG_TYPE_TRACING && 19462 prog->type != BPF_PROG_TYPE_LSM && 19463 prog->type != BPF_PROG_TYPE_EXT) 19464 return 0; 19465 19466 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 19467 if (ret) 19468 return ret; 19469 19470 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 19471 /* to make freplace equivalent to their targets, they need to 19472 * inherit env->ops and expected_attach_type for the rest of the 19473 * verification 19474 */ 19475 env->ops = bpf_verifier_ops[tgt_prog->type]; 19476 prog->expected_attach_type = tgt_prog->expected_attach_type; 19477 } 19478 19479 /* store info about the attachment target that will be used later */ 19480 prog->aux->attach_func_proto = tgt_info.tgt_type; 19481 prog->aux->attach_func_name = tgt_info.tgt_name; 19482 prog->aux->mod = tgt_info.tgt_mod; 19483 19484 if (tgt_prog) { 19485 prog->aux->saved_dst_prog_type = tgt_prog->type; 19486 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 19487 } 19488 19489 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 19490 prog->aux->attach_btf_trace = true; 19491 return 0; 19492 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 19493 return bpf_iter_prog_supported(prog); 19494 } 19495 19496 if (prog->type == BPF_PROG_TYPE_LSM) { 19497 ret = bpf_lsm_verify_prog(&env->log, prog); 19498 if (ret < 0) 19499 return ret; 19500 } else if (prog->type == BPF_PROG_TYPE_TRACING && 19501 btf_id_set_contains(&btf_id_deny, btf_id)) { 19502 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 19503 tgt_info.tgt_name); 19504 return -EINVAL; 19505 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 19506 prog->expected_attach_type == BPF_TRACE_FSESSION || 19507 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI || 19508 prog->expected_attach_type == BPF_MODIFY_RETURN) && 19509 btf_id_set_contains(&noreturn_deny, btf_id)) { 19510 verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n", 19511 tgt_info.tgt_name); 19512 return -EINVAL; 19513 } 19514 19515 /* 19516 * We don't get trampoline for tracing_multi programs at this point, 19517 * it's done when tracing_multi link is created. 19518 */ 19519 if (prog->type == BPF_PROG_TYPE_TRACING && 19520 is_tracing_multi(prog->expected_attach_type)) 19521 return 0; 19522 19523 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 19524 tr = bpf_trampoline_get(key, &tgt_info); 19525 if (!tr) 19526 return -ENOMEM; 19527 19528 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 19529 bpf_trampoline_set_flags(tr, BPF_TRAMP_F_TAIL_CALL_CTX); 19530 19531 prog->aux->dst_trampoline = tr; 19532 return 0; 19533 } 19534 19535 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id, 19536 struct bpf_attach_target_info *tgt_info) 19537 { 19538 const struct btf_type *t; 19539 unsigned long addr; 19540 const char *tname; 19541 int err; 19542 19543 if (!btf_id || !btf) 19544 return -EINVAL; 19545 19546 /* Check noreturn attachment. */ 19547 if ((prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || 19548 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) && 19549 btf_id_set_contains(&noreturn_deny, btf_id)) 19550 return -EINVAL; 19551 /* Check denied attachment. */ 19552 if (btf_id_set_contains(&btf_id_deny, btf_id)) 19553 return -EINVAL; 19554 19555 /* Check and get function target data. */ 19556 t = btf_type_by_id(btf, btf_id); 19557 if (!t) 19558 return -EINVAL; 19559 tname = btf_name_by_offset(btf, t->name_off); 19560 if (!tname) 19561 return -EINVAL; 19562 t = btf_attach_func_proto(NULL, btf, btf_id); 19563 if (!t || !btf_type_is_func_proto(t)) 19564 return -EINVAL; 19565 err = btf_distill_func_proto(NULL, btf, t, tname, &tgt_info->fmodel); 19566 if (err < 0) 19567 return err; 19568 if (tgt_info->fmodel.ret_size > 8 && 19569 attach_uses_trampoline_retval(prog->expected_attach_type)) 19570 return -EOPNOTSUPP; 19571 if (btf_is_module(btf)) { 19572 /* The bpf program already holds reference to module. */ 19573 if (WARN_ON_ONCE(!prog->aux->mod)) 19574 return -EINVAL; 19575 addr = find_kallsyms_symbol_value(prog->aux->mod, tname); 19576 } else { 19577 addr = kallsyms_lookup_name(tname); 19578 } 19579 if (!addr || !ftrace_location(addr)) 19580 return -ENOENT; 19581 19582 /* Check sleepable program attachment. */ 19583 if (prog->sleepable) { 19584 err = btf_id_allow_sleepable(btf_id, addr, prog, btf); 19585 if (err) 19586 return err; 19587 } 19588 tgt_info->tgt_addr = addr; 19589 return 0; 19590 } 19591 19592 struct btf *bpf_get_btf_vmlinux(void) 19593 { 19594 /* Pairs with the smp_store_release() on the parse path below. */ 19595 struct btf *btf = smp_load_acquire(&btf_vmlinux); 19596 19597 if (!btf && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 19598 mutex_lock(&btf_vmlinux_lock); 19599 btf = btf_vmlinux; 19600 if (!btf) { 19601 btf = btf_parse_vmlinux(); 19602 /* 19603 * Order the parsed BTF contents and the globals the 19604 * parse populated (e.g. bpf_ctx_convert.t) before 19605 * the pointer publication. Pairs with the acquire 19606 * on the lockless fast path above. 19607 */ 19608 smp_store_release(&btf_vmlinux, btf); 19609 } 19610 mutex_unlock(&btf_vmlinux_lock); 19611 } 19612 return btf; 19613 } 19614 19615 /* 19616 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 19617 * this case expect that every file descriptor in the array is either a map or 19618 * a BTF. Everything else is considered to be trash. 19619 */ 19620 static int add_fd_from_fd_array(struct bpf_verifier_env *env, u32 idx, int fd) 19621 { 19622 struct bpf_map *map; 19623 struct btf *btf; 19624 CLASS(fd, f)(fd); 19625 int err; 19626 19627 map = __bpf_map_get(f); 19628 if (!IS_ERR(map)) { 19629 err = __add_used_map(env, map); 19630 if (err < 0) 19631 return err; 19632 fd_slot_set_map(&env->fd_array[idx], map); 19633 return 0; 19634 } 19635 19636 btf = __btf_get_by_fd(f); 19637 if (!IS_ERR(btf)) { 19638 btf_get(btf); 19639 err = __add_used_btf(env, btf); 19640 if (err < 0) 19641 return err; 19642 fd_slot_set_btf(&env->fd_array[idx], btf); 19643 return 0; 19644 } 19645 19646 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 19647 return PTR_ERR(map); 19648 } 19649 19650 /* 19651 * A continuous fd_array is resolved into an in-memory cache with one slot 19652 * per entry. The bound here is deliberately generous and not derived from 19653 * the per-program object limits: Duplicate entries /are/ permitted, and 19654 * the number of distinct maps and BTFs a program can bind is enforced when 19655 * each entry is resolved by __add_used_map() and __add_used_btf(). 19656 */ 19657 #define MAX_FD_ARRAY_CNT 4096 19658 19659 static int process_fd_array_continuous(struct bpf_verifier_env *env, 19660 bpfptr_t fd_array, u32 cnt) 19661 { 19662 int fd, ret; 19663 u32 i; 19664 19665 if (cnt > MAX_FD_ARRAY_CNT) { 19666 verbose(env, "fd_array has too many entries (%u, max %u)\n", 19667 cnt, MAX_FD_ARRAY_CNT); 19668 return -E2BIG; 19669 } 19670 19671 env->fd_array = kvcalloc(cnt, sizeof(*env->fd_array), 19672 GFP_KERNEL_ACCOUNT); 19673 if (!env->fd_array) 19674 return -ENOMEM; 19675 env->fd_array_cnt = cnt; 19676 for (i = 0; i < cnt; i++) { 19677 if (copy_from_bpfptr_offset(&fd, fd_array, 19678 (size_t)i * sizeof(fd), sizeof(fd))) 19679 return -EFAULT; 19680 ret = add_fd_from_fd_array(env, i, fd); 19681 if (ret) 19682 return ret; 19683 } 19684 return 0; 19685 } 19686 19687 static int process_fd_array(struct bpf_verifier_env *env, 19688 union bpf_attr *attr, bpfptr_t uattr) 19689 { 19690 bpfptr_t fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 19691 19692 if (bpfptr_is_null(fd_array)) { 19693 if (attr->fd_array_cnt) { 19694 verbose(env, "fd_array_cnt %u without fd_array is invalid\n", 19695 attr->fd_array_cnt); 19696 return -EINVAL; 19697 } 19698 return 0; 19699 } 19700 /* 19701 * New API: the caller passes fd_array_cnt and a continuous array that 19702 * is resolved and bound up front. Legacy API (no fd_array_cnt): keep 19703 * the caller's array and resolve entries on the spot at each reference. 19704 */ 19705 if (attr->fd_array_cnt) 19706 return process_fd_array_continuous(env, fd_array, 19707 attr->fd_array_cnt); 19708 env->fd_array_raw = fd_array; 19709 return 0; 19710 } 19711 19712 /* replace a generic kfunc with a specialized version if necessary */ 19713 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx) 19714 { 19715 struct bpf_prog *prog = env->prog; 19716 bool seen_direct_write; 19717 void *xdp_kfunc; 19718 bool is_rdonly; 19719 u32 func_id = desc->func_id; 19720 u16 offset = desc->offset; 19721 unsigned long addr = desc->addr; 19722 19723 if (offset) /* return if module BTF is used */ 19724 return 0; 19725 19726 if (bpf_dev_bound_kfunc_id(func_id)) { 19727 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19728 if (xdp_kfunc) 19729 addr = (unsigned long)xdp_kfunc; 19730 /* fallback to default kfunc when not supported by netdev */ 19731 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19732 seen_direct_write = env->seen_direct_write; 19733 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19734 19735 if (is_rdonly) 19736 addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19737 19738 /* restore env->seen_direct_write to its original value, since 19739 * may_access_direct_pkt_data mutates it 19740 */ 19741 env->seen_direct_write = seen_direct_write; 19742 } else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) { 19743 if (bpf_lsm_has_d_inode_locked(prog)) 19744 addr = (unsigned long)bpf_set_dentry_xattr_locked; 19745 } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) { 19746 if (bpf_lsm_has_d_inode_locked(prog)) 19747 addr = (unsigned long)bpf_remove_dentry_xattr_locked; 19748 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 19749 if (!env->insn_aux_data[insn_idx].non_sleepable) 19750 addr = (unsigned long)bpf_dynptr_from_file_sleepable; 19751 } else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) { 19752 if (env->insn_aux_data[insn_idx].non_sleepable) 19753 addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable; 19754 } else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) { 19755 if (env->insn_aux_data[insn_idx].non_sleepable) 19756 addr = (unsigned long)bpf_arena_free_pages_non_sleepable; 19757 } 19758 desc->addr = addr; 19759 return 0; 19760 } 19761 19762 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19763 u16 struct_meta_reg, 19764 u16 node_offset_reg, 19765 struct bpf_insn *insn, 19766 struct bpf_insn *insn_buf, 19767 int *cnt) 19768 { 19769 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19770 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19771 19772 insn_buf[0] = addr[0]; 19773 insn_buf[1] = addr[1]; 19774 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19775 insn_buf[3] = *insn; 19776 *cnt = 4; 19777 } 19778 19779 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19780 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19781 { 19782 struct bpf_kfunc_desc *desc; 19783 int err; 19784 19785 if (!insn->imm) { 19786 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19787 return -EINVAL; 19788 } 19789 19790 *cnt = 0; 19791 19792 /* insn->imm has the btf func_id. Replace it with an offset relative to 19793 * __bpf_call_base, unless the JIT needs to call functions that are 19794 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19795 */ 19796 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19797 if (!desc) { 19798 verifier_bug(env, "kernel function descriptor not found for func_id %u", 19799 insn->imm); 19800 return -EFAULT; 19801 } 19802 19803 err = specialize_kfunc(env, desc, insn_idx); 19804 if (err) 19805 return err; 19806 19807 if (!bpf_jit_supports_far_kfunc_call()) 19808 insn->imm = BPF_CALL_IMM(desc->addr); 19809 19810 if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) { 19811 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19812 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19813 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19814 19815 if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) { 19816 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19817 insn_idx); 19818 return -EFAULT; 19819 } 19820 19821 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19822 insn_buf[1] = addr[0]; 19823 insn_buf[2] = addr[1]; 19824 insn_buf[3] = *insn; 19825 *cnt = 4; 19826 } else if (is_bpf_obj_drop_kfunc(desc->func_id) || 19827 is_bpf_percpu_obj_drop_kfunc(desc->func_id) || 19828 is_bpf_refcount_acquire_kfunc(desc->func_id)) { 19829 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19830 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19831 19832 if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) { 19833 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19834 insn_idx); 19835 return -EFAULT; 19836 } 19837 19838 if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) { 19839 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19840 insn_idx); 19841 return -EFAULT; 19842 } 19843 19844 insn_buf[0] = addr[0]; 19845 insn_buf[1] = addr[1]; 19846 insn_buf[2] = *insn; 19847 *cnt = 3; 19848 } else if (is_bpf_list_push_kfunc(desc->func_id) || 19849 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19850 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19851 int struct_meta_reg = BPF_REG_3; 19852 int node_offset_reg = BPF_REG_4; 19853 19854 /* list_add/rbtree_add have an extra arg (prev/less), 19855 * so args-to-fixup are in diff regs. 19856 */ 19857 if (desc->func_id == special_kfunc_list[KF_bpf_list_add] || 19858 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19859 struct_meta_reg = BPF_REG_4; 19860 node_offset_reg = BPF_REG_5; 19861 } 19862 19863 if (!kptr_struct_meta) { 19864 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19865 insn_idx); 19866 return -EFAULT; 19867 } 19868 19869 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19870 node_offset_reg, insn, insn_buf, cnt); 19871 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19872 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19873 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19874 *cnt = 1; 19875 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] && 19876 (env->prog->expected_attach_type == BPF_TRACE_FSESSION || 19877 env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19878 19879 /* 19880 * inline the bpf_session_is_return() for fsession: 19881 * bool bpf_session_is_return(void *ctx) 19882 * { 19883 * return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1; 19884 * } 19885 */ 19886 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19887 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT); 19888 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1); 19889 *cnt = 3; 19890 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] && 19891 (env->prog->expected_attach_type == BPF_TRACE_FSESSION || 19892 env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19893 /* 19894 * inline bpf_session_cookie() for fsession: 19895 * __u64 *bpf_session_cookie(void *ctx) 19896 * { 19897 * u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF; 19898 * return &((u64 *)ctx)[-off]; 19899 * } 19900 */ 19901 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19902 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT); 19903 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF); 19904 insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19905 insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1); 19906 insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0); 19907 *cnt = 6; 19908 } else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_new]) { 19909 /* inline bpf_iter_num_new(&it, start, end); R1=&it, R2=start, R3=end */ 19910 int i = 0; 19911 19912 /* if (start > end) goto einval; */ 19913 insn_buf[i++] = BPF_JMP32_REG(BPF_JSGT, BPF_REG_2, BPF_REG_3, 8); 19914 /* r0 = (u32)end - (u32)start; if (r0 > BPF_MAX_LOOPS) goto e2big; */ 19915 insn_buf[i++] = BPF_MOV32_REG(BPF_REG_0, BPF_REG_3); 19916 insn_buf[i++] = BPF_ALU32_REG(BPF_SUB, BPF_REG_0, BPF_REG_2); 19917 insn_buf[i++] = BPF_JMP_IMM(BPF_JGT, BPF_REG_0, BPF_MAX_LOOPS, 8); 19918 /* s->cur = start - 1; s->end = end; return 0; */ 19919 insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_2, -1); 19920 insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_2, 0); 19921 insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_3, 4); 19922 insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0); 19923 insn_buf[i++] = BPF_JMP_A(5); 19924 /* einval: s->cur = s->end = 0; return -EINVAL; */ 19925 insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0); 19926 insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 19927 insn_buf[i++] = BPF_JMP_A(2); 19928 /* e2big: s->cur = s->end = 0; return -E2BIG; */ 19929 insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0); 19930 insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, -E2BIG); 19931 *cnt = i; 19932 } else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_next]) { 19933 /* inline bpf_iter_num_next(&it); R1=&it, returns &s->cur or NULL */ 19934 int i = 0; 19935 19936 /* r0 = s->cur + 1; if ((s32)r0 >= s->end) goto done; */ 19937 insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_1, 0); 19938 insn_buf[i++] = BPF_ALU32_IMM(BPF_ADD, BPF_REG_0, 1); 19939 insn_buf[i++] = BPF_LDX_MEM(BPF_W, BPF_REG_2, BPF_REG_1, 4); 19940 insn_buf[i++] = BPF_JMP32_REG(BPF_JSGE, BPF_REG_0, BPF_REG_2, 3); 19941 /* s->cur = r0; return &s->cur; */ 19942 insn_buf[i++] = BPF_STX_MEM(BPF_W, BPF_REG_1, BPF_REG_0, 0); 19943 insn_buf[i++] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19944 insn_buf[i++] = BPF_JMP_A(2); 19945 /* done: s->cur = s->end = 0; return NULL; */ 19946 insn_buf[i++] = BPF_ST_MEM(BPF_DW, BPF_REG_1, 0, 0); 19947 insn_buf[i++] = BPF_MOV64_IMM(BPF_REG_0, 0); 19948 *cnt = i; 19949 } else if (desc->func_id == special_kfunc_list[KF_bpf_iter_num_destroy]) { 19950 /* bpf_iter_num_destroy() is a no-op; emit a nop to drop the call */ 19951 insn_buf[0] = BPF_JMP_A(0); 19952 *cnt = 1; 19953 } 19954 19955 if (env->insn_aux_data[insn_idx].arg_prog) { 19956 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 19957 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 19958 int idx = *cnt; 19959 19960 insn_buf[idx++] = ld_addrs[0]; 19961 insn_buf[idx++] = ld_addrs[1]; 19962 insn_buf[idx++] = *insn; 19963 *cnt = idx; 19964 } 19965 return 0; 19966 } 19967 19968 static enum bpf_sig_keyring bpf_classify_keyring(s32 keyring_id) 19969 { 19970 switch (keyring_id) { 19971 case 0: 19972 return BPF_SIG_KEYRING_BUILTIN; 19973 case (s32)(unsigned long)VERIFY_USE_SECONDARY_KEYRING: 19974 return BPF_SIG_KEYRING_SECONDARY; 19975 case (s32)(unsigned long)VERIFY_USE_PLATFORM_KEYRING: 19976 return BPF_SIG_KEYRING_PLATFORM; 19977 default: 19978 return BPF_SIG_KEYRING_USER; 19979 } 19980 } 19981 19982 /* 19983 * Verify the PKCS#7 signature of a loaded program. Called from bpf_check() 19984 * once the program's metadata maps have been resolved into used_maps, so 19985 * the exact maps folded into the signature are the ones the program binds. 19986 * 19987 * The signature covers the instructions followed by the frozen contents of 19988 * each map, in @maps order: insns || map_0 || map_1 || [...]. On success the 19989 * verdict and keyring info are recorded on prog->aux. 19990 */ 19991 static int bpf_prog_verify_signature(struct bpf_verifier_env *env, 19992 union bpf_attr *attr, bool is_kernel) 19993 { 19994 bpfptr_t usig = make_bpfptr(attr->signature, is_kernel); 19995 struct bpf_dynptr_kern sig_ptr, data_ptr; 19996 struct bpf_prog *prog = env->prog; 19997 struct bpf_map **maps = env->used_maps; 19998 struct bpf_key *key = NULL; 19999 void *sig, *data = NULL; 20000 u32 map_cnt = env->used_map_cnt; 20001 u32 i, off, insns_sz; 20002 u64 data_sz; 20003 int err = 0; 20004 20005 /* 20006 * Don't attempt to use kmalloc_large or vmalloc for signatures. 20007 * Practical signature for BPF program should be below this limit. 20008 */ 20009 if (!attr->signature_size || 20010 attr->signature_size > KMALLOC_MAX_CACHE_SIZE) 20011 return -EINVAL; 20012 if (system_keyring_id_check(attr->keyring_id) == 0) 20013 key = bpf_lookup_system_key(attr->keyring_id); 20014 else 20015 key = bpf_lookup_user_key(attr->keyring_id, 0); 20016 if (!key) { 20017 verbose(env, "cannot resolve signing keyring with keyring_id %d\n", 20018 attr->keyring_id); 20019 return -EINVAL; 20020 } 20021 20022 sig = kvmemdup_bpfptr(usig, attr->signature_size); 20023 if (IS_ERR(sig)) { 20024 bpf_key_put(key); 20025 return PTR_ERR(sig); 20026 } 20027 20028 insns_sz = prog->len * sizeof(struct bpf_insn); 20029 data_sz = insns_sz; 20030 for (i = 0; i < map_cnt; i++) { 20031 struct bpf_map *map = maps[i]; 20032 20033 if (map->map_type != BPF_MAP_TYPE_ARRAY || 20034 !map->ops->map_direct_value_addr) { 20035 verbose(env, "signed program metadata map '%s' must be an array\n", 20036 map->name); 20037 err = -EINVAL; 20038 goto out; 20039 } 20040 if (!READ_ONCE(map->frozen)) { 20041 verbose(env, "signed program metadata map '%s' must be frozen\n", 20042 map->name); 20043 err = -EPERM; 20044 goto out; 20045 } 20046 if (bpf_map_write_active(map)) { 20047 verbose(env, "signed program metadata map '%s' has active writers\n", 20048 map->name); 20049 err = -EBUSY; 20050 goto out; 20051 } 20052 if (!map->excl_prog_sha) { 20053 verbose(env, "signed program metadata map '%s' must be exclusive\n", 20054 map->name); 20055 err = -EPERM; 20056 goto out; 20057 } 20058 data_sz += map->value_size; 20059 } 20060 if (bpf_dynptr_check_size(data_sz)) { 20061 verbose(env, "signed payload too large: %llu bytes\n", data_sz); 20062 err = -E2BIG; 20063 goto out; 20064 } 20065 data = kvmalloc(data_sz, GFP_KERNEL_ACCOUNT | __GFP_ZERO); 20066 if (!data) { 20067 err = -ENOMEM; 20068 goto out; 20069 } 20070 memcpy(data, prog->insnsi, insns_sz); 20071 off = insns_sz; 20072 for (i = 0; i < map_cnt; i++) { 20073 struct bpf_map *map = maps[i]; 20074 u64 addr; 20075 20076 err = map->ops->map_direct_value_addr(map, &addr, 0); 20077 if (err) { 20078 verbose(env, "failed to read signed metadata map '%s': %d\n", 20079 map->name, err); 20080 goto out; 20081 } 20082 memcpy(data + off, (void *)(unsigned long)addr, 20083 map->value_size); 20084 off += map->value_size; 20085 } 20086 20087 bpf_dynptr_init(&data_ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, data_sz); 20088 bpf_dynptr_init(&sig_ptr, sig, BPF_DYNPTR_TYPE_LOCAL, 0, 20089 attr->signature_size); 20090 20091 err = bpf_verify_pkcs7_signature((struct bpf_dynptr *)&data_ptr, 20092 (struct bpf_dynptr *)&sig_ptr, key); 20093 if (err) { 20094 verbose(env, "signature verification failed: %d\n", err); 20095 } else { 20096 verbose(env, "signature verification passed\n"); 20097 prog->aux->sig.keyring_serial = bpf_key_serial(key); 20098 prog->aux->sig.keyring_type = bpf_classify_keyring(attr->keyring_id); 20099 prog->aux->sig.verdict = BPF_SIG_VERIFIED; 20100 } 20101 out: 20102 kvfree(data); 20103 bpf_key_put(key); 20104 kvfree(sig); 20105 return err; 20106 } 20107 20108 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, 20109 struct bpf_log_attr *attr_log) 20110 { 20111 u64 start_time = ktime_get_ns(); 20112 struct bpf_verifier_env *env; 20113 int i, len, ret = -EINVAL, err; 20114 bool is_priv; 20115 20116 BTF_TYPE_EMIT(enum bpf_features); 20117 20118 /* no program is valid */ 20119 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20120 return -EINVAL; 20121 20122 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20123 * allocate/free it every time bpf_check() is called 20124 */ 20125 env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT); 20126 if (!env) 20127 return -ENOMEM; 20128 20129 env->bt.env = env; 20130 env->prog = *prog; 20131 env->ops = bpf_verifier_ops[env->prog->type]; 20132 20133 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 20134 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 20135 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 20136 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 20137 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 20138 env->signature = attr->signature; 20139 20140 /* user could have requested verbose verifier output 20141 * and supplied buffer to store the verification trace 20142 */ 20143 ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size); 20144 if (ret) 20145 goto err_free_env; 20146 if (env->signature) { 20147 ret = bpf_prog_calc_tag(env->prog); 20148 if (ret < 0) 20149 goto err_prep; 20150 } 20151 20152 ret = process_fd_array(env, attr, uattr); 20153 if (ret) 20154 goto err_prep; 20155 20156 if (env->signature) { 20157 ret = bpf_prog_verify_signature(env, attr, uattr.is_kernel); 20158 if (ret) 20159 goto err_prep; 20160 } 20161 20162 ret = security_bpf_prog_load(env->prog, attr, env->prog->aux->token, 20163 uattr.is_kernel); 20164 if (ret) 20165 goto err_prep; 20166 20167 bpf_get_btf_vmlinux(); 20168 20169 /* Serialize verification of unprivileged programs. */ 20170 if (!is_priv) 20171 mutex_lock(&bpf_verifier_lock); 20172 20173 len = env->prog->len; 20174 env->insn_aux_data = 20175 __vmalloc(array_size(sizeof(struct bpf_insn_aux_data), len), 20176 GFP_KERNEL_ACCOUNT | __GFP_ZERO); 20177 ret = -ENOMEM; 20178 if (!env->insn_aux_data) 20179 goto skip_full_check; 20180 for (i = 0; i < len; i++) 20181 env->insn_aux_data[i].orig_idx = i; 20182 env->succ = bpf_iarray_realloc(NULL, 2); 20183 if (!env->succ) 20184 goto skip_full_check; 20185 20186 mark_verifier_state_clean(env); 20187 20188 if (IS_ERR(btf_vmlinux)) { 20189 /* Either gcc or pahole or kernel are broken. */ 20190 verbose(env, "in-kernel BTF is malformed\n"); 20191 ret = PTR_ERR(btf_vmlinux); 20192 goto skip_full_check; 20193 } 20194 20195 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20196 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20197 env->strict_alignment = true; 20198 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20199 env->strict_alignment = false; 20200 20201 if (is_priv) 20202 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20203 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 20204 20205 env->explored_states = kvzalloc_objs(struct list_head, 20206 state_htab_size(env), 20207 GFP_KERNEL_ACCOUNT); 20208 ret = -ENOMEM; 20209 if (!env->explored_states) 20210 goto skip_full_check; 20211 20212 for (i = 0; i < state_htab_size(env); i++) 20213 INIT_LIST_HEAD(&env->explored_states[i]); 20214 INIT_LIST_HEAD(&env->free_list); 20215 20216 /* Prepare BTF and func_info needed to discover all subprograms. */ 20217 ret = bpf_prepare_btf_info(env, attr, uattr); 20218 if (ret < 0) 20219 goto skip_full_check; 20220 20221 /* Discover all subprograms before validating their layout and BTF. */ 20222 ret = add_subprogs(env); 20223 if (ret < 0) 20224 goto skip_full_check; 20225 20226 ret = check_subprogs(env); 20227 if (ret < 0) 20228 goto skip_full_check; 20229 20230 /* Validate BTF against the complete subprogram layout and apply CO-RE. */ 20231 ret = bpf_check_btf_info(env, attr, uattr); 20232 if (ret < 0) 20233 goto skip_full_check; 20234 20235 /* Validate instructions and resolve the program's referenced resources. */ 20236 ret = check_and_resolve_insns(env); 20237 if (ret < 0) 20238 goto skip_full_check; 20239 20240 /* Build kfunc prototypes after resolving program resources. */ 20241 ret = add_kfuncs(env); 20242 if (ret < 0) 20243 goto skip_full_check; 20244 20245 if (bpf_prog_is_offloaded(env->prog->aux)) { 20246 ret = bpf_prog_offload_verifier_prep(env->prog); 20247 if (ret) 20248 goto skip_full_check; 20249 } 20250 20251 ret = bpf_check_cfg(env); 20252 if (ret < 0) 20253 goto skip_full_check; 20254 20255 ret = bpf_compute_postorder(env); 20256 if (ret < 0) 20257 goto skip_full_check; 20258 20259 ret = bpf_stack_liveness_init(env); 20260 if (ret) 20261 goto skip_full_check; 20262 20263 ret = check_attach_btf_id(env); 20264 if (ret) 20265 goto skip_full_check; 20266 20267 ret = bpf_compute_const_regs(env); 20268 if (ret < 0) 20269 goto skip_full_check; 20270 20271 ret = bpf_prune_dead_branches(env); 20272 if (ret < 0) 20273 goto skip_full_check; 20274 20275 ret = sort_subprogs_topo(env); 20276 if (ret < 0) 20277 goto skip_full_check; 20278 20279 ret = bpf_compute_scc(env); 20280 if (ret < 0) 20281 goto skip_full_check; 20282 20283 ret = bpf_compute_live_registers(env); 20284 if (ret < 0) 20285 goto skip_full_check; 20286 20287 ret = mark_fastcall_patterns(env); 20288 if (ret < 0) 20289 goto skip_full_check; 20290 20291 ret = do_check_main(env); 20292 ret = ret ?: do_check_subprogs(env); 20293 20294 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20295 ret = bpf_prog_offload_finalize(env); 20296 20297 skip_full_check: 20298 kvfree(env->explored_states); 20299 20300 /* might decrease stack depth, keep it before passes that 20301 * allocate additional slots. 20302 */ 20303 if (ret == 0) 20304 ret = bpf_remove_fastcall_spills_fills(env); 20305 20306 if (ret == 0) 20307 ret = check_max_stack_depth(env); 20308 20309 /* instruction rewrites happen after this point */ 20310 if (ret == 0) 20311 ret = bpf_optimize_bpf_loop(env); 20312 20313 if (is_priv) { 20314 if (ret == 0) 20315 bpf_opt_hard_wire_dead_code_branches(env); 20316 if (ret == 0) 20317 ret = bpf_opt_remove_dead_code(env); 20318 if (ret == 0) 20319 ret = bpf_opt_remove_nops(env); 20320 } else { 20321 if (ret == 0) 20322 sanitize_dead_code(env); 20323 } 20324 20325 if (ret == 0) 20326 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20327 ret = bpf_convert_ctx_accesses(env); 20328 20329 if (ret == 0) 20330 ret = bpf_do_misc_fixups(env); 20331 20332 /* do 32-bit optimization after insn patching has done so those patched 20333 * insns could be handled correctly. 20334 */ 20335 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20336 ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr); 20337 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20338 : false; 20339 } 20340 20341 if (ret == 0) 20342 ret = bpf_fixup_call_args(env); 20343 20344 env->verification_time = ktime_get_ns() - start_time; 20345 print_verification_stats(env); 20346 env->prog->aux->verified_insns = env->insn_processed; 20347 20348 /* preserve original error even if log finalization is successful */ 20349 err = bpf_log_attr_finalize(attr_log, &env->log); 20350 if (err) 20351 ret = err; 20352 20353 if (ret) 20354 goto err_release_maps; 20355 20356 if (env->used_map_cnt) { 20357 /* if program passed verifier, update used_maps in bpf_prog_info */ 20358 env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0], 20359 env->used_map_cnt, 20360 GFP_KERNEL_ACCOUNT); 20361 20362 if (!env->prog->aux->used_maps) { 20363 ret = -ENOMEM; 20364 goto err_release_maps; 20365 } 20366 20367 memcpy(env->prog->aux->used_maps, env->used_maps, 20368 sizeof(env->used_maps[0]) * env->used_map_cnt); 20369 env->prog->aux->used_map_cnt = env->used_map_cnt; 20370 } 20371 if (env->used_btf_cnt) { 20372 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20373 env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0], 20374 env->used_btf_cnt, 20375 GFP_KERNEL_ACCOUNT); 20376 if (!env->prog->aux->used_btfs) { 20377 ret = -ENOMEM; 20378 goto err_release_maps; 20379 } 20380 20381 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20382 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20383 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20384 } 20385 if (env->used_map_cnt || env->used_btf_cnt) { 20386 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20387 * bpf_ld_imm64 instructions 20388 */ 20389 convert_pseudo_ld_imm64(env); 20390 } 20391 20392 adjust_btf_func(env); 20393 20394 /* extension progs temporarily inherit the attach_type of their targets 20395 for verification purposes, so set it back to zero before returning 20396 */ 20397 if (env->prog->type == BPF_PROG_TYPE_EXT) 20398 env->prog->expected_attach_type = 0; 20399 20400 env->prog = __bpf_prog_select_runtime(env, env->prog, &ret); 20401 20402 err_release_maps: 20403 if (ret) 20404 release_insn_arrays(env); 20405 if (!env->prog->aux->used_maps) 20406 /* if we didn't copy map pointers into bpf_prog_info, release 20407 * them now. Otherwise free_used_maps() will release them. 20408 */ 20409 release_maps(env); 20410 if (!env->prog->aux->used_btfs) 20411 release_btfs(env); 20412 20413 *prog = env->prog; 20414 20415 module_put(env->attach_btf_mod); 20416 if (!is_priv) 20417 mutex_unlock(&bpf_verifier_lock); 20418 goto err_free_env; 20419 err_prep: 20420 err = bpf_log_attr_finalize(attr_log, &env->log); 20421 if (err) 20422 ret = err; 20423 release_insn_arrays(env); 20424 release_maps(env); 20425 release_btfs(env); 20426 err_free_env: 20427 if (env->insn_aux_data) 20428 bpf_clear_insn_aux_data(env, 0, env->prog->len); 20429 vfree(env->insn_aux_data); 20430 kvfree(env->fd_array); 20431 bpf_stack_liveness_free(env); 20432 kvfree(env->cfg.insn_postorder); 20433 kvfree(env->scc_info); 20434 kvfree(env->succ); 20435 kvfree(env->gotox_tmp_buf); 20436 kvfree(env); 20437 return ret; 20438 } 20439