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 bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 210 static bool is_tracing_prog_type(enum bpf_prog_type type); 211 static int ref_set_non_owning(struct bpf_verifier_env *env, 212 struct bpf_reg_state *reg); 213 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg); 214 static inline bool in_sleepable_context(struct bpf_verifier_env *env); 215 static const char *non_sleepable_context_description(struct bpf_verifier_env *env); 216 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 217 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 218 219 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 220 struct bpf_map *map, 221 bool unpriv, bool poison) 222 { 223 unpriv |= bpf_map_ptr_unpriv(aux); 224 aux->map_ptr_state.unpriv = unpriv; 225 aux->map_ptr_state.poison = poison; 226 aux->map_ptr_state.map_ptr = map; 227 } 228 229 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 230 { 231 bool poisoned = bpf_map_key_poisoned(aux); 232 233 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 234 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 235 } 236 237 static void update_ref_obj(struct ref_obj_desc *ref_obj, struct bpf_reg_state *reg) 238 { 239 ref_obj->id = reg->id; 240 ref_obj->parent_id = reg->parent_id; 241 ref_obj->cnt++; 242 } 243 244 static int validate_ref_obj(struct bpf_verifier_env *env, struct ref_obj_desc *ref_obj) 245 { 246 if (ref_obj->cnt > 1) { 247 verifier_bug(env, "function expects only one referenced object but got %d\n", 248 ref_obj->cnt); 249 return -EFAULT; 250 } 251 252 return 0; 253 } 254 255 struct bpf_kfunc_meta { 256 struct btf *btf; 257 const struct btf_type *proto; 258 const char *name; 259 const u32 *flags; 260 s32 id; 261 }; 262 263 struct btf *btf_vmlinux; 264 265 typedef struct argno { 266 int argno; 267 } argno_t; 268 269 static argno_t argno_from_reg(u32 regno) 270 { 271 return (argno_t){ .argno = regno }; 272 } 273 274 static argno_t argno_from_arg(u32 arg) 275 { 276 return (argno_t){ .argno = -arg }; 277 } 278 279 static int reg_from_argno(argno_t a) 280 { 281 if (a.argno >= 0) 282 return a.argno; 283 if (a.argno >= -MAX_BPF_FUNC_REG_ARGS) 284 return -a.argno; 285 return -1; 286 } 287 288 static int arg_from_argno(argno_t a) 289 { 290 if (a.argno < 0) 291 return -a.argno; 292 return -1; 293 } 294 295 static int arg_idx_from_argno(argno_t a) 296 { 297 return arg_from_argno(a) - 1; 298 } 299 300 static const char *btf_type_name(const struct btf *btf, u32 id) 301 { 302 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 303 } 304 305 static DEFINE_MUTEX(bpf_verifier_lock); 306 static DEFINE_MUTEX(btf_vmlinux_lock); 307 static DEFINE_MUTEX(bpf_percpu_ma_lock); 308 309 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 310 { 311 struct bpf_verifier_env *env = private_data; 312 va_list args; 313 314 if (!bpf_verifier_log_needed(&env->log)) 315 return; 316 317 va_start(args, fmt); 318 bpf_verifier_vlog(&env->log, fmt, args); 319 va_end(args); 320 } 321 322 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 323 struct bpf_reg_state *reg, 324 struct bpf_retval_range range, const char *ctx, 325 const char *reg_name) 326 { 327 bool unknown = true; 328 329 verbose(env, "%s the register %s has", ctx, reg_name); 330 if (reg_smin(reg) > S64_MIN) { 331 verbose(env, " smin=%lld", reg_smin(reg)); 332 unknown = false; 333 } 334 if (reg_smax(reg) < S64_MAX) { 335 verbose(env, " smax=%lld", reg_smax(reg)); 336 unknown = false; 337 } 338 if (unknown) 339 verbose(env, " unknown scalar value"); 340 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 341 } 342 343 static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 344 { 345 enum bpf_reg_type type; 346 347 type = reg->type; 348 if (type_may_be_null(type)) 349 return false; 350 351 type = base_type(type); 352 return type == PTR_TO_SOCKET || 353 type == PTR_TO_TCP_SOCK || 354 type == PTR_TO_MAP_VALUE || 355 type == PTR_TO_MAP_KEY || 356 type == PTR_TO_SOCK_COMMON || 357 (type == PTR_TO_BTF_ID && is_trusted_reg(env, reg)) || 358 (type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) || 359 type == CONST_PTR_TO_MAP; 360 } 361 362 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 363 { 364 struct btf_record *rec = NULL; 365 struct btf_struct_meta *meta; 366 367 if (reg->type == PTR_TO_MAP_VALUE) { 368 rec = reg->map_ptr->record; 369 } else if (type_is_ptr_alloc_obj(reg->type)) { 370 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 371 if (meta) 372 rec = meta->record; 373 } 374 return rec; 375 } 376 377 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog) 378 { 379 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 380 381 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 382 } 383 384 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog) 385 { 386 const struct btf_type *type, *func, *func_proto; 387 const struct btf *btf = env->prog->aux->btf; 388 u32 btf_id; 389 390 btf_id = env->prog->aux->func_info[subprog].type_id; 391 392 func = btf_type_by_id(btf, btf_id); 393 if (verifier_bug_if(!func, env, "btf_id %u not found", btf_id)) 394 return false; 395 396 func_proto = btf_type_by_id(btf, func->type); 397 if (!func_proto) 398 return false; 399 400 type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 401 if (!type) 402 return false; 403 404 return btf_type_is_void(type); 405 } 406 407 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 408 { 409 struct bpf_func_info *info; 410 411 if (!env->prog->aux->func_info) 412 return ""; 413 414 info = &env->prog->aux->func_info[subprog]; 415 return btf_type_name(env->prog->aux->btf, info->type_id); 416 } 417 418 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 419 { 420 struct bpf_subprog_info *info = subprog_info(env, subprog); 421 422 info->is_cb = true; 423 info->is_async_cb = true; 424 info->is_exception_cb = true; 425 } 426 427 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 428 { 429 return subprog_info(env, subprog)->is_exception_cb; 430 } 431 432 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 433 { 434 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK); 435 } 436 437 static bool type_is_rdonly_mem(u32 type) 438 { 439 return type & MEM_RDONLY; 440 } 441 442 static bool is_acquire_function(enum bpf_func_id func_id, 443 const struct bpf_map *map) 444 { 445 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 446 447 if (func_id == BPF_FUNC_sk_lookup_tcp || 448 func_id == BPF_FUNC_sk_lookup_udp || 449 func_id == BPF_FUNC_skc_lookup_tcp || 450 func_id == BPF_FUNC_ringbuf_reserve || 451 func_id == BPF_FUNC_kptr_xchg) 452 return true; 453 454 if (func_id == BPF_FUNC_map_lookup_elem && 455 (map_type == BPF_MAP_TYPE_SOCKMAP || 456 map_type == BPF_MAP_TYPE_SOCKHASH)) 457 return true; 458 459 return false; 460 } 461 462 static bool is_ptr_cast_function(enum bpf_func_id func_id) 463 { 464 return func_id == BPF_FUNC_tcp_sock || 465 func_id == BPF_FUNC_sk_fullsock || 466 func_id == BPF_FUNC_skc_to_tcp_sock || 467 func_id == BPF_FUNC_skc_to_tcp6_sock || 468 func_id == BPF_FUNC_skc_to_udp6_sock || 469 func_id == BPF_FUNC_skc_to_mptcp_sock || 470 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 471 func_id == BPF_FUNC_skc_to_tcp_request_sock; 472 } 473 474 static bool is_sync_callback_calling_kfunc(u32 btf_id); 475 static bool is_async_callback_calling_kfunc(u32 btf_id); 476 static bool is_callback_calling_kfunc(u32 btf_id); 477 478 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id); 479 static bool is_task_work_add_kfunc(u32 func_id); 480 481 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 482 { 483 return func_id == BPF_FUNC_for_each_map_elem || 484 func_id == BPF_FUNC_find_vma || 485 func_id == BPF_FUNC_loop || 486 func_id == BPF_FUNC_user_ringbuf_drain; 487 } 488 489 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 490 { 491 return func_id == BPF_FUNC_timer_set_callback; 492 } 493 494 static bool is_callback_calling_function(enum bpf_func_id func_id) 495 { 496 return is_sync_callback_calling_function(func_id) || 497 is_async_callback_calling_function(func_id); 498 } 499 500 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn) 501 { 502 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 503 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 504 } 505 506 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn) 507 { 508 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 509 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 510 } 511 512 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn) 513 { 514 /* bpf_timer callbacks are never sleepable. */ 515 if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback) 516 return false; 517 518 /* bpf_wq and bpf_task_work callbacks are always sleepable. */ 519 if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 520 (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm))) 521 return true; 522 523 verifier_bug(env, "unhandled async callback in is_async_cb_sleepable"); 524 return false; 525 } 526 527 bool bpf_is_may_goto_insn(struct bpf_insn *insn) 528 { 529 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 530 } 531 532 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 533 { 534 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 535 536 /* We need to check that slots between [spi - nr_slots + 1, spi] are 537 * within [0, allocated_stack). 538 * 539 * Please note that the spi grows downwards. For example, a dynptr 540 * takes the size of two stack slots; the first slot will be at 541 * spi and the second slot will be at spi - 1. 542 */ 543 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 544 } 545 546 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 547 const char *obj_kind, int nr_slots) 548 { 549 int off, spi; 550 551 if (!tnum_is_const(reg->var_off)) { 552 verbose(env, "%s has to be at a constant offset\n", obj_kind); 553 return -EINVAL; 554 } 555 556 off = reg->var_off.value; 557 if (off % BPF_REG_SIZE) { 558 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 559 return -EINVAL; 560 } 561 562 spi = bpf_get_spi(off); 563 if (spi + 1 < nr_slots) { 564 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 565 return -EINVAL; 566 } 567 568 if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots)) 569 return -ERANGE; 570 return spi; 571 } 572 573 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 574 { 575 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 576 } 577 578 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 579 { 580 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 581 } 582 583 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 584 { 585 return stack_slot_obj_get_spi(env, reg, "irq_flag", 1); 586 } 587 588 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 589 { 590 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 591 case DYNPTR_TYPE_LOCAL: 592 return BPF_DYNPTR_TYPE_LOCAL; 593 case DYNPTR_TYPE_RINGBUF: 594 return BPF_DYNPTR_TYPE_RINGBUF; 595 case DYNPTR_TYPE_SKB: 596 return BPF_DYNPTR_TYPE_SKB; 597 case DYNPTR_TYPE_XDP: 598 return BPF_DYNPTR_TYPE_XDP; 599 case DYNPTR_TYPE_SKB_META: 600 return BPF_DYNPTR_TYPE_SKB_META; 601 case DYNPTR_TYPE_FILE: 602 return BPF_DYNPTR_TYPE_FILE; 603 default: 604 return BPF_DYNPTR_TYPE_INVALID; 605 } 606 } 607 608 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 609 { 610 switch (type) { 611 case BPF_DYNPTR_TYPE_LOCAL: 612 return DYNPTR_TYPE_LOCAL; 613 case BPF_DYNPTR_TYPE_RINGBUF: 614 return DYNPTR_TYPE_RINGBUF; 615 case BPF_DYNPTR_TYPE_SKB: 616 return DYNPTR_TYPE_SKB; 617 case BPF_DYNPTR_TYPE_XDP: 618 return DYNPTR_TYPE_XDP; 619 case BPF_DYNPTR_TYPE_SKB_META: 620 return DYNPTR_TYPE_SKB_META; 621 case BPF_DYNPTR_TYPE_FILE: 622 return DYNPTR_TYPE_FILE; 623 default: 624 return 0; 625 } 626 } 627 628 static bool dynptr_type_referenced(enum bpf_dynptr_type type) 629 { 630 return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE; 631 } 632 633 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 634 enum bpf_dynptr_type type, 635 bool first_slot, int id, int parent_id); 636 637 638 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 639 struct bpf_reg_state *sreg1, 640 struct bpf_reg_state *sreg2, 641 enum bpf_dynptr_type type, int parent_id) 642 { 643 int id = ++env->id_gen; 644 645 __mark_dynptr_reg(sreg1, type, true, id, parent_id); 646 __mark_dynptr_reg(sreg2, type, false, id, parent_id); 647 } 648 649 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 650 struct bpf_reg_state *reg, 651 enum bpf_dynptr_type type) 652 { 653 __mark_dynptr_reg(reg, type, true, ++env->id_gen, 0); 654 } 655 656 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 657 struct bpf_func_state *state, int spi); 658 659 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 660 enum bpf_arg_type arg_type, int insn_idx, 661 struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr) 662 { 663 struct bpf_func_state *state = bpf_func(env, reg); 664 int spi, i, err, parent_id = 0; 665 enum bpf_dynptr_type type; 666 667 spi = dynptr_get_spi(env, reg); 668 if (spi < 0) 669 return spi; 670 671 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 672 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 673 * to ensure that for the following example: 674 * [d1][d1][d2][d2] 675 * spi 3 2 1 0 676 * So marking spi = 2 should lead to destruction of both d1 and d2. In 677 * case they do belong to same dynptr, second call won't see slot_type 678 * as STACK_DYNPTR and will simply skip destruction. 679 */ 680 err = destroy_if_dynptr_stack_slot(env, state, spi); 681 if (err) 682 return err; 683 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 684 if (err) 685 return err; 686 687 for (i = 0; i < BPF_REG_SIZE; i++) { 688 state->stack[spi].slot_type[i] = STACK_DYNPTR; 689 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 690 } 691 692 type = arg_to_dynptr_type(arg_type); 693 if (type == BPF_DYNPTR_TYPE_INVALID) 694 return -EINVAL; 695 696 if (dynptr->type == BPF_DYNPTR_TYPE_INVALID) { /* dynptr constructors */ 697 err = validate_ref_obj(env, ref_obj); 698 if (err) 699 return err; 700 701 /* Track parent's id if the parent is a referenced object */ 702 parent_id = ref_obj->id; 703 704 if (dynptr_type_referenced(type)) { 705 int id; 706 707 /* 708 * Create an intermediate reference that tracks the referenced 709 * object for the referenced dynptr. Freeing a referenced dynptr 710 * through helpers/kfuncs will invalidate all clones. 711 */ 712 id = acquire_reference(env, insn_idx, parent_id); 713 if (id < 0) 714 return id; 715 716 parent_id = id; 717 } 718 } else { /* bpf_dynptr_clone() */ 719 parent_id = dynptr->parent_id; 720 } 721 722 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 723 &state->stack[spi - 1].spilled_ptr, type, parent_id); 724 725 return 0; 726 } 727 728 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_stack_state *stack) 729 { 730 int i; 731 732 for (i = 0; i < BPF_REG_SIZE; i++) { 733 stack[0].slot_type[i] = STACK_INVALID; 734 stack[1].slot_type[i] = STACK_INVALID; 735 } 736 737 bpf_mark_reg_not_init(env, &stack[0].spilled_ptr); 738 bpf_mark_reg_not_init(env, &stack[1].spilled_ptr); 739 } 740 741 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 742 { 743 struct bpf_func_state *state = bpf_func(env, reg); 744 int spi; 745 746 spi = dynptr_get_spi(env, reg); 747 if (spi < 0) 748 return spi; 749 750 /* 751 * For referenced dynptr, release the parent ref which cascades to 752 * all clones and derived slices. For non-referenced dynptr, only 753 * the dynptr and slices derived from it will be invalidated. 754 */ 755 reg = &state->stack[spi].spilled_ptr; 756 return release_reference(env, dynptr_type_referenced(reg->dynptr.type) 757 ? reg->parent_id 758 : reg->id); 759 } 760 761 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 762 struct bpf_reg_state *reg); 763 764 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 765 { 766 if (!env->allow_ptr_leaks) 767 bpf_mark_reg_not_init(env, reg); 768 else 769 __mark_reg_unknown(env, reg); 770 } 771 772 static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id) 773 { 774 struct bpf_stack_state *stack; 775 struct bpf_func_state *state; 776 struct bpf_reg_state *reg; 777 int ref_cnt = 0; 778 779 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({ 780 if (!stack || stack->slot_type[0] != STACK_DYNPTR) 781 continue; 782 if (!stack->spilled_ptr.dynptr.first_slot) 783 continue; 784 if (stack->spilled_ptr.parent_id == v_parent_id) 785 ref_cnt++; 786 })); 787 788 return ref_cnt; 789 } 790 791 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 792 struct bpf_func_state *state, int spi) 793 { 794 int err = 0; 795 796 /* We always ensure that STACK_DYNPTR is never set partially, 797 * hence just checking for slot_type[0] is enough. This is 798 * different for STACK_SPILL, where it may be only set for 799 * 1 byte, so code has to use is_spilled_reg. 800 */ 801 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 802 return 0; 803 804 /* Reposition spi to first slot */ 805 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 806 spi = spi + 1; 807 808 /* 809 * A referenced dynptr can be overwritten only if there is at 810 * least one other dynptr sharing the same virtual ref parent, 811 * ensuring the reference can still be properly released. 812 */ 813 if (dynptr_type_referenced(state->stack[spi].spilled_ptr.dynptr.type) && 814 dynptr_ref_cnt(env, state->stack[spi].spilled_ptr.parent_id) <= 1) { 815 verbose(env, "cannot overwrite referenced dynptr\n"); 816 return -EINVAL; 817 } 818 819 /* Invalidate the dynptr and any derived slices */ 820 err = release_reference(env, state->stack[spi].spilled_ptr.id); 821 if (!err) { 822 mark_stack_slot_scratched(env, spi); 823 mark_stack_slot_scratched(env, spi - 1); 824 } 825 826 return err; 827 } 828 829 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 830 { 831 int spi; 832 833 if (reg->type == CONST_PTR_TO_DYNPTR) 834 return false; 835 836 spi = dynptr_get_spi(env, reg); 837 838 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 839 * error because this just means the stack state hasn't been updated yet. 840 * We will do check_mem_access to check and update stack bounds later. 841 */ 842 if (spi < 0 && spi != -ERANGE) 843 return false; 844 845 /* We don't need to check if the stack slots are marked by previous 846 * dynptr initializations because we allow overwriting existing unreferenced 847 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 848 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 849 * touching are completely destructed before we reinitialize them for a new 850 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 851 * instead of delaying it until the end where the user will get "Unreleased 852 * reference" error. 853 */ 854 return true; 855 } 856 857 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 858 { 859 struct bpf_func_state *state = bpf_func(env, reg); 860 int i, spi; 861 862 /* This already represents first slot of initialized bpf_dynptr. 863 * 864 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 865 * check_func_arg_reg_off's logic, so we don't need to check its 866 * offset and alignment. 867 */ 868 if (reg->type == CONST_PTR_TO_DYNPTR) 869 return true; 870 871 spi = dynptr_get_spi(env, reg); 872 if (spi < 0) 873 return false; 874 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 875 return false; 876 877 for (i = 0; i < BPF_REG_SIZE; i++) { 878 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 879 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 880 return false; 881 } 882 883 return true; 884 } 885 886 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 887 enum bpf_arg_type arg_type) 888 { 889 struct bpf_func_state *state = bpf_func(env, reg); 890 enum bpf_dynptr_type dynptr_type; 891 int spi; 892 893 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 894 if (arg_type == ARG_PTR_TO_DYNPTR) 895 return true; 896 897 dynptr_type = arg_to_dynptr_type(arg_type); 898 if (reg->type == CONST_PTR_TO_DYNPTR) { 899 return reg->dynptr.type == dynptr_type; 900 } else { 901 spi = dynptr_get_spi(env, reg); 902 if (spi < 0) 903 return false; 904 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 905 } 906 } 907 908 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 909 910 static bool in_rcu_cs(struct bpf_verifier_env *env); 911 912 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta); 913 914 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 915 struct bpf_call_arg_meta *meta, 916 struct bpf_reg_state *reg, int insn_idx, 917 struct btf *btf, u32 btf_id, int nr_slots) 918 { 919 struct bpf_func_state *state = bpf_func(env, reg); 920 int spi, i, j, id; 921 922 spi = iter_get_spi(env, reg, nr_slots); 923 if (spi < 0) 924 return spi; 925 926 id = acquire_reference(env, insn_idx, 0); 927 if (id < 0) 928 return id; 929 930 for (i = 0; i < nr_slots; i++) { 931 struct bpf_stack_state *slot = &state->stack[spi - i]; 932 struct bpf_reg_state *st = &slot->spilled_ptr; 933 934 __mark_reg_known_zero(st); 935 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 936 if (is_kfunc_rcu_protected(meta)) { 937 if (in_rcu_cs(env)) 938 st->type |= MEM_RCU; 939 else 940 st->type |= PTR_UNTRUSTED; 941 } 942 st->id = i == 0 ? id : 0; 943 st->iter.btf = btf; 944 st->iter.btf_id = btf_id; 945 st->iter.state = BPF_ITER_STATE_ACTIVE; 946 st->iter.depth = 0; 947 948 for (j = 0; j < BPF_REG_SIZE; j++) 949 slot->slot_type[j] = STACK_ITER; 950 951 mark_stack_slot_scratched(env, spi - i); 952 } 953 954 return 0; 955 } 956 957 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 958 struct bpf_reg_state *reg, int nr_slots) 959 { 960 struct bpf_func_state *state = bpf_func(env, reg); 961 int spi, i, j; 962 963 spi = iter_get_spi(env, reg, nr_slots); 964 if (spi < 0) 965 return spi; 966 967 for (i = 0; i < nr_slots; i++) { 968 struct bpf_stack_state *slot = &state->stack[spi - i]; 969 struct bpf_reg_state *st = &slot->spilled_ptr; 970 971 if (i == 0) 972 WARN_ON_ONCE(release_reference(env, st->id)); 973 974 bpf_mark_reg_not_init(env, st); 975 976 for (j = 0; j < BPF_REG_SIZE; j++) 977 slot->slot_type[j] = STACK_INVALID; 978 979 mark_stack_slot_scratched(env, spi - i); 980 } 981 982 return 0; 983 } 984 985 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 986 struct bpf_reg_state *reg, int nr_slots) 987 { 988 struct bpf_func_state *state = bpf_func(env, reg); 989 int spi, i, j; 990 991 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 992 * will do check_mem_access to check and update stack bounds later, so 993 * return true for that case. 994 */ 995 spi = iter_get_spi(env, reg, nr_slots); 996 if (spi == -ERANGE) 997 return true; 998 if (spi < 0) 999 return false; 1000 1001 for (i = 0; i < nr_slots; i++) { 1002 struct bpf_stack_state *slot = &state->stack[spi - i]; 1003 1004 for (j = 0; j < BPF_REG_SIZE; j++) 1005 if (slot->slot_type[j] == STACK_ITER) 1006 return false; 1007 } 1008 1009 return true; 1010 } 1011 1012 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1013 struct btf *btf, u32 btf_id, int nr_slots) 1014 { 1015 struct bpf_func_state *state = bpf_func(env, reg); 1016 int spi, i, j; 1017 1018 spi = iter_get_spi(env, reg, nr_slots); 1019 if (spi < 0) 1020 return -EINVAL; 1021 1022 for (i = 0; i < nr_slots; i++) { 1023 struct bpf_stack_state *slot = &state->stack[spi - i]; 1024 struct bpf_reg_state *st = &slot->spilled_ptr; 1025 1026 if (st->type & PTR_UNTRUSTED) 1027 return -EPROTO; 1028 /* only main (first) slot has id set */ 1029 if (i == 0 && !st->id) 1030 return -EINVAL; 1031 if (i != 0 && st->id) 1032 return -EINVAL; 1033 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1034 return -EINVAL; 1035 1036 for (j = 0; j < BPF_REG_SIZE; j++) 1037 if (slot->slot_type[j] != STACK_ITER) 1038 return -EINVAL; 1039 } 1040 1041 return 0; 1042 } 1043 1044 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx); 1045 static int release_irq_state(struct bpf_verifier_state *state, int id); 1046 1047 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env, 1048 struct bpf_call_arg_meta *meta, 1049 struct bpf_reg_state *reg, int insn_idx, 1050 int kfunc_class) 1051 { 1052 struct bpf_func_state *state = bpf_func(env, reg); 1053 struct bpf_stack_state *slot; 1054 struct bpf_reg_state *st; 1055 int spi, i, id; 1056 1057 spi = irq_flag_get_spi(env, reg); 1058 if (spi < 0) 1059 return spi; 1060 1061 id = acquire_irq_state(env, insn_idx); 1062 if (id < 0) 1063 return id; 1064 1065 slot = &state->stack[spi]; 1066 st = &slot->spilled_ptr; 1067 1068 __mark_reg_known_zero(st); 1069 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1070 st->id = id; 1071 st->irq.kfunc_class = kfunc_class; 1072 1073 for (i = 0; i < BPF_REG_SIZE; i++) 1074 slot->slot_type[i] = STACK_IRQ_FLAG; 1075 1076 mark_stack_slot_scratched(env, spi); 1077 return 0; 1078 } 1079 1080 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1081 int kfunc_class) 1082 { 1083 struct bpf_func_state *state = bpf_func(env, reg); 1084 struct bpf_stack_state *slot; 1085 struct bpf_reg_state *st; 1086 int spi, i, err; 1087 1088 spi = irq_flag_get_spi(env, reg); 1089 if (spi < 0) 1090 return spi; 1091 1092 slot = &state->stack[spi]; 1093 st = &slot->spilled_ptr; 1094 1095 if (st->irq.kfunc_class != kfunc_class) { 1096 const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1097 const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1098 1099 verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n", 1100 flag_kfunc, used_kfunc); 1101 return -EINVAL; 1102 } 1103 1104 err = release_irq_state(env->cur_state, st->id); 1105 WARN_ON_ONCE(err && err != -EACCES); 1106 if (err) { 1107 int insn_idx = 0; 1108 1109 for (int i = 0; i < env->cur_state->acquired_refs; i++) { 1110 if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) { 1111 insn_idx = env->cur_state->refs[i].insn_idx; 1112 break; 1113 } 1114 } 1115 1116 verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n", 1117 env->cur_state->active_irq_id, insn_idx); 1118 return err; 1119 } 1120 1121 bpf_mark_reg_not_init(env, st); 1122 1123 for (i = 0; i < BPF_REG_SIZE; i++) 1124 slot->slot_type[i] = STACK_INVALID; 1125 1126 mark_stack_slot_scratched(env, spi); 1127 return 0; 1128 } 1129 1130 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1131 { 1132 struct bpf_func_state *state = bpf_func(env, reg); 1133 struct bpf_stack_state *slot; 1134 int spi, i; 1135 1136 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1137 * will do check_mem_access to check and update stack bounds later, so 1138 * return true for that case. 1139 */ 1140 spi = irq_flag_get_spi(env, reg); 1141 if (spi == -ERANGE) 1142 return true; 1143 if (spi < 0) 1144 return false; 1145 1146 slot = &state->stack[spi]; 1147 1148 for (i = 0; i < BPF_REG_SIZE; i++) 1149 if (slot->slot_type[i] == STACK_IRQ_FLAG) 1150 return false; 1151 return true; 1152 } 1153 1154 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1155 { 1156 struct bpf_func_state *state = bpf_func(env, reg); 1157 struct bpf_stack_state *slot; 1158 struct bpf_reg_state *st; 1159 int spi, i; 1160 1161 spi = irq_flag_get_spi(env, reg); 1162 if (spi < 0) 1163 return -EINVAL; 1164 1165 slot = &state->stack[spi]; 1166 st = &slot->spilled_ptr; 1167 1168 if (!st->id) 1169 return -EINVAL; 1170 1171 for (i = 0; i < BPF_REG_SIZE; i++) 1172 if (slot->slot_type[i] != STACK_IRQ_FLAG) 1173 return -EINVAL; 1174 return 0; 1175 } 1176 1177 /* Check if given stack slot is "special": 1178 * - spilled register state (STACK_SPILL); 1179 * - dynptr state (STACK_DYNPTR); 1180 * - iter state (STACK_ITER). 1181 * - irq flag state (STACK_IRQ_FLAG) 1182 */ 1183 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1184 { 1185 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1186 1187 switch (type) { 1188 case STACK_SPILL: 1189 case STACK_DYNPTR: 1190 case STACK_ITER: 1191 case STACK_IRQ_FLAG: 1192 return true; 1193 case STACK_INVALID: 1194 case STACK_POISON: 1195 case STACK_MISC: 1196 case STACK_ZERO: 1197 return false; 1198 default: 1199 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1200 return true; 1201 } 1202 } 1203 1204 /* The reg state of a pointer or a bounded scalar was saved when 1205 * it was spilled to the stack. 1206 */ 1207 1208 /* 1209 * Mark stack slot as STACK_MISC, unless it is already: 1210 * - STACK_INVALID, in which case they are equivalent. 1211 * - STACK_ZERO, in which case we preserve more precise STACK_ZERO. 1212 * - STACK_POISON, which truly forbids access to the slot. 1213 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged 1214 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is 1215 * unnecessary as both are considered equivalent when loading data and pruning, 1216 * in case of unprivileged mode it will be incorrect to allow reads of invalid 1217 * slots. 1218 */ 1219 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1220 { 1221 if (*stype == STACK_ZERO) 1222 return; 1223 if (*stype == STACK_INVALID || *stype == STACK_POISON) 1224 return; 1225 *stype = STACK_MISC; 1226 } 1227 1228 static void scrub_spilled_slot(u8 *stype) 1229 { 1230 if (*stype != STACK_INVALID && *stype != STACK_POISON) 1231 *stype = STACK_MISC; 1232 } 1233 1234 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1235 * small to hold src. This is different from krealloc since we don't want to preserve 1236 * the contents of dst. 1237 * 1238 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1239 * not be allocated. 1240 */ 1241 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1242 { 1243 size_t alloc_bytes; 1244 void *orig = dst; 1245 size_t bytes; 1246 1247 if (ZERO_OR_NULL_PTR(src)) 1248 goto out; 1249 1250 if (unlikely(check_mul_overflow(n, size, &bytes))) 1251 return NULL; 1252 1253 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1254 dst = krealloc(orig, alloc_bytes, flags); 1255 if (!dst) { 1256 kfree(orig); 1257 return NULL; 1258 } 1259 1260 memcpy(dst, src, bytes); 1261 out: 1262 return dst ? dst : ZERO_SIZE_PTR; 1263 } 1264 1265 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1266 * small to hold new_n items. new items are zeroed out if the array grows. 1267 * 1268 * Contrary to krealloc_array, does not free arr if new_n is zero. 1269 */ 1270 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1271 { 1272 size_t alloc_size; 1273 void *new_arr; 1274 1275 if (!new_n || old_n == new_n) 1276 goto out; 1277 1278 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1279 new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT); 1280 if (!new_arr) { 1281 kfree(arr); 1282 return NULL; 1283 } 1284 arr = new_arr; 1285 1286 if (new_n > old_n) 1287 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1288 1289 out: 1290 return arr ? arr : ZERO_SIZE_PTR; 1291 } 1292 1293 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) 1294 { 1295 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1296 sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT); 1297 if (!dst->refs) 1298 return -ENOMEM; 1299 1300 dst->acquired_refs = src->acquired_refs; 1301 dst->active_locks = src->active_locks; 1302 dst->active_preempt_locks = src->active_preempt_locks; 1303 dst->active_rcu_locks = src->active_rcu_locks; 1304 dst->active_irq_id = src->active_irq_id; 1305 dst->active_lock_id = src->active_lock_id; 1306 dst->active_lock_ptr = src->active_lock_ptr; 1307 return 0; 1308 } 1309 1310 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1311 { 1312 size_t n = src->allocated_stack / BPF_REG_SIZE; 1313 1314 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1315 GFP_KERNEL_ACCOUNT); 1316 if (!dst->stack) 1317 return -ENOMEM; 1318 1319 dst->allocated_stack = src->allocated_stack; 1320 1321 /* copy stack args state */ 1322 n = src->out_stack_arg_cnt; 1323 if (n) { 1324 dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n, 1325 sizeof(struct bpf_reg_state), 1326 GFP_KERNEL_ACCOUNT); 1327 if (!dst->stack_arg_regs) 1328 return -ENOMEM; 1329 } 1330 1331 dst->out_stack_arg_cnt = src->out_stack_arg_cnt; 1332 return 0; 1333 } 1334 1335 static int resize_reference_state(struct bpf_verifier_state *state, size_t n) 1336 { 1337 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1338 sizeof(struct bpf_reference_state)); 1339 if (!state->refs) 1340 return -ENOMEM; 1341 1342 state->acquired_refs = n; 1343 return 0; 1344 } 1345 1346 /* Possibly update state->allocated_stack to be at least size bytes. Also 1347 * possibly update the function's high-water mark in its bpf_subprog_info. 1348 */ 1349 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1350 { 1351 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1352 1353 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1354 size = round_up(size, BPF_REG_SIZE); 1355 n = size / BPF_REG_SIZE; 1356 1357 if (old_n >= n) 1358 return 0; 1359 1360 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1361 if (!state->stack) 1362 return -ENOMEM; 1363 1364 state->allocated_stack = size; 1365 1366 /* update known max for given subprogram */ 1367 if (env->subprog_info[state->subprogno].stack_depth < size) 1368 env->subprog_info[state->subprogno].stack_depth = size; 1369 1370 return 0; 1371 } 1372 1373 static int grow_stack_arg_slots(struct bpf_verifier_env *env, 1374 struct bpf_func_state *state, int cnt) 1375 { 1376 size_t old_n = state->out_stack_arg_cnt; 1377 1378 if (old_n >= cnt) 1379 return 0; 1380 1381 state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt, 1382 sizeof(struct bpf_reg_state)); 1383 if (!state->stack_arg_regs) 1384 return -ENOMEM; 1385 1386 state->out_stack_arg_cnt = cnt; 1387 return 0; 1388 } 1389 1390 /* Acquire a pointer id from the env and update the state->refs to include 1391 * this new pointer reference. 1392 * On success, returns a valid pointer id to associate with the register 1393 * On failure, returns a negative errno. 1394 */ 1395 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1396 { 1397 struct bpf_verifier_state *state = env->cur_state; 1398 int new_ofs = state->acquired_refs; 1399 int err; 1400 1401 err = resize_reference_state(state, state->acquired_refs + 1); 1402 if (err) 1403 return NULL; 1404 state->refs[new_ofs].insn_idx = insn_idx; 1405 1406 return &state->refs[new_ofs]; 1407 } 1408 1409 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id) 1410 { 1411 struct bpf_reference_state *s; 1412 1413 s = acquire_reference_state(env, insn_idx); 1414 if (!s) 1415 return -ENOMEM; 1416 s->type = REF_TYPE_PTR; 1417 s->id = ++env->id_gen; 1418 s->parent_id = parent_id; 1419 return s->id; 1420 } 1421 1422 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type, 1423 int id, void *ptr) 1424 { 1425 struct bpf_verifier_state *state = env->cur_state; 1426 struct bpf_reference_state *s; 1427 1428 s = acquire_reference_state(env, insn_idx); 1429 if (!s) 1430 return -ENOMEM; 1431 s->type = type; 1432 s->id = id; 1433 s->ptr = ptr; 1434 1435 state->active_locks++; 1436 state->active_lock_id = id; 1437 state->active_lock_ptr = ptr; 1438 return 0; 1439 } 1440 1441 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx) 1442 { 1443 struct bpf_verifier_state *state = env->cur_state; 1444 struct bpf_reference_state *s; 1445 1446 s = acquire_reference_state(env, insn_idx); 1447 if (!s) 1448 return -ENOMEM; 1449 s->type = REF_TYPE_IRQ; 1450 s->id = ++env->id_gen; 1451 1452 state->active_irq_id = s->id; 1453 return s->id; 1454 } 1455 1456 static void release_reference_state(struct bpf_verifier_state *state, int idx) 1457 { 1458 int last_idx; 1459 size_t rem; 1460 1461 /* IRQ state requires the relative ordering of elements remaining the 1462 * same, since it relies on the refs array to behave as a stack, so that 1463 * it can detect out-of-order IRQ restore. Hence use memmove to shift 1464 * the array instead of swapping the final element into the deleted idx. 1465 */ 1466 last_idx = state->acquired_refs - 1; 1467 rem = state->acquired_refs - idx - 1; 1468 if (last_idx && idx != last_idx) 1469 memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem); 1470 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1471 state->acquired_refs--; 1472 return; 1473 } 1474 1475 static bool find_reference_state(struct bpf_verifier_state *state, int id) 1476 { 1477 int i; 1478 1479 for (i = 0; i < state->acquired_refs; i++) { 1480 if (state->refs[i].type != REF_TYPE_PTR) 1481 continue; 1482 if (state->refs[i].id == id) 1483 return true; 1484 } 1485 1486 return false; 1487 } 1488 1489 static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 1490 { 1491 return find_reference_state(env->cur_state, reg->id); 1492 } 1493 1494 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr) 1495 { 1496 void *prev_ptr = NULL; 1497 u32 prev_id = 0; 1498 int i; 1499 1500 for (i = 0; i < state->acquired_refs; i++) { 1501 if (state->refs[i].type == type && state->refs[i].id == id && 1502 state->refs[i].ptr == ptr) { 1503 release_reference_state(state, i); 1504 state->active_locks--; 1505 /* Reassign active lock (id, ptr). */ 1506 state->active_lock_id = prev_id; 1507 state->active_lock_ptr = prev_ptr; 1508 return 0; 1509 } 1510 if (state->refs[i].type & REF_TYPE_LOCK_MASK) { 1511 prev_id = state->refs[i].id; 1512 prev_ptr = state->refs[i].ptr; 1513 } 1514 } 1515 return -EINVAL; 1516 } 1517 1518 static int release_irq_state(struct bpf_verifier_state *state, int id) 1519 { 1520 u32 prev_id = 0; 1521 int i; 1522 1523 if (id != state->active_irq_id) 1524 return -EACCES; 1525 1526 for (i = 0; i < state->acquired_refs; i++) { 1527 if (state->refs[i].type != REF_TYPE_IRQ) 1528 continue; 1529 if (state->refs[i].id == id) { 1530 release_reference_state(state, i); 1531 state->active_irq_id = prev_id; 1532 return 0; 1533 } else { 1534 prev_id = state->refs[i].id; 1535 } 1536 } 1537 return -EINVAL; 1538 } 1539 1540 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type, 1541 int id, void *ptr) 1542 { 1543 int i; 1544 1545 for (i = 0; i < state->acquired_refs; i++) { 1546 struct bpf_reference_state *s = &state->refs[i]; 1547 1548 if (!(s->type & type)) 1549 continue; 1550 1551 if (s->id == id && s->ptr == ptr) 1552 return s; 1553 } 1554 return NULL; 1555 } 1556 1557 static void free_func_state(struct bpf_func_state *state) 1558 { 1559 if (!state) 1560 return; 1561 kfree(state->stack_arg_regs); 1562 kfree(state->stack); 1563 kfree(state); 1564 } 1565 1566 void bpf_clear_jmp_history(struct bpf_verifier_state *state) 1567 { 1568 kfree(state->jmp_history); 1569 state->jmp_history = NULL; 1570 state->jmp_history_cnt = 0; 1571 } 1572 1573 void bpf_free_verifier_state(struct bpf_verifier_state *state, 1574 bool free_self) 1575 { 1576 int i; 1577 1578 for (i = 0; i <= state->curframe; i++) { 1579 free_func_state(state->frame[i]); 1580 state->frame[i] = NULL; 1581 } 1582 kfree(state->refs); 1583 bpf_clear_jmp_history(state); 1584 if (free_self) 1585 kfree(state); 1586 } 1587 1588 /* copy verifier state from src to dst growing dst stack space 1589 * when necessary to accommodate larger src stack 1590 */ 1591 static int copy_func_state(struct bpf_func_state *dst, 1592 const struct bpf_func_state *src) 1593 { 1594 memcpy(dst, src, offsetof(struct bpf_func_state, stack)); 1595 return copy_stack_state(dst, src); 1596 } 1597 1598 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state, 1599 const struct bpf_verifier_state *src) 1600 { 1601 struct bpf_func_state *dst; 1602 int i, err; 1603 1604 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1605 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1606 GFP_KERNEL_ACCOUNT); 1607 if (!dst_state->jmp_history) 1608 return -ENOMEM; 1609 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1610 1611 /* if dst has more stack frames then src frame, free them, this is also 1612 * necessary in case of exceptional exits using bpf_throw. 1613 */ 1614 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1615 free_func_state(dst_state->frame[i]); 1616 dst_state->frame[i] = NULL; 1617 } 1618 err = copy_reference_state(dst_state, src); 1619 if (err) 1620 return err; 1621 dst_state->speculative = src->speculative; 1622 dst_state->in_sleepable = src->in_sleepable; 1623 dst_state->curframe = src->curframe; 1624 dst_state->branches = src->branches; 1625 dst_state->parent = src->parent; 1626 dst_state->first_insn_idx = src->first_insn_idx; 1627 dst_state->last_insn_idx = src->last_insn_idx; 1628 dst_state->dfs_depth = src->dfs_depth; 1629 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1630 dst_state->may_goto_depth = src->may_goto_depth; 1631 dst_state->equal_state = src->equal_state; 1632 for (i = 0; i <= src->curframe; i++) { 1633 dst = dst_state->frame[i]; 1634 if (!dst) { 1635 dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT); 1636 if (!dst) 1637 return -ENOMEM; 1638 dst_state->frame[i] = dst; 1639 } 1640 err = copy_func_state(dst, src->frame[i]); 1641 if (err) 1642 return err; 1643 } 1644 return 0; 1645 } 1646 1647 static u32 state_htab_size(struct bpf_verifier_env *env) 1648 { 1649 return env->prog->len; 1650 } 1651 1652 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx) 1653 { 1654 struct bpf_verifier_state *cur = env->cur_state; 1655 struct bpf_func_state *state = cur->frame[cur->curframe]; 1656 1657 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1658 } 1659 1660 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1661 { 1662 int fr; 1663 1664 if (a->curframe != b->curframe) 1665 return false; 1666 1667 for (fr = a->curframe; fr >= 0; fr--) 1668 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1669 return false; 1670 1671 return true; 1672 } 1673 1674 1675 void bpf_free_backedges(struct bpf_scc_visit *visit) 1676 { 1677 struct bpf_scc_backedge *backedge, *next; 1678 1679 for (backedge = visit->backedges; backedge; backedge = next) { 1680 bpf_free_verifier_state(&backedge->state, false); 1681 next = backedge->next; 1682 kfree(backedge); 1683 } 1684 visit->backedges = NULL; 1685 } 1686 1687 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1688 int *insn_idx, bool pop_log) 1689 { 1690 struct bpf_verifier_state *cur = env->cur_state; 1691 struct bpf_verifier_stack_elem *elem, *head = env->head; 1692 int err; 1693 1694 if (env->head == NULL) 1695 return -ENOENT; 1696 1697 if (cur) { 1698 err = bpf_copy_verifier_state(cur, &head->st); 1699 if (err) 1700 return err; 1701 } 1702 if (pop_log) 1703 bpf_vlog_reset(&env->log, head->log_pos); 1704 if (insn_idx) 1705 *insn_idx = head->insn_idx; 1706 if (prev_insn_idx) 1707 *prev_insn_idx = head->prev_insn_idx; 1708 elem = head->next; 1709 bpf_free_verifier_state(&head->st, false); 1710 kfree(head); 1711 env->head = elem; 1712 env->stack_size--; 1713 return 0; 1714 } 1715 1716 static bool error_recoverable_with_nospec(int err) 1717 { 1718 /* Should only return true for non-fatal errors that are allowed to 1719 * occur during speculative verification. For these we can insert a 1720 * nospec and the program might still be accepted. Do not include 1721 * something like ENOMEM because it is likely to re-occur for the next 1722 * architectural path once it has been recovered-from in all speculative 1723 * paths. 1724 */ 1725 return err == -EPERM || err == -EACCES || err == -EINVAL; 1726 } 1727 1728 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1729 int insn_idx, int prev_insn_idx, 1730 bool speculative) 1731 { 1732 struct bpf_verifier_state *cur = env->cur_state; 1733 struct bpf_verifier_stack_elem *elem; 1734 int err; 1735 1736 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 1737 if (!elem) 1738 return ERR_PTR(-ENOMEM); 1739 1740 elem->insn_idx = insn_idx; 1741 elem->prev_insn_idx = prev_insn_idx; 1742 elem->next = env->head; 1743 elem->log_pos = env->log.end_pos; 1744 env->head = elem; 1745 env->stack_size++; 1746 err = bpf_copy_verifier_state(&elem->st, cur); 1747 if (err) 1748 return ERR_PTR(-ENOMEM); 1749 elem->st.speculative |= speculative; 1750 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1751 verbose(env, "The sequence of %d jumps is too complex.\n", 1752 env->stack_size); 1753 return ERR_PTR(-E2BIG); 1754 } 1755 if (elem->st.parent) { 1756 ++elem->st.parent->branches; 1757 /* WARN_ON(branches > 2) technically makes sense here, 1758 * but 1759 * 1. speculative states will bump 'branches' for non-branch 1760 * instructions 1761 * 2. is_state_visited() heuristics may decide not to create 1762 * a new state for a sequence of branches and all such current 1763 * and cloned states will be pointing to a single parent state 1764 * which might have large 'branches' count. 1765 */ 1766 } 1767 return &elem->st; 1768 } 1769 1770 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno) 1771 { 1772 char *buf = env->tmp_arg_name; 1773 int len = sizeof(env->tmp_arg_name); 1774 int arg, regno = reg_from_argno(argno); 1775 1776 if (regno >= 0) { 1777 snprintf(buf, len, "R%d", regno); 1778 } else { 1779 arg = arg_from_argno(argno); 1780 snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE); 1781 } 1782 1783 return buf; 1784 } 1785 1786 static const int caller_saved[CALLER_SAVED_REGS] = { 1787 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1788 }; 1789 1790 /* This helper doesn't clear reg->id */ 1791 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1792 { 1793 reg->var_off = tnum_const(imm); 1794 reg->r64 = cnum64_from_urange(imm, imm); 1795 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 1796 } 1797 1798 /* Mark the unknown part of a register (variable offset or scalar value) as 1799 * known to have the value @imm. 1800 */ 1801 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1802 { 1803 /* Clear off and union(map_ptr, range) */ 1804 memset(((u8 *)reg) + sizeof(reg->type), 0, 1805 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1806 reg->id = 0; 1807 reg->parent_id = 0; 1808 ___mark_reg_known(reg, imm); 1809 } 1810 1811 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1812 { 1813 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1814 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 1815 } 1816 1817 /* Mark the 'variable offset' part of a register as zero. This should be 1818 * used only on registers holding a pointer type. 1819 */ 1820 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1821 { 1822 __mark_reg_known(reg, 0); 1823 } 1824 1825 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1826 { 1827 __mark_reg_known(reg, 0); 1828 reg->type = SCALAR_VALUE; 1829 /* all scalars are assumed imprecise initially (unless unprivileged, 1830 * in which case everything is forced to be precise) 1831 */ 1832 reg->precise = !env->bpf_capable; 1833 } 1834 1835 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1836 struct bpf_reg_state *regs, u32 regno) 1837 { 1838 __mark_reg_known_zero(regs + regno); 1839 } 1840 1841 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1842 bool first_slot, int id, int parent_id) 1843 { 1844 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1845 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1846 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1847 */ 1848 __mark_reg_known_zero(reg); 1849 reg->type = CONST_PTR_TO_DYNPTR; 1850 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1851 reg->id = id; 1852 reg->parent_id = parent_id; 1853 reg->dynptr.type = type; 1854 reg->dynptr.first_slot = first_slot; 1855 } 1856 1857 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1858 { 1859 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1860 const struct bpf_map *map = reg->map_ptr; 1861 1862 if (map->inner_map_meta) { 1863 reg->type = CONST_PTR_TO_MAP; 1864 reg->map_ptr = map->inner_map_meta; 1865 /* transfer reg's id which is unique for every map_lookup_elem 1866 * as UID of the inner map. 1867 */ 1868 if (btf_record_has_field(map->inner_map_meta->record, 1869 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) { 1870 reg->map_uid = reg->id; 1871 } 1872 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1873 reg->type = PTR_TO_XDP_SOCK; 1874 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1875 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1876 reg->type = PTR_TO_SOCKET; 1877 } else { 1878 reg->type = PTR_TO_MAP_VALUE; 1879 } 1880 return; 1881 } 1882 1883 reg->type &= ~PTR_MAYBE_NULL; 1884 } 1885 1886 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1887 struct btf_field_graph_root *ds_head) 1888 { 1889 __mark_reg_known(®s[regno], ds_head->node_offset); 1890 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1891 regs[regno].btf = ds_head->btf; 1892 regs[regno].btf_id = ds_head->value_btf_id; 1893 } 1894 1895 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1896 { 1897 return type_is_pkt_pointer(reg->type); 1898 } 1899 1900 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1901 { 1902 return reg_is_pkt_pointer(reg) || 1903 reg->type == PTR_TO_PACKET_END; 1904 } 1905 1906 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1907 { 1908 return base_type(reg->type) == PTR_TO_MEM && 1909 (reg->type & 1910 (DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META)); 1911 } 1912 1913 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1914 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1915 enum bpf_reg_type which) 1916 { 1917 /* The register can already have a range from prior markings. 1918 * This is fine as long as it hasn't been advanced from its 1919 * origin. 1920 */ 1921 return reg->type == which && 1922 reg->id == 0 && 1923 tnum_equals_const(reg->var_off, 0); 1924 } 1925 1926 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1927 { 1928 reg->r32 = CNUM32_UNBOUNDED; 1929 } 1930 1931 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1932 { 1933 reg->r64 = CNUM64_UNBOUNDED; 1934 } 1935 1936 /* Reset the min/max bounds of a register */ 1937 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1938 { 1939 __mark_reg64_unbounded(reg); 1940 __mark_reg32_unbounded(reg); 1941 } 1942 1943 static void reset_reg64_and_tnum(struct bpf_reg_state *reg) 1944 { 1945 __mark_reg64_unbounded(reg); 1946 reg->var_off = tnum_unknown; 1947 } 1948 1949 static void reset_reg32_and_tnum(struct bpf_reg_state *reg) 1950 { 1951 __mark_reg32_unbounded(reg); 1952 reg->var_off = tnum_unknown; 1953 } 1954 1955 static struct cnum32 cnum32_from_tnum(struct tnum tnum) 1956 { 1957 tnum = tnum_subreg(tnum); 1958 if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN)) 1959 /* min signed is max(sign bit) | min(other bits) */ 1960 /* max signed is min(sign bit) | max(other bits) */ 1961 return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN), 1962 tnum.value | (tnum.mask & S32_MAX)); 1963 else 1964 return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask)); 1965 } 1966 1967 static struct cnum64 cnum64_from_tnum(struct tnum tnum) 1968 { 1969 if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN)) 1970 /* min signed is max(sign bit) | min(other bits) */ 1971 /* max signed is min(sign bit) | max(other bits) */ 1972 return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN), 1973 tnum.value | (tnum.mask & S64_MAX)); 1974 else 1975 return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask)); 1976 } 1977 1978 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1979 { 1980 cnum32_intersect_with(®->r32, cnum32_from_tnum(reg->var_off)); 1981 } 1982 1983 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1984 { 1985 u64 tnum_next, tmax; 1986 bool umin_in_tnum; 1987 1988 cnum64_intersect_with(®->r64, cnum64_from_tnum(reg->var_off)); 1989 1990 /* Check if u64 and tnum overlap in a single value */ 1991 tnum_next = tnum_step(reg->var_off, reg_umin(reg)); 1992 umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value; 1993 tmax = reg->var_off.value | reg->var_off.mask; 1994 if (umin_in_tnum && tnum_next > reg_umax(reg)) { 1995 /* The u64 range and the tnum only overlap in umin. 1996 * u64: ---[xxxxxx]----- 1997 * tnum: --xx----------x- 1998 */ 1999 ___mark_reg_known(reg, reg_umin(reg)); 2000 } else if (!umin_in_tnum && tnum_next == tmax) { 2001 /* The u64 range and the tnum only overlap in the maximum value 2002 * represented by the tnum, called tmax. 2003 * u64: ---[xxxxxx]----- 2004 * tnum: xx-----x-------- 2005 */ 2006 ___mark_reg_known(reg, tmax); 2007 } else if (!umin_in_tnum && tnum_next <= reg_umax(reg) && 2008 tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) { 2009 /* The u64 range and the tnum only overlap in between umin 2010 * (excluded) and umax. 2011 * u64: ---[xxxxxx]----- 2012 * tnum: xx----x-------x- 2013 */ 2014 ___mark_reg_known(reg, tnum_next); 2015 } 2016 } 2017 2018 static void __update_reg_bounds(struct bpf_reg_state *reg) 2019 { 2020 __update_reg32_bounds(reg); 2021 __update_reg64_bounds(reg); 2022 } 2023 2024 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg) 2025 { 2026 cnum32_intersect_with(®->r32, cnum32_from_cnum64(reg->r64)); 2027 } 2028 2029 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg) 2030 { 2031 reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32); 2032 } 2033 2034 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2035 { 2036 deduce_bounds_32_from_64(reg); 2037 deduce_bounds_64_from_32(reg); 2038 } 2039 2040 /* Attempts to improve var_off based on unsigned min/max information */ 2041 static void __reg_bound_offset(struct bpf_reg_state *reg) 2042 { 2043 struct tnum var64_off = tnum_intersect(reg->var_off, 2044 tnum_range(reg_umin(reg), 2045 reg_umax(reg))); 2046 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2047 tnum_range(reg_u32_min(reg), 2048 reg_u32_max(reg))); 2049 2050 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2051 } 2052 2053 static bool range_bounds_violation(struct bpf_reg_state *reg); 2054 2055 static void reg_bounds_sync(struct bpf_reg_state *reg) 2056 { 2057 /* If the input reg_state is invalid, we can exit early */ 2058 if (range_bounds_violation(reg)) 2059 return; 2060 /* We might have learned new bounds from the var_off. */ 2061 __update_reg_bounds(reg); 2062 /* We might have learned something about the sign bit. */ 2063 __reg_deduce_bounds(reg); 2064 __reg_deduce_bounds(reg); 2065 /* We might have learned some bits from the bounds. */ 2066 __reg_bound_offset(reg); 2067 /* Intersecting with the old var_off might have improved our bounds 2068 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2069 * then new var_off is (0; 0x7f...fc) which improves our umax. 2070 */ 2071 __update_reg_bounds(reg); 2072 } 2073 2074 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg) 2075 { 2076 if (!tnum_is_const(reg->var_off)) 2077 return false; 2078 2079 return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value; 2080 } 2081 2082 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg) 2083 { 2084 if (!tnum_subreg_is_const(reg->var_off)) 2085 return false; 2086 2087 return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value; 2088 } 2089 2090 static bool range_bounds_violation(struct bpf_reg_state *reg) 2091 { 2092 return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64); 2093 } 2094 2095 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2096 struct bpf_reg_state *reg, const char *ctx) 2097 { 2098 const char *msg; 2099 2100 if (range_bounds_violation(reg)) { 2101 msg = "range bounds violation"; 2102 goto out; 2103 } 2104 2105 if (const_tnum_range_mismatch(reg)) { 2106 msg = "const tnum out of sync with range bounds"; 2107 goto out; 2108 } 2109 2110 if (const_tnum_range_mismatch_32(reg)) { 2111 msg = "const subreg tnum out of sync with range bounds"; 2112 goto out; 2113 } 2114 2115 return 0; 2116 out: 2117 verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} " 2118 "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx)", 2119 ctx, msg, 2120 reg->r64.base, reg->r64.size, 2121 reg->r32.base, reg->r32.size, 2122 reg->var_off.value, reg->var_off.mask); 2123 if (env->test_reg_invariants) 2124 return -EFAULT; 2125 __mark_reg_unbounded(reg); 2126 return 0; 2127 } 2128 2129 /* Mark a register as having a completely unknown (scalar) value. */ 2130 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2131 { 2132 s32 subreg_def = reg->subreg_def; 2133 2134 memset(reg, 0, sizeof(*reg)); 2135 reg->type = SCALAR_VALUE; 2136 reg->var_off = tnum_unknown; 2137 reg->subreg_def = subreg_def; 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 #define DEF_NOT_SUBREG (0) 2214 static void init_reg_state(struct bpf_verifier_env *env, 2215 struct bpf_func_state *state) 2216 { 2217 struct bpf_reg_state *regs = state->regs; 2218 int i; 2219 2220 for (i = 0; i < MAX_BPF_REG; i++) { 2221 bpf_mark_reg_not_init(env, ®s[i]); 2222 regs[i].subreg_def = DEF_NOT_SUBREG; 2223 } 2224 2225 /* frame pointer */ 2226 regs[BPF_REG_FP].type = PTR_TO_STACK; 2227 mark_reg_known_zero(env, regs, BPF_REG_FP); 2228 regs[BPF_REG_FP].frameno = state->frameno; 2229 } 2230 2231 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2232 { 2233 /* 2234 * return_32bit is set to false by default and set explicitly 2235 * by the caller when necessary. 2236 */ 2237 return (struct bpf_retval_range){ minval, maxval, false }; 2238 } 2239 2240 static void init_func_state(struct bpf_verifier_env *env, 2241 struct bpf_func_state *state, 2242 int callsite, int frameno, int subprogno) 2243 { 2244 state->callsite = callsite; 2245 state->frameno = frameno; 2246 state->subprogno = subprogno; 2247 state->callback_ret_range = retval_range(0, 0); 2248 init_reg_state(env, state); 2249 mark_verifier_state_scratched(env); 2250 } 2251 2252 /* Similar to push_stack(), but for async callbacks */ 2253 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2254 int insn_idx, int prev_insn_idx, 2255 int subprog, bool is_sleepable) 2256 { 2257 struct bpf_verifier_stack_elem *elem; 2258 struct bpf_func_state *frame; 2259 2260 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 2261 if (!elem) 2262 return ERR_PTR(-ENOMEM); 2263 2264 elem->insn_idx = insn_idx; 2265 elem->prev_insn_idx = prev_insn_idx; 2266 elem->next = env->head; 2267 elem->log_pos = env->log.end_pos; 2268 env->head = elem; 2269 env->stack_size++; 2270 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2271 verbose(env, 2272 "The sequence of %d jumps is too complex for async cb.\n", 2273 env->stack_size); 2274 return ERR_PTR(-E2BIG); 2275 } 2276 /* Unlike push_stack() do not bpf_copy_verifier_state(). 2277 * The caller state doesn't matter. 2278 * This is async callback. It starts in a fresh stack. 2279 * Initialize it similar to do_check_common(). 2280 */ 2281 elem->st.branches = 1; 2282 elem->st.in_sleepable = is_sleepable; 2283 frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT); 2284 if (!frame) 2285 return ERR_PTR(-ENOMEM); 2286 init_func_state(env, frame, 2287 BPF_MAIN_FUNC /* callsite */, 2288 0 /* frameno within this callchain */, 2289 subprog /* subprog number within this prog */); 2290 elem->st.frame[0] = frame; 2291 return &elem->st; 2292 } 2293 2294 2295 static int cmp_subprogs(const void *a, const void *b) 2296 { 2297 return ((struct bpf_subprog_info *)a)->start - 2298 ((struct bpf_subprog_info *)b)->start; 2299 } 2300 2301 /* Find subprogram that contains instruction at 'off' */ 2302 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off) 2303 { 2304 struct bpf_subprog_info *vals = env->subprog_info; 2305 int l, r, m; 2306 2307 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0) 2308 return NULL; 2309 2310 l = 0; 2311 r = env->subprog_cnt - 1; 2312 while (l < r) { 2313 m = l + (r - l + 1) / 2; 2314 if (vals[m].start <= off) 2315 l = m; 2316 else 2317 r = m - 1; 2318 } 2319 return &vals[l]; 2320 } 2321 2322 /* Find subprogram that starts exactly at 'off' */ 2323 int bpf_find_subprog(struct bpf_verifier_env *env, int off) 2324 { 2325 struct bpf_subprog_info *p; 2326 2327 p = bpf_find_containing_subprog(env, off); 2328 if (!p || p->start != off) 2329 return -ENOENT; 2330 return p - env->subprog_info; 2331 } 2332 2333 static int add_subprog(struct bpf_verifier_env *env, int off) 2334 { 2335 int insn_cnt = env->prog->len; 2336 int ret; 2337 2338 if (off >= insn_cnt || off < 0) { 2339 verbose(env, "call to invalid destination\n"); 2340 return -EINVAL; 2341 } 2342 ret = bpf_find_subprog(env, off); 2343 if (ret >= 0) 2344 return ret; 2345 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2346 verbose(env, "too many subprograms\n"); 2347 return -E2BIG; 2348 } 2349 /* determine subprog starts. The end is one before the next starts */ 2350 env->subprog_info[env->subprog_cnt++].start = off; 2351 sort(env->subprog_info, env->subprog_cnt, 2352 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2353 return env->subprog_cnt - 1; 2354 } 2355 2356 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2357 { 2358 struct bpf_prog_aux *aux = env->prog->aux; 2359 struct btf *btf = aux->btf; 2360 const struct btf_type *t; 2361 u32 main_btf_id, id; 2362 const char *name; 2363 int ret, i; 2364 2365 /* Non-zero func_info_cnt implies valid btf */ 2366 if (!aux->func_info_cnt) 2367 return 0; 2368 main_btf_id = aux->func_info[0].type_id; 2369 2370 t = btf_type_by_id(btf, main_btf_id); 2371 if (!t) { 2372 verbose(env, "invalid btf id for main subprog in func_info\n"); 2373 return -EINVAL; 2374 } 2375 2376 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2377 if (IS_ERR(name)) { 2378 ret = PTR_ERR(name); 2379 /* If there is no tag present, there is no exception callback */ 2380 if (ret == -ENOENT) 2381 ret = 0; 2382 else if (ret == -EEXIST) 2383 verbose(env, "multiple exception callback tags for main subprog\n"); 2384 return ret; 2385 } 2386 2387 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2388 if (ret < 0) { 2389 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2390 return ret; 2391 } 2392 id = ret; 2393 t = btf_type_by_id(btf, id); 2394 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2395 verbose(env, "exception callback '%s' must have global linkage\n", name); 2396 return -EINVAL; 2397 } 2398 ret = 0; 2399 for (i = 0; i < aux->func_info_cnt; i++) { 2400 if (aux->func_info[i].type_id != id) 2401 continue; 2402 ret = aux->func_info[i].insn_off; 2403 /* Further func_info and subprog checks will also happen 2404 * later, so assume this is the right insn_off for now. 2405 */ 2406 if (!ret) { 2407 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2408 ret = -EINVAL; 2409 } 2410 } 2411 if (!ret) { 2412 verbose(env, "exception callback type id not found in func_info\n"); 2413 ret = -EINVAL; 2414 } 2415 return ret; 2416 } 2417 2418 #define MAX_KFUNC_BTFS 256 2419 2420 struct bpf_kfunc_btf { 2421 struct btf *btf; 2422 struct module *module; 2423 u16 offset; 2424 }; 2425 2426 struct bpf_kfunc_btf_tab { 2427 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2428 u32 nr_descs; 2429 }; 2430 2431 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2432 { 2433 const struct bpf_kfunc_desc *d0 = a; 2434 const struct bpf_kfunc_desc *d1 = b; 2435 2436 /* func_id is not greater than BTF_MAX_TYPE */ 2437 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2438 } 2439 2440 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2441 { 2442 const struct bpf_kfunc_btf *d0 = a; 2443 const struct bpf_kfunc_btf *d1 = b; 2444 2445 return d0->offset - d1->offset; 2446 } 2447 2448 static struct bpf_kfunc_desc * 2449 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2450 { 2451 struct bpf_kfunc_desc desc = { 2452 .func_id = func_id, 2453 .offset = offset, 2454 }; 2455 struct bpf_kfunc_desc_tab *tab; 2456 2457 tab = prog->aux->kfunc_tab; 2458 return bsearch(&desc, tab->descs, tab->nr_descs, 2459 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2460 } 2461 2462 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2463 u16 btf_fd_idx, u8 **func_addr) 2464 { 2465 const struct bpf_kfunc_desc *desc; 2466 2467 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2468 if (!desc) 2469 return -EFAULT; 2470 2471 *func_addr = (u8 *)desc->addr; 2472 return 0; 2473 } 2474 2475 #define BPF_FD_SLOT_BTF 1UL 2476 2477 static void fd_slot_set_map(struct bpf_fd_array *slot, struct bpf_map *map) 2478 { 2479 slot->val = (unsigned long)map; 2480 } 2481 2482 static void fd_slot_set_btf(struct bpf_fd_array *slot, struct btf *btf) 2483 { 2484 slot->val = (unsigned long)btf | BPF_FD_SLOT_BTF; 2485 } 2486 2487 static struct bpf_map *fd_slot_map(struct bpf_fd_array slot) 2488 { 2489 if (slot.val & BPF_FD_SLOT_BTF) 2490 return NULL; 2491 return (struct bpf_map *)slot.val; 2492 } 2493 2494 static struct btf *fd_slot_btf(struct bpf_fd_array slot) 2495 { 2496 if (!(slot.val & BPF_FD_SLOT_BTF)) 2497 return NULL; 2498 return (struct btf *)(slot.val & ~BPF_FD_SLOT_BTF); 2499 } 2500 2501 static struct btf * 2502 fd_array_get_btf_continuous(struct bpf_verifier_env *env, u32 idx) 2503 { 2504 struct btf *btf; 2505 2506 if (idx >= env->fd_array_cnt) { 2507 verbose(env, "kfunc fd_idx %u out of bounds, fd_array_cnt %u\n", 2508 idx, env->fd_array_cnt); 2509 return ERR_PTR(-EINVAL); 2510 } 2511 btf = fd_slot_btf(env->fd_array[idx]); 2512 if (!btf) { 2513 verbose(env, "kfunc fd_idx %u is not a module BTF\n", idx); 2514 return ERR_PTR(-EINVAL); 2515 } 2516 btf_get(btf); 2517 return btf; 2518 } 2519 2520 static struct btf * 2521 fd_array_get_btf_sparse(struct bpf_verifier_env *env, u32 idx) 2522 { 2523 struct btf *btf; 2524 int btf_fd; 2525 2526 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array_raw, 2527 (size_t)idx * sizeof(btf_fd), sizeof(btf_fd))) 2528 return ERR_PTR(-EFAULT); 2529 btf = btf_get_by_fd(btf_fd); 2530 if (IS_ERR(btf)) { 2531 verbose(env, "invalid module BTF fd specified\n"); 2532 return btf; 2533 } 2534 return btf; 2535 } 2536 2537 static struct btf *fd_array_get_btf(struct bpf_verifier_env *env, u32 idx) 2538 { 2539 if (env->signature) { 2540 verbose(env, "signed program cannot bind any BTF\n"); 2541 return ERR_PTR(-EACCES); 2542 } 2543 if (env->fd_array) 2544 return fd_array_get_btf_continuous(env, idx); 2545 if (!bpfptr_is_null(env->fd_array_raw)) 2546 return fd_array_get_btf_sparse(env, idx); 2547 2548 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2549 return ERR_PTR(-EPROTO); 2550 } 2551 2552 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2553 s16 offset) 2554 { 2555 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2556 struct bpf_kfunc_btf_tab *tab; 2557 struct bpf_kfunc_btf *b; 2558 struct module *mod; 2559 struct btf *btf; 2560 2561 tab = env->prog->aux->kfunc_btf_tab; 2562 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2563 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2564 if (!b) { 2565 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2566 verbose(env, "too many different module BTFs\n"); 2567 return ERR_PTR(-E2BIG); 2568 } 2569 2570 btf = fd_array_get_btf(env, offset); 2571 if (IS_ERR(btf)) 2572 return btf; 2573 if (!btf_is_module(btf)) { 2574 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2575 btf_put(btf); 2576 return ERR_PTR(-EINVAL); 2577 } 2578 2579 mod = btf_try_get_module(btf); 2580 if (!mod) { 2581 btf_put(btf); 2582 return ERR_PTR(-ENXIO); 2583 } 2584 2585 b = &tab->descs[tab->nr_descs++]; 2586 b->btf = btf; 2587 b->module = mod; 2588 b->offset = offset; 2589 2590 /* sort() reorders entries by value, so b may no longer point 2591 * to the right entry after this 2592 */ 2593 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2594 kfunc_btf_cmp_by_off, NULL); 2595 } else { 2596 btf = b->btf; 2597 } 2598 2599 return btf; 2600 } 2601 2602 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2603 { 2604 if (!tab) 2605 return; 2606 2607 while (tab->nr_descs--) { 2608 module_put(tab->descs[tab->nr_descs].module); 2609 btf_put(tab->descs[tab->nr_descs].btf); 2610 } 2611 kfree(tab); 2612 } 2613 2614 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2615 { 2616 if (offset) { 2617 if (offset < 0) { 2618 /* In the future, this can be allowed to increase limit 2619 * of fd index into fd_array, interpreted as u16. 2620 */ 2621 verbose(env, "negative offset disallowed for kernel module function call\n"); 2622 return ERR_PTR(-EINVAL); 2623 } 2624 2625 return __find_kfunc_desc_btf(env, offset); 2626 } 2627 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2628 } 2629 2630 #define KF_IMPL_SUFFIX "_impl" 2631 2632 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_log *log, 2633 struct btf *btf, 2634 const char *func_name) 2635 { 2636 const struct btf_type *func; 2637 char buf[KSYM_NAME_LEN]; 2638 s32 impl_id; 2639 int len; 2640 2641 len = snprintf(buf, sizeof(buf), "%s%s", func_name, KF_IMPL_SUFFIX); 2642 if (len < 0 || len >= sizeof(buf)) { 2643 bpf_log(log, "function name %s%s is too long\n", 2644 func_name, KF_IMPL_SUFFIX); 2645 return NULL; 2646 } 2647 2648 impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC); 2649 if (impl_id <= 0) { 2650 bpf_log(log, "cannot find function %s in BTF\n", buf); 2651 return NULL; 2652 } 2653 2654 func = btf_type_by_id(btf, impl_id); 2655 2656 return btf_type_by_id(btf, func->type); 2657 } 2658 2659 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 2660 s32 func_id, 2661 s16 offset, 2662 struct bpf_kfunc_meta *kfunc) 2663 { 2664 const struct btf_type *func, *func_proto; 2665 const char *func_name; 2666 u32 *kfunc_flags; 2667 struct btf *btf; 2668 2669 if (func_id <= 0) { 2670 verbose(env, "invalid kernel function btf_id %d\n", func_id); 2671 return -EINVAL; 2672 } 2673 2674 btf = find_kfunc_desc_btf(env, offset); 2675 if (IS_ERR(btf)) { 2676 verbose(env, "failed to find BTF for kernel function\n"); 2677 return PTR_ERR(btf); 2678 } 2679 2680 /* 2681 * Note that kfunc_flags may be NULL at this point, which 2682 * means that we couldn't find func_id in any relevant 2683 * kfunc_id_set. This most likely indicates an invalid kfunc 2684 * call. However we don't fail with an error here, 2685 * and let the caller decide what to do with NULL kfunc->flags. 2686 */ 2687 kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog); 2688 2689 func = btf_type_by_id(btf, func_id); 2690 if (!func || !btf_type_is_func(func)) { 2691 verbose(env, "kernel btf_id %d is not a function\n", func_id); 2692 return -EINVAL; 2693 } 2694 2695 func_name = btf_name_by_offset(btf, func->name_off); 2696 2697 /* 2698 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag 2699 * can be found through the counterpart _impl kfunc. 2700 */ 2701 if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS)) 2702 func_proto = find_kfunc_impl_proto(&env->log, btf, func_name); 2703 else 2704 func_proto = btf_type_by_id(btf, func->type); 2705 2706 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2707 verbose(env, "kernel function btf_id %d does not have a valid func_proto\n", 2708 func_id); 2709 return -EINVAL; 2710 } 2711 2712 memset(kfunc, 0, sizeof(*kfunc)); 2713 kfunc->btf = btf; 2714 kfunc->id = func_id; 2715 kfunc->name = func_name; 2716 kfunc->proto = func_proto; 2717 kfunc->flags = kfunc_flags; 2718 2719 return 0; 2720 } 2721 2722 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset) 2723 { 2724 struct bpf_kfunc_btf_tab *btf_tab; 2725 struct btf_func_model func_model; 2726 struct bpf_kfunc_desc_tab *tab; 2727 struct bpf_prog_aux *prog_aux; 2728 struct bpf_kfunc_meta kfunc; 2729 struct bpf_kfunc_desc *desc; 2730 unsigned long addr; 2731 int err; 2732 2733 prog_aux = env->prog->aux; 2734 tab = prog_aux->kfunc_tab; 2735 btf_tab = prog_aux->kfunc_btf_tab; 2736 if (!tab) { 2737 if (!btf_vmlinux) { 2738 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2739 return -ENOTSUPP; 2740 } 2741 2742 if (!env->prog->jit_requested) { 2743 verbose(env, "JIT is required for calling kernel function\n"); 2744 return -ENOTSUPP; 2745 } 2746 2747 if (!bpf_jit_supports_kfunc_call()) { 2748 verbose(env, "JIT does not support calling kernel function\n"); 2749 return -ENOTSUPP; 2750 } 2751 2752 if (!env->prog->gpl_compatible) { 2753 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2754 return -EINVAL; 2755 } 2756 2757 tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT); 2758 if (!tab) 2759 return -ENOMEM; 2760 prog_aux->kfunc_tab = tab; 2761 } 2762 2763 env->prog->jit_required = 1; 2764 2765 /* func_id == 0 is always invalid, but instead of returning an error, be 2766 * conservative and wait until the code elimination pass before returning 2767 * error, so that invalid calls that get pruned out can be in BPF programs 2768 * loaded from userspace. It is also required that offset be untouched 2769 * for such calls. 2770 */ 2771 if (!func_id && !offset) 2772 return 0; 2773 2774 if (!btf_tab && offset) { 2775 btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT); 2776 if (!btf_tab) 2777 return -ENOMEM; 2778 prog_aux->kfunc_btf_tab = btf_tab; 2779 } 2780 2781 if (find_kfunc_desc(env->prog, func_id, offset)) 2782 return 0; 2783 2784 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2785 verbose(env, "too many different kernel function calls\n"); 2786 return -E2BIG; 2787 } 2788 2789 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 2790 if (err) 2791 return err; 2792 2793 addr = kallsyms_lookup_name(kfunc.name); 2794 if (!addr) { 2795 verbose(env, "cannot find address for kernel function %s\n", kfunc.name); 2796 return -EINVAL; 2797 } 2798 2799 if (bpf_dev_bound_kfunc_id(func_id)) { 2800 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2801 if (err) 2802 return err; 2803 } 2804 2805 err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model); 2806 if (err) 2807 return err; 2808 2809 desc = &tab->descs[tab->nr_descs++]; 2810 desc->func_id = func_id; 2811 desc->offset = offset; 2812 desc->addr = addr; 2813 desc->func_model = func_model; 2814 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2815 kfunc_desc_cmp_by_id_off, NULL); 2816 return 0; 2817 } 2818 2819 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2820 { 2821 struct bpf_subprog_info *subprog = env->subprog_info; 2822 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2823 struct bpf_insn *insn = env->prog->insnsi; 2824 2825 /* Add entry function. */ 2826 ret = add_subprog(env, 0); 2827 if (ret) 2828 return ret; 2829 2830 for (i = 0; i < insn_cnt; i++, insn++) { 2831 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2832 !bpf_pseudo_kfunc_call(insn)) 2833 continue; 2834 2835 if (!env->bpf_capable) { 2836 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2837 return -EPERM; 2838 } 2839 2840 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2841 ret = add_subprog(env, i + insn->imm + 1); 2842 else 2843 ret = bpf_add_kfunc_call(env, insn->imm, insn->off); 2844 2845 if (ret < 0) 2846 return ret; 2847 } 2848 2849 ret = bpf_find_exception_callback_insn_off(env); 2850 if (ret < 0) 2851 return ret; 2852 ex_cb_insn = ret; 2853 2854 /* If ex_cb_insn > 0, this means that the main program has a subprog 2855 * marked using BTF decl tag to serve as the exception callback. 2856 */ 2857 if (ex_cb_insn) { 2858 ret = add_subprog(env, ex_cb_insn); 2859 if (ret < 0) 2860 return ret; 2861 for (i = 1; i < env->subprog_cnt; i++) { 2862 if (env->subprog_info[i].start != ex_cb_insn) 2863 continue; 2864 env->exception_callback_subprog = i; 2865 bpf_mark_subprog_exc_cb(env, i); 2866 break; 2867 } 2868 } 2869 2870 /* Add a fake 'exit' subprog which could simplify subprog iteration 2871 * logic. 'subprog_cnt' should not be increased. 2872 */ 2873 subprog[env->subprog_cnt].start = insn_cnt; 2874 2875 if (env->log.level & BPF_LOG_LEVEL2) 2876 for (i = 0; i < env->subprog_cnt; i++) 2877 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2878 2879 return 0; 2880 } 2881 2882 static int check_subprogs(struct bpf_verifier_env *env) 2883 { 2884 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2885 struct bpf_subprog_info *subprog = env->subprog_info; 2886 struct bpf_insn *insn = env->prog->insnsi; 2887 int insn_cnt = env->prog->len; 2888 2889 /* now check that all jumps are within the same subprog */ 2890 subprog_start = subprog[cur_subprog].start; 2891 subprog_end = subprog[cur_subprog + 1].start; 2892 for (i = 0; i < insn_cnt; i++) { 2893 u8 code = insn[i].code; 2894 2895 if (code == (BPF_JMP | BPF_CALL) && 2896 insn[i].src_reg == 0 && 2897 insn[i].imm == BPF_FUNC_tail_call) { 2898 subprog[cur_subprog].has_tail_call = true; 2899 subprog[cur_subprog].tail_call_reachable = true; 2900 } 2901 if (BPF_CLASS(code) == BPF_LD && 2902 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2903 subprog[cur_subprog].has_ld_abs = true; 2904 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2905 goto next; 2906 if (BPF_OP(code) == BPF_CALL) 2907 goto next; 2908 if (BPF_OP(code) == BPF_EXIT) { 2909 subprog[cur_subprog].exit_idx = i; 2910 goto next; 2911 } 2912 off = i + bpf_jmp_offset(&insn[i]) + 1; 2913 if (off < subprog_start || off >= subprog_end) { 2914 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2915 return -EINVAL; 2916 } 2917 next: 2918 if (i == subprog_end - 1) { 2919 /* to avoid fall-through from one subprog into another 2920 * the last insn of the subprog should be either exit 2921 * or unconditional jump back or bpf_throw call 2922 */ 2923 if (code != (BPF_JMP | BPF_EXIT) && 2924 code != (BPF_JMP32 | BPF_JA) && 2925 code != (BPF_JMP | BPF_JA)) { 2926 verbose(env, "last insn is not an exit or jmp\n"); 2927 return -EINVAL; 2928 } 2929 subprog_start = subprog_end; 2930 cur_subprog++; 2931 if (cur_subprog < env->subprog_cnt) 2932 subprog_end = subprog[cur_subprog + 1].start; 2933 } 2934 } 2935 return 0; 2936 } 2937 2938 /* 2939 * Sort subprogs in topological order so that leaf subprogs come first and 2940 * their callers come later. This is a DFS post-order traversal of the call 2941 * graph. Scan only reachable instructions (those in the computed postorder) of 2942 * the current subprog to discover callees (direct subprogs and sync 2943 * callbacks). 2944 */ 2945 static int sort_subprogs_topo(struct bpf_verifier_env *env) 2946 { 2947 struct bpf_subprog_info *si = env->subprog_info; 2948 int *insn_postorder = env->cfg.insn_postorder; 2949 struct bpf_insn *insn = env->prog->insnsi; 2950 int cnt = env->subprog_cnt; 2951 int *dfs_stack = NULL; 2952 int top = 0, order = 0; 2953 int i, ret = 0; 2954 u8 *color = NULL; 2955 2956 color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT); 2957 dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT); 2958 if (!color || !dfs_stack) { 2959 ret = -ENOMEM; 2960 goto out; 2961 } 2962 2963 /* 2964 * DFS post-order traversal. 2965 * Color values: 0 = unvisited, 1 = on stack, 2 = done. 2966 */ 2967 for (i = 0; i < cnt; i++) { 2968 if (color[i]) 2969 continue; 2970 color[i] = 1; 2971 dfs_stack[top++] = i; 2972 2973 while (top > 0) { 2974 int cur = dfs_stack[top - 1]; 2975 int po_start = si[cur].postorder_start; 2976 int po_end = si[cur + 1].postorder_start; 2977 bool pushed = false; 2978 int j; 2979 2980 for (j = po_start; j < po_end; j++) { 2981 int idx = insn_postorder[j]; 2982 int callee; 2983 2984 if (!bpf_pseudo_call(&insn[idx]) && !bpf_pseudo_func(&insn[idx])) 2985 continue; 2986 callee = bpf_find_subprog(env, idx + insn[idx].imm + 1); 2987 if (callee < 0) { 2988 ret = -EFAULT; 2989 goto out; 2990 } 2991 if (color[callee] == 2) 2992 continue; 2993 if (color[callee] == 1) { 2994 if (bpf_pseudo_func(&insn[idx])) 2995 continue; 2996 verbose(env, "recursive call from %s() to %s()\n", 2997 subprog_name(env, cur), 2998 subprog_name(env, callee)); 2999 ret = -EINVAL; 3000 goto out; 3001 } 3002 color[callee] = 1; 3003 dfs_stack[top++] = callee; 3004 pushed = true; 3005 break; 3006 } 3007 3008 if (!pushed) { 3009 color[cur] = 2; 3010 env->subprog_topo_order[order++] = cur; 3011 top--; 3012 } 3013 } 3014 } 3015 3016 if (env->log.level & BPF_LOG_LEVEL2) 3017 for (i = 0; i < cnt; i++) 3018 verbose(env, "topo_order[%d] = %s\n", 3019 i, subprog_name(env, env->subprog_topo_order[i])); 3020 out: 3021 kvfree(dfs_stack); 3022 kvfree(color); 3023 return ret; 3024 } 3025 3026 static void mark_stack_slots_scratched(struct bpf_verifier_env *env, 3027 int spi, int nr_slots) 3028 { 3029 int i; 3030 3031 for (i = 0; i < nr_slots; i++) 3032 mark_stack_slot_scratched(env, spi - i); 3033 } 3034 3035 /* This function is supposed to be used by the following 32-bit optimization 3036 * code only. It returns TRUE if the source or destination register operates 3037 * on 64-bit, otherwise return FALSE. 3038 */ 3039 bool bpf_is_reg64(struct bpf_insn *insn, 3040 u32 regno, struct bpf_reg_state *reg, enum bpf_reg_arg_type t) 3041 { 3042 u8 code, class, op; 3043 3044 code = insn->code; 3045 class = BPF_CLASS(code); 3046 op = BPF_OP(code); 3047 if (class == BPF_JMP) { 3048 /* BPF_EXIT for "main" will reach here. Return TRUE 3049 * conservatively. 3050 */ 3051 if (op == BPF_EXIT) 3052 return true; 3053 if (op == BPF_CALL) { 3054 /* BPF to BPF call will reach here because of marking 3055 * caller saved clobber with DST_OP_NO_MARK for which we 3056 * don't care the register def because they are anyway 3057 * marked as NOT_INIT already. 3058 */ 3059 if (insn->src_reg == BPF_PSEUDO_CALL) 3060 return false; 3061 /* Helper call will reach here because of arg type 3062 * check, conservatively return TRUE. 3063 */ 3064 if (t == SRC_OP) 3065 return true; 3066 3067 return false; 3068 } 3069 } 3070 3071 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3072 return false; 3073 3074 if (class == BPF_ALU64 || class == BPF_JMP || 3075 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3076 return true; 3077 3078 if (class == BPF_ALU || class == BPF_JMP32) 3079 return false; 3080 3081 if (class == BPF_LDX) { 3082 if (t != SRC_OP) 3083 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3084 /* LDX source must be ptr. */ 3085 return true; 3086 } 3087 3088 if (class == BPF_STX) { 3089 /* BPF_STX (including atomic variants) has one or more source 3090 * operands, one of which is a ptr. Check whether the caller is 3091 * asking about it. 3092 */ 3093 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3094 return true; 3095 return BPF_SIZE(code) == BPF_DW; 3096 } 3097 3098 if (class == BPF_LD) { 3099 u8 mode = BPF_MODE(code); 3100 3101 /* LD_IMM64 */ 3102 if (mode == BPF_IMM) 3103 return true; 3104 3105 /* Both LD_IND and LD_ABS return 32-bit data. */ 3106 if (t != SRC_OP) 3107 return false; 3108 3109 /* Implicit ctx ptr. */ 3110 if (regno == BPF_REG_6) 3111 return true; 3112 3113 /* Explicit source could be any width. */ 3114 return true; 3115 } 3116 3117 if (class == BPF_ST) 3118 /* The only source register for BPF_ST is a ptr. */ 3119 return true; 3120 3121 /* Conservatively return true at default. */ 3122 return true; 3123 } 3124 3125 static void mark_insn_zext(struct bpf_verifier_env *env, 3126 struct bpf_reg_state *reg) 3127 { 3128 s32 def_idx = reg->subreg_def; 3129 3130 if (def_idx == DEF_NOT_SUBREG) 3131 return; 3132 3133 env->insn_aux_data[def_idx - 1].zext_dst = true; 3134 /* The dst will be zero extended, so won't be sub-register anymore. */ 3135 reg->subreg_def = DEF_NOT_SUBREG; 3136 } 3137 3138 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3139 enum bpf_reg_arg_type t) 3140 { 3141 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3142 struct bpf_reg_state *reg; 3143 bool rw64; 3144 3145 mark_reg_scratched(env, regno); 3146 3147 reg = ®s[regno]; 3148 rw64 = bpf_is_reg64(insn, regno, reg, t); 3149 if (t == SRC_OP) { 3150 /* check whether register used as source operand can be read */ 3151 if (reg->type == NOT_INIT) { 3152 verbose(env, "R%d !read_ok\n", regno); 3153 return -EACCES; 3154 } 3155 /* We don't need to worry about FP liveness because it's read-only */ 3156 if (regno == BPF_REG_FP) 3157 return 0; 3158 3159 if (rw64) 3160 mark_insn_zext(env, reg); 3161 3162 return 0; 3163 } else { 3164 /* check whether register used as dest operand can be written to */ 3165 if (regno == BPF_REG_FP) { 3166 verbose(env, "frame pointer is read only\n"); 3167 return -EACCES; 3168 } 3169 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3170 if (t == DST_OP) 3171 mark_reg_unknown(env, regs, regno); 3172 } 3173 return 0; 3174 } 3175 3176 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3177 enum bpf_reg_arg_type t) 3178 { 3179 struct bpf_verifier_state *vstate = env->cur_state; 3180 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3181 3182 return __check_reg_arg(env, state->regs, regno, t); 3183 } 3184 3185 static void mark_indirect_target(struct bpf_verifier_env *env, int idx) 3186 { 3187 env->insn_aux_data[idx].indirect_target = true; 3188 } 3189 3190 #define LR_FRAMENO_BITS 4 3191 #define LR_SPI_BITS 6 3192 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3193 #define LR_SIZE_BITS 4 3194 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3195 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3196 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3197 #define LR_SPI_OFF LR_FRAMENO_BITS 3198 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3199 #define LINKED_REGS_MAX 5 3200 3201 static_assert(MAX_CALL_FRAMES <= (1 << LR_FRAMENO_BITS)); 3202 static_assert(LINKED_REGS_MAX < (1 << LR_SIZE_BITS)); 3203 static_assert(LINKED_REGS_MAX * LR_ENTRY_BITS + LR_SIZE_BITS <= 64); 3204 3205 struct linked_reg { 3206 u8 frameno; 3207 union { 3208 u8 spi; 3209 u8 regno; 3210 }; 3211 bool is_reg; 3212 }; 3213 3214 struct linked_regs { 3215 int cnt; 3216 struct linked_reg entries[LINKED_REGS_MAX]; 3217 }; 3218 3219 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3220 { 3221 if (s->cnt < LINKED_REGS_MAX) 3222 return &s->entries[s->cnt++]; 3223 3224 return NULL; 3225 } 3226 3227 /* 3228 * Use u64 as a vector of 5 11-bit values, use first 4-bits to track 3229 * number of elements currently in stack. 3230 * Pack one history entry for linked registers as 11 bits in the following format: 3231 * - 4-bits frameno 3232 * - 6-bits spi_or_reg 3233 * - 1-bit is_reg 3234 */ 3235 static u64 linked_regs_pack(struct linked_regs *s) 3236 { 3237 u64 val = 0; 3238 int i; 3239 3240 for (i = 0; i < s->cnt; ++i) { 3241 struct linked_reg *e = &s->entries[i]; 3242 u64 tmp = 0; 3243 3244 tmp |= e->frameno; 3245 tmp |= e->spi << LR_SPI_OFF; 3246 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3247 3248 val <<= LR_ENTRY_BITS; 3249 val |= tmp; 3250 } 3251 val <<= LR_SIZE_BITS; 3252 val |= s->cnt; 3253 return val; 3254 } 3255 3256 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3257 { 3258 int i; 3259 3260 s->cnt = val & LR_SIZE_MASK; 3261 val >>= LR_SIZE_BITS; 3262 3263 for (i = 0; i < s->cnt; ++i) { 3264 struct linked_reg *e = &s->entries[i]; 3265 3266 e->frameno = val & LR_FRAMENO_MASK; 3267 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3268 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3269 val >>= LR_ENTRY_BITS; 3270 } 3271 } 3272 3273 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3274 { 3275 const struct btf_type *func; 3276 struct btf *desc_btf; 3277 3278 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3279 return NULL; 3280 3281 desc_btf = find_kfunc_desc_btf(data, insn->off); 3282 if (IS_ERR(desc_btf)) 3283 return "<error>"; 3284 3285 func = btf_type_by_id(desc_btf, insn->imm); 3286 return btf_name_by_offset(desc_btf, func->name_off); 3287 } 3288 3289 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn) 3290 { 3291 const struct bpf_insn_cbs cbs = { 3292 .cb_call = disasm_kfunc_name, 3293 .cb_print = verbose, 3294 .private_data = env, 3295 }; 3296 3297 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3298 } 3299 3300 /* If any register R in hist->linked_regs is marked as precise in bt, 3301 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 3302 */ 3303 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 3304 { 3305 struct linked_regs linked_regs; 3306 bool some_precise = false; 3307 int i; 3308 3309 if (!hist || hist->linked_regs == 0) 3310 return; 3311 3312 linked_regs_unpack(hist->linked_regs, &linked_regs); 3313 for (i = 0; i < linked_regs.cnt; ++i) { 3314 struct linked_reg *e = &linked_regs.entries[i]; 3315 3316 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 3317 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 3318 some_precise = true; 3319 break; 3320 } 3321 } 3322 3323 if (!some_precise) 3324 return; 3325 3326 for (i = 0; i < linked_regs.cnt; ++i) { 3327 struct linked_reg *e = &linked_regs.entries[i]; 3328 3329 if (e->is_reg) 3330 bpf_bt_set_frame_reg(bt, e->frameno, e->regno); 3331 else 3332 bpf_bt_set_frame_slot(bt, e->frameno, e->spi); 3333 } 3334 } 3335 3336 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3337 { 3338 return bpf_mark_chain_precision(env, env->cur_state, regno, NULL); 3339 } 3340 3341 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 3342 * desired reg and stack masks across all relevant frames 3343 */ 3344 static int mark_chain_precision_batch(struct bpf_verifier_env *env, 3345 struct bpf_verifier_state *starting_state) 3346 { 3347 return bpf_mark_chain_precision(env, starting_state, -1, NULL); 3348 } 3349 3350 /* check if register is a constant scalar value */ 3351 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 3352 { 3353 return reg->type == SCALAR_VALUE && 3354 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 3355 } 3356 3357 /* assuming is_reg_const() is true, return constant value of a register */ 3358 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 3359 { 3360 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 3361 } 3362 3363 static bool is_pointer_regtype(enum bpf_reg_type type) 3364 { 3365 return type != SCALAR_VALUE && type != NOT_INIT; 3366 } 3367 3368 static bool __is_pointer_value(bool allow_ptr_leaks, 3369 const struct bpf_reg_state *reg) 3370 { 3371 if (allow_ptr_leaks) 3372 return false; 3373 3374 return is_pointer_regtype(reg->type); 3375 } 3376 3377 static void clear_scalar_id(struct bpf_reg_state *reg) 3378 { 3379 reg->id = 0; 3380 reg->delta = 0; 3381 } 3382 3383 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 3384 struct bpf_reg_state *src_reg) 3385 { 3386 if (src_reg->type != SCALAR_VALUE) 3387 return; 3388 /* 3389 * The verifier is processing rX = rY insn and 3390 * rY->id has special linked register already. 3391 * Cleared it, since multiple rX += const are not supported. 3392 */ 3393 if (src_reg->id & BPF_ADD_CONST) 3394 clear_scalar_id(src_reg); 3395 /* 3396 * Ensure that src_reg has a valid ID that will be copied to 3397 * dst_reg and then will be used by sync_linked_regs() to 3398 * propagate min/max range. 3399 */ 3400 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 3401 src_reg->id = ++env->id_gen; 3402 } 3403 3404 static void save_register_state(struct bpf_verifier_env *env, 3405 struct bpf_func_state *state, 3406 int spi, struct bpf_reg_state *reg, 3407 int size) 3408 { 3409 int i; 3410 3411 state->stack[spi].spilled_ptr = *reg; 3412 3413 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3414 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 3415 3416 /* size < 8 bytes spill */ 3417 for (; i; i--) 3418 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 3419 } 3420 3421 static bool is_bpf_st_mem(struct bpf_insn *insn) 3422 { 3423 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 3424 } 3425 3426 static int get_reg_width(struct bpf_reg_state *reg) 3427 { 3428 return fls64(reg_umax(reg)); 3429 } 3430 3431 /* See comment for mark_fastcall_pattern_for_call() */ 3432 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 3433 struct bpf_func_state *state, int insn_idx, int off) 3434 { 3435 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 3436 struct bpf_insn_aux_data *aux = env->insn_aux_data; 3437 int i; 3438 3439 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 3440 return; 3441 /* access to the region [max_stack_depth .. fastcall_stack_off) 3442 * from something that is not a part of the fastcall pattern, 3443 * disable fastcall rewrites for current subprogram by setting 3444 * fastcall_stack_off to a value smaller than any possible offset. 3445 */ 3446 subprog->fastcall_stack_off = S16_MIN; 3447 /* reset fastcall aux flags within subprogram, 3448 * happens at most once per subprogram 3449 */ 3450 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 3451 aux[i].fastcall_spills_num = 0; 3452 aux[i].fastcall_pattern = 0; 3453 } 3454 } 3455 3456 static void scrub_special_slot(struct bpf_func_state *state, int spi) 3457 { 3458 int i; 3459 3460 /* regular write of data into stack destroys any spilled ptr */ 3461 state->stack[spi].spilled_ptr.type = NOT_INIT; 3462 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 3463 if (is_stack_slot_special(&state->stack[spi])) 3464 for (i = 0; i < BPF_REG_SIZE; i++) 3465 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 3466 } 3467 3468 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3469 * stack boundary and alignment are checked in check_mem_access() 3470 */ 3471 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3472 /* stack frame we're writing to */ 3473 struct bpf_func_state *state, 3474 int off, int size, int value_regno, 3475 int insn_idx) 3476 { 3477 struct bpf_func_state *cur; /* state of the current function */ 3478 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3479 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3480 struct bpf_reg_state *reg = NULL; 3481 int insn_flags = INSN_F_STACK_ACCESS; 3482 int hist_spi = spi, hist_frame = state->frameno; 3483 3484 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 3485 * so it's aligned access and [off, off + size) are within stack limits 3486 */ 3487 if (!env->allow_ptr_leaks && 3488 bpf_is_spilled_reg(&state->stack[spi]) && 3489 !bpf_is_spilled_scalar_reg(&state->stack[spi]) && 3490 size != BPF_REG_SIZE) { 3491 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3492 return -EACCES; 3493 } 3494 3495 cur = env->cur_state->frame[env->cur_state->curframe]; 3496 if (value_regno >= 0) 3497 reg = &cur->regs[value_regno]; 3498 if (!env->bypass_spec_v4) { 3499 bool sanitize = reg && is_pointer_regtype(reg->type); 3500 3501 for (i = 0; i < size; i++) { 3502 u8 type = state->stack[spi].slot_type[(slot - i) % 3503 BPF_REG_SIZE]; 3504 3505 if (type != STACK_MISC && type != STACK_ZERO) { 3506 sanitize = true; 3507 break; 3508 } 3509 } 3510 3511 if (sanitize) 3512 env->insn_aux_data[insn_idx].nospec_result = true; 3513 } 3514 3515 err = destroy_if_dynptr_stack_slot(env, state, spi); 3516 if (err) 3517 return err; 3518 3519 check_fastcall_stack_contract(env, state, insn_idx, off); 3520 mark_stack_slot_scratched(env, spi); 3521 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 3522 bool reg_value_fits; 3523 3524 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 3525 /* Make sure that reg had an ID to build a relation on spill. */ 3526 if (reg_value_fits) 3527 assign_scalar_id_before_mov(env, reg); 3528 save_register_state(env, state, spi, reg, size); 3529 /* Break the relation on a narrowing spill. */ 3530 if (!reg_value_fits) 3531 state->stack[spi].spilled_ptr.id = 0; 3532 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 3533 env->bpf_capable) { 3534 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 3535 3536 memset(tmp_reg, 0, sizeof(*tmp_reg)); 3537 __mark_reg_known(tmp_reg, insn->imm); 3538 tmp_reg->type = SCALAR_VALUE; 3539 save_register_state(env, state, spi, tmp_reg, size); 3540 } else if (reg && is_pointer_regtype(reg->type)) { 3541 /* register containing pointer is being spilled into stack */ 3542 if (size != BPF_REG_SIZE) { 3543 verbose_linfo(env, insn_idx, "; "); 3544 verbose(env, "invalid size of register spill\n"); 3545 return -EACCES; 3546 } 3547 if (state != cur && reg->type == PTR_TO_STACK) { 3548 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 3549 return -EINVAL; 3550 } 3551 save_register_state(env, state, spi, reg, size); 3552 } else { 3553 u8 type = STACK_MISC; 3554 3555 scrub_special_slot(state, spi); 3556 3557 /* when we zero initialize stack slots mark them as such */ 3558 if ((reg && bpf_register_is_null(reg)) || 3559 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 3560 /* STACK_ZERO case happened because register spill 3561 * wasn't properly aligned at the stack slot boundary, 3562 * so it's not a register spill anymore; force 3563 * originating register to be precise to make 3564 * STACK_ZERO correct for subsequent states 3565 */ 3566 err = mark_chain_precision(env, value_regno); 3567 if (err) 3568 return err; 3569 type = STACK_ZERO; 3570 } 3571 3572 /* Mark slots affected by this stack write. */ 3573 for (i = 0; i < size; i++) 3574 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 3575 insn_flags = 0; /* not a register spill */ 3576 } 3577 3578 if (insn_flags) 3579 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3580 hist_spi, hist_frame, 0); 3581 return 0; 3582 } 3583 3584 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is 3585 * known to contain a variable offset. 3586 * This function checks whether the write is permitted and conservatively 3587 * tracks the effects of the write, considering that each stack slot in the 3588 * dynamic range is potentially written to. 3589 * 3590 * 'value_regno' can be -1, meaning that an unknown value is being written to 3591 * the stack. 3592 * 3593 * Spilled pointers in range are not marked as written because we don't know 3594 * what's going to be actually written. This means that read propagation for 3595 * future reads cannot be terminated by this write. 3596 * 3597 * For privileged programs, uninitialized stack slots are considered 3598 * initialized by this write (even though we don't know exactly what offsets 3599 * are going to be written to). The idea is that we don't want the verifier to 3600 * reject future reads that access slots written to through variable offsets. 3601 */ 3602 static int check_stack_write_var_off(struct bpf_verifier_env *env, 3603 /* func where register points to */ 3604 struct bpf_func_state *state, 3605 struct bpf_reg_state *ptr_reg, int off, int size, 3606 int value_regno, int insn_idx) 3607 { 3608 struct bpf_func_state *cur; /* state of the current function */ 3609 int min_off, max_off; 3610 int i, err; 3611 struct bpf_reg_state *value_reg = NULL; 3612 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3613 bool writing_zero = false; 3614 /* set if the fact that we're writing a zero is used to let any 3615 * stack slots remain STACK_ZERO 3616 */ 3617 bool zero_used = false; 3618 3619 cur = env->cur_state->frame[env->cur_state->curframe]; 3620 min_off = reg_smin(ptr_reg) + off; 3621 max_off = reg_smax(ptr_reg) + off + size; 3622 if (value_regno >= 0) 3623 value_reg = &cur->regs[value_regno]; 3624 if ((value_reg && bpf_register_is_null(value_reg)) || 3625 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 3626 writing_zero = true; 3627 3628 for (i = min_off; i < max_off; i++) { 3629 int spi; 3630 3631 spi = bpf_get_spi(i); 3632 err = destroy_if_dynptr_stack_slot(env, state, spi); 3633 if (err) 3634 return err; 3635 } 3636 3637 check_fastcall_stack_contract(env, state, insn_idx, min_off); 3638 /* Variable offset writes destroy any spilled pointers in range. */ 3639 for (i = min_off; i < max_off; i++) { 3640 u8 new_type, *stype; 3641 int slot, spi; 3642 3643 slot = -i - 1; 3644 spi = slot / BPF_REG_SIZE; 3645 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 3646 mark_stack_slot_scratched(env, spi); 3647 3648 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 3649 /* Reject the write if range we may write to has not 3650 * been initialized beforehand. If we didn't reject 3651 * here, the ptr status would be erased below (even 3652 * though not all slots are actually overwritten), 3653 * possibly opening the door to leaks. 3654 * 3655 * We do however catch STACK_INVALID case below, and 3656 * only allow reading possibly uninitialized memory 3657 * later for CAP_PERFMON, as the write may not happen to 3658 * that slot. 3659 */ 3660 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 3661 insn_idx, i); 3662 return -EINVAL; 3663 } 3664 3665 /* If writing_zero and the spi slot contains a spill of value 0, 3666 * maintain the spill type. 3667 */ 3668 if (writing_zero && *stype == STACK_SPILL && 3669 bpf_is_spilled_scalar_reg(&state->stack[spi])) { 3670 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 3671 3672 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 3673 zero_used = true; 3674 continue; 3675 } 3676 } 3677 3678 /* 3679 * Scrub slots if variable-offset stack write goes over spilled pointers. 3680 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT 3681 * and valid program is rejected by check_stack_read_fixed_off() 3682 * with obscure "invalid size of register fill" message. 3683 */ 3684 scrub_special_slot(state, spi); 3685 3686 /* Update the slot type. */ 3687 new_type = STACK_MISC; 3688 if (writing_zero && *stype == STACK_ZERO) { 3689 new_type = STACK_ZERO; 3690 zero_used = true; 3691 } 3692 /* If the slot is STACK_INVALID, we check whether it's OK to 3693 * pretend that it will be initialized by this write. The slot 3694 * might not actually be written to, and so if we mark it as 3695 * initialized future reads might leak uninitialized memory. 3696 * For privileged programs, we will accept such reads to slots 3697 * that may or may not be written because, if we're reject 3698 * them, the error would be too confusing. 3699 * Conservatively, treat STACK_POISON in a similar way. 3700 */ 3701 if ((*stype == STACK_INVALID || *stype == STACK_POISON) && 3702 !env->allow_uninit_stack) { 3703 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 3704 insn_idx, i); 3705 return -EINVAL; 3706 } 3707 *stype = new_type; 3708 } 3709 if (zero_used) { 3710 /* backtracking doesn't work for STACK_ZERO yet. */ 3711 err = mark_chain_precision(env, value_regno); 3712 if (err) 3713 return err; 3714 } 3715 return 0; 3716 } 3717 3718 /* When register 'dst_regno' is assigned some values from stack[min_off, 3719 * max_off), we set the register's type according to the types of the 3720 * respective stack slots. If all the stack values are known to be zeros, then 3721 * so is the destination reg. Otherwise, the register is considered to be 3722 * SCALAR. This function does not deal with register filling; the caller must 3723 * ensure that all spilled registers in the stack range have been marked as 3724 * read. 3725 * 3726 * STACK_SPILL bytes backed by spilled scalar const zeroes are also considered 3727 * zero bytes. In that case, mark the contributing stack slots precise so 3728 * pruning cannot reuse a zero-spill state for a later non-zero spill state. 3729 * 3730 * Returns an error if precision backtracking fails. 3731 */ 3732 static int mark_reg_stack_read(struct bpf_verifier_env *env, 3733 /* func where src register points to */ 3734 struct bpf_func_state *ptr_state, 3735 int min_off, int max_off, int dst_regno) 3736 { 3737 struct bpf_verifier_state *vstate = env->cur_state; 3738 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3739 u64 zero_spill_mask = 0; 3740 int i, slot, spi; 3741 u8 *stype; 3742 int zeros = 0; 3743 3744 for (i = min_off; i < max_off; i++) { 3745 slot = -i - 1; 3746 spi = slot / BPF_REG_SIZE; 3747 mark_stack_slot_scratched(env, spi); 3748 stype = ptr_state->stack[spi].slot_type; 3749 if (stype[slot % BPF_REG_SIZE] == STACK_ZERO) { 3750 zeros++; 3751 continue; 3752 } 3753 if (stype[slot % BPF_REG_SIZE] == STACK_SPILL && 3754 bpf_register_is_null(&ptr_state->stack[spi].spilled_ptr)) { 3755 zero_spill_mask |= 1ull << spi; 3756 zeros++; 3757 continue; 3758 } 3759 break; 3760 } 3761 if (zeros == max_off - min_off) { 3762 /* Any access_size read into register is zero extended, 3763 * so the whole register == const_zero. 3764 */ 3765 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3766 if (zero_spill_mask) { 3767 bpf_bt_set_frame_slot_mask(&env->bt, ptr_state->frameno, zero_spill_mask); 3768 return mark_chain_precision_batch(env, env->cur_state); 3769 } 3770 } else { 3771 /* have read misc data from the stack */ 3772 mark_reg_unknown(env, state->regs, dst_regno); 3773 } 3774 3775 return 0; 3776 } 3777 3778 /* Read the stack at 'off' and put the results into the register indicated by 3779 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 3780 * spilled reg. 3781 * 3782 * 'dst_regno' can be -1, meaning that the read value is not going to a 3783 * register. 3784 * 3785 * The access is assumed to be within the current stack bounds. 3786 */ 3787 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 3788 /* func where src register points to */ 3789 struct bpf_func_state *reg_state, 3790 int off, int size, int dst_regno) 3791 { 3792 struct bpf_verifier_state *vstate = env->cur_state; 3793 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3794 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 3795 struct bpf_reg_state *reg; 3796 u8 *stype, type; 3797 int err; 3798 int insn_flags = INSN_F_STACK_ACCESS; 3799 int hist_spi = spi, hist_frame = reg_state->frameno; 3800 3801 stype = reg_state->stack[spi].slot_type; 3802 reg = ®_state->stack[spi].spilled_ptr; 3803 3804 mark_stack_slot_scratched(env, spi); 3805 check_fastcall_stack_contract(env, state, env->insn_idx, off); 3806 3807 if (bpf_is_spilled_reg(®_state->stack[spi])) { 3808 u8 spill_size = 1; 3809 3810 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 3811 spill_size++; 3812 3813 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 3814 if (reg->type != SCALAR_VALUE) { 3815 verbose_linfo(env, env->insn_idx, "; "); 3816 verbose(env, "invalid size of register fill\n"); 3817 return -EACCES; 3818 } 3819 3820 if (dst_regno < 0) 3821 return 0; 3822 3823 if (size <= spill_size && 3824 bpf_stack_narrow_access_ok(off, size, spill_size)) { 3825 /* The earlier check_reg_arg() has decided the 3826 * subreg_def for this insn. Save it first. 3827 */ 3828 s32 subreg_def = state->regs[dst_regno].subreg_def; 3829 3830 if (env->bpf_capable && size == 4 && spill_size == 4 && 3831 get_reg_width(reg) <= 32) 3832 /* Ensure stack slot has an ID to build a relation 3833 * with the destination register on fill. 3834 */ 3835 assign_scalar_id_before_mov(env, reg); 3836 state->regs[dst_regno] = *reg; 3837 state->regs[dst_regno].subreg_def = subreg_def; 3838 3839 /* Break the relation on a narrowing fill. 3840 * coerce_reg_to_size will adjust the boundaries. 3841 */ 3842 if (get_reg_width(reg) > size * BITS_PER_BYTE) 3843 clear_scalar_id(&state->regs[dst_regno]); 3844 } else { 3845 int spill_cnt = 0, zero_cnt = 0; 3846 3847 for (i = 0; i < size; i++) { 3848 type = stype[(slot - i) % BPF_REG_SIZE]; 3849 if (type == STACK_SPILL) { 3850 spill_cnt++; 3851 continue; 3852 } 3853 if (type == STACK_MISC) 3854 continue; 3855 if (type == STACK_ZERO) { 3856 zero_cnt++; 3857 continue; 3858 } 3859 if (type == STACK_INVALID && env->allow_uninit_stack) 3860 continue; 3861 if (type == STACK_POISON) { 3862 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3863 off, i, size); 3864 } else { 3865 verbose(env, "invalid read from stack off %d+%d size %d\n", 3866 off, i, size); 3867 } 3868 return -EACCES; 3869 } 3870 3871 if (spill_cnt == size && 3872 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 3873 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3874 /* this IS register fill, so keep insn_flags */ 3875 } else if (zero_cnt == size) { 3876 /* similarly to mark_reg_stack_read(), preserve zeroes */ 3877 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3878 insn_flags = 0; /* not restoring original register state */ 3879 } else { 3880 err = mark_reg_stack_read(env, reg_state, off, off + size, 3881 dst_regno); 3882 if (err) 3883 return err; 3884 insn_flags = 0; /* not restoring original register state */ 3885 } 3886 } 3887 } else if (dst_regno >= 0) { 3888 /* restore register state from stack */ 3889 if (env->bpf_capable) 3890 /* Ensure stack slot has an ID to build a relation 3891 * with the destination register on fill. 3892 */ 3893 assign_scalar_id_before_mov(env, reg); 3894 state->regs[dst_regno] = *reg; 3895 /* mark reg as written since spilled pointer state likely 3896 * has its liveness marks cleared by is_state_visited() 3897 * which resets stack/reg liveness for state transitions 3898 */ 3899 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 3900 /* If dst_regno==-1, the caller is asking us whether 3901 * it is acceptable to use this value as a SCALAR_VALUE 3902 * (e.g. for XADD). 3903 * We must not allow unprivileged callers to do that 3904 * with spilled pointers. 3905 */ 3906 verbose(env, "leaking pointer from stack off %d\n", 3907 off); 3908 return -EACCES; 3909 } 3910 } else { 3911 for (i = 0; i < size; i++) { 3912 type = stype[(slot - i) % BPF_REG_SIZE]; 3913 if (type == STACK_MISC) 3914 continue; 3915 if (type == STACK_ZERO) 3916 continue; 3917 if (type == STACK_INVALID && env->allow_uninit_stack) 3918 continue; 3919 if (type == STACK_POISON) { 3920 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3921 off, i, size); 3922 } else { 3923 verbose(env, "invalid read from stack off %d+%d size %d\n", 3924 off, i, size); 3925 } 3926 return -EACCES; 3927 } 3928 if (dst_regno >= 0) { 3929 err = mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3930 if (err) 3931 return err; 3932 } 3933 insn_flags = 0; /* we are not restoring spilled register */ 3934 } 3935 if (insn_flags) 3936 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3937 hist_spi, hist_frame, 0); 3938 return 0; 3939 } 3940 3941 enum bpf_access_src { 3942 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3943 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3944 }; 3945 3946 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3947 argno_t argno, int off, int access_size, 3948 bool zero_size_allowed, 3949 enum bpf_access_type type, 3950 struct bpf_call_arg_meta *meta); 3951 3952 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3953 { 3954 return cur_regs(env) + regno; 3955 } 3956 3957 /* Read the stack at 'reg + off' and put the result into the register 3958 * 'dst_regno'. 3959 * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'), 3960 * but not its variable offset. 3961 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3962 * 3963 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3964 * filling registers (i.e. reads of spilled register cannot be detected when 3965 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3966 * SCALAR_VALUE. That's why we assert that the 'reg' has a variable 3967 * offset; for a fixed offset check_stack_read_fixed_off should be used 3968 * instead. 3969 */ 3970 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3971 argno_t ptr_argno, int off, int size, int dst_regno) 3972 { 3973 struct bpf_func_state *ptr_state = bpf_func(env, reg); 3974 int err; 3975 int min_off, max_off; 3976 3977 /* Note that we pass a NULL meta, so raw access will not be permitted. 3978 */ 3979 err = check_stack_range_initialized(env, reg, ptr_argno, off, size, 3980 false, BPF_READ, NULL); 3981 if (err) 3982 return err; 3983 3984 min_off = reg_smin(reg) + off; 3985 max_off = reg_smax(reg) + off; 3986 err = mark_reg_stack_read(env, ptr_state, min_off, max_off + size, 3987 dst_regno); 3988 if (err) 3989 return err; 3990 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 3991 return 0; 3992 } 3993 3994 /* check_stack_read dispatches to check_stack_read_fixed_off or 3995 * check_stack_read_var_off. 3996 * 3997 * The caller must ensure that the offset falls within the allocated stack 3998 * bounds. 3999 * 4000 * 'dst_regno' is a register which will receive the value from the stack. It 4001 * can be -1, meaning that the read value is not going to a register. 4002 */ 4003 static int check_stack_read(struct bpf_verifier_env *env, 4004 struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size, 4005 int dst_regno) 4006 { 4007 struct bpf_func_state *state = bpf_func(env, reg); 4008 int err; 4009 /* Some accesses are only permitted with a static offset. */ 4010 bool var_off = !tnum_is_const(reg->var_off); 4011 4012 /* The offset is required to be static when reads don't go to a 4013 * register, in order to not leak pointers (see 4014 * check_stack_read_fixed_off). 4015 */ 4016 if (dst_regno < 0 && var_off) { 4017 char tn_buf[48]; 4018 4019 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4020 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4021 tn_buf, off, size); 4022 return -EACCES; 4023 } 4024 /* Variable offset is prohibited for unprivileged mode for simplicity 4025 * since it requires corresponding support in Spectre masking for stack 4026 * ALU. See also retrieve_ptr_limit(). The check in 4027 * check_stack_access_for_ptr_arithmetic() called by 4028 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4029 * with variable offsets, therefore no check is required here. Further, 4030 * just checking it here would be insufficient as speculative stack 4031 * writes could still lead to unsafe speculative behaviour. 4032 */ 4033 if (!var_off) { 4034 off += reg->var_off.value; 4035 err = check_stack_read_fixed_off(env, state, off, size, 4036 dst_regno); 4037 } else { 4038 /* Variable offset stack reads need more conservative handling 4039 * than fixed offset ones. Note that dst_regno >= 0 on this 4040 * branch. 4041 */ 4042 err = check_stack_read_var_off(env, reg, ptr_argno, off, size, 4043 dst_regno); 4044 } 4045 return err; 4046 } 4047 4048 4049 /* check_stack_write dispatches to check_stack_write_fixed_off or 4050 * check_stack_write_var_off. 4051 * 4052 * 'reg' is the register used as a pointer into the stack. 4053 * 'value_regno' is the register whose value we're writing to the stack. It can 4054 * be -1, meaning that we're not writing from a register. 4055 * 4056 * The caller must ensure that the offset falls within the maximum stack size. 4057 */ 4058 static int check_stack_write(struct bpf_verifier_env *env, 4059 struct bpf_reg_state *reg, int off, int size, 4060 int value_regno, int insn_idx) 4061 { 4062 struct bpf_func_state *state = bpf_func(env, reg); 4063 int err; 4064 4065 if (tnum_is_const(reg->var_off)) { 4066 off += reg->var_off.value; 4067 err = check_stack_write_fixed_off(env, state, off, size, 4068 value_regno, insn_idx); 4069 } else { 4070 /* Variable offset stack reads need more conservative handling 4071 * than fixed offset ones. 4072 */ 4073 err = check_stack_write_var_off(env, state, 4074 reg, off, size, 4075 value_regno, insn_idx); 4076 } 4077 return err; 4078 } 4079 4080 /* 4081 * Write a value to the outgoing stack arg area. 4082 * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7). 4083 */ 4084 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state, 4085 int off, struct bpf_reg_state *value_reg) 4086 { 4087 int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS; 4088 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4089 int spi = -off / BPF_REG_SIZE - 1; 4090 struct bpf_reg_state *arg; 4091 int err; 4092 4093 if (spi >= max_stack_arg_regs) { 4094 verbose(env, "stack arg write offset %d exceeds max %d stack args\n", 4095 off, max_stack_arg_regs); 4096 return -EINVAL; 4097 } 4098 4099 err = grow_stack_arg_slots(env, state, spi + 1); 4100 if (err) 4101 return err; 4102 4103 /* Track the max outgoing stack arg slot count. */ 4104 if (spi + 1 > subprog->max_out_stack_arg_cnt) 4105 subprog->max_out_stack_arg_cnt = spi + 1; 4106 4107 if (value_reg) { 4108 state->stack_arg_regs[spi] = *value_reg; 4109 } else { 4110 /* BPF_ST: store immediate, treat as scalar */ 4111 arg = &state->stack_arg_regs[spi]; 4112 arg->type = SCALAR_VALUE; 4113 __mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm); 4114 } 4115 state->no_stack_arg_load = true; 4116 return bpf_push_jmp_history(env, env->cur_state, 4117 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4118 } 4119 4120 /* 4121 * Read a value from the incoming stack arg area. 4122 * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7). 4123 */ 4124 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state, 4125 int off, int dst_regno) 4126 { 4127 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4128 struct bpf_verifier_state *vstate = env->cur_state; 4129 int spi = off / BPF_REG_SIZE - 1; 4130 struct bpf_func_state *caller, *cur; 4131 struct bpf_reg_state *arg; 4132 4133 if (state->no_stack_arg_load) { 4134 verbose(env, "r11 load must be before any r11 store or call insn\n"); 4135 return -EINVAL; 4136 } 4137 4138 if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) { 4139 verbose(env, "invalid read from stack arg off %d depth %d\n", 4140 off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE); 4141 return -EACCES; 4142 } 4143 4144 caller = vstate->frame[vstate->curframe - 1]; 4145 arg = &caller->stack_arg_regs[spi]; 4146 cur = vstate->frame[vstate->curframe]; 4147 cur->regs[dst_regno] = *arg; 4148 return bpf_push_jmp_history(env, env->cur_state, 4149 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4150 } 4151 4152 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx) 4153 { 4154 struct bpf_func_state *caller = cur_func(env); 4155 int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS; 4156 4157 bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi); 4158 return mark_chain_precision_batch(env, env->cur_state); 4159 } 4160 4161 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller, 4162 int nargs) 4163 { 4164 int i, spi; 4165 4166 for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) { 4167 spi = i - MAX_BPF_FUNC_REG_ARGS; 4168 if (spi >= caller->out_stack_arg_cnt || 4169 caller->stack_arg_regs[spi].type == NOT_INIT) { 4170 verbose(env, "callee expects %d args, stack arg%d is not initialized\n", 4171 nargs, spi + 1); 4172 return -EFAULT; 4173 } 4174 } 4175 4176 return 0; 4177 } 4178 4179 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller, 4180 struct bpf_reg_state *regs, int arg) 4181 { 4182 if (arg < MAX_BPF_FUNC_REG_ARGS) 4183 return ®s[arg + 1]; 4184 4185 return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS]; 4186 } 4187 4188 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4189 int off, int size, enum bpf_access_type type) 4190 { 4191 struct bpf_map *map = reg->map_ptr; 4192 u32 cap = bpf_map_flags_to_cap(map); 4193 4194 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4195 verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n", 4196 map->value_size, reg_smin(reg) + off, size); 4197 return -EACCES; 4198 } 4199 4200 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4201 verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n", 4202 map->value_size, reg_smin(reg) + off, size); 4203 return -EACCES; 4204 } 4205 4206 return 0; 4207 } 4208 4209 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4210 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4211 int off, int size, u32 mem_size, 4212 bool zero_size_allowed) 4213 { 4214 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4215 4216 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4217 return 0; 4218 4219 switch (reg->type) { 4220 case PTR_TO_MAP_KEY: 4221 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4222 mem_size, off, size); 4223 break; 4224 case PTR_TO_MAP_VALUE: 4225 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4226 mem_size, off, size); 4227 break; 4228 case PTR_TO_PACKET: 4229 case PTR_TO_PACKET_META: 4230 case PTR_TO_PACKET_END: 4231 verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n", 4232 off, size, reg_arg_name(env, argno), reg->id, off, mem_size); 4233 break; 4234 case PTR_TO_CTX: 4235 verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n", 4236 mem_size, off, size); 4237 break; 4238 case PTR_TO_MEM: 4239 default: 4240 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4241 mem_size, off, size); 4242 } 4243 4244 return -EACCES; 4245 } 4246 4247 /* check read/write into a memory region with possible variable offset */ 4248 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4249 int off, int size, u32 mem_size, 4250 bool zero_size_allowed) 4251 { 4252 int err; 4253 4254 /* We may have adjusted the register pointing to memory region, so we 4255 * need to try adding each of min_value and max_value to off 4256 * to make sure our theoretical access will be safe. 4257 * 4258 * The minimum value is only important with signed 4259 * comparisons where we can't assume the floor of a 4260 * value is 0. If we are using signed variables for our 4261 * index'es we need to make sure that whatever we use 4262 * will have a set floor within our range. 4263 */ 4264 if (reg_smin(reg) < 0 && 4265 (reg_smin(reg) == S64_MIN || 4266 (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) || 4267 reg_smin(reg) + off < 0)) { 4268 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4269 reg_arg_name(env, argno)); 4270 return -EACCES; 4271 } 4272 err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size, 4273 mem_size, zero_size_allowed); 4274 if (err) { 4275 verbose(env, "%s min value is outside of the allowed memory range\n", 4276 reg_arg_name(env, argno)); 4277 return err; 4278 } 4279 4280 /* If we haven't set a max value then we need to bail since we can't be 4281 * sure we won't do bad things. 4282 * If reg_umax(reg) + off could overflow, treat that as unbounded too. 4283 */ 4284 if (reg_umax(reg) >= BPF_MAX_VAR_OFF) { 4285 verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n", 4286 reg_arg_name(env, argno)); 4287 return -EACCES; 4288 } 4289 err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size, 4290 mem_size, zero_size_allowed); 4291 if (err) { 4292 verbose(env, "%s max value is outside of the allowed memory range\n", 4293 reg_arg_name(env, argno)); 4294 return err; 4295 } 4296 4297 return 0; 4298 } 4299 4300 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4301 const struct bpf_reg_state *reg, argno_t argno, 4302 bool fixed_off_ok) 4303 { 4304 /* Access to this pointer-typed register or passing it to a helper 4305 * is only allowed in its original, unmodified form. 4306 */ 4307 4308 if (!tnum_is_const(reg->var_off)) { 4309 char tn_buf[48]; 4310 4311 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4312 verbose(env, "variable %s access var_off=%s disallowed\n", 4313 reg_type_str(env, reg->type), tn_buf); 4314 return -EACCES; 4315 } 4316 4317 if (reg_smin(reg) < 0) { 4318 verbose(env, "negative offset %s ptr %s off=%lld disallowed\n", 4319 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4320 return -EACCES; 4321 } 4322 4323 if (!fixed_off_ok && reg->var_off.value != 0) { 4324 verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n", 4325 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4326 return -EACCES; 4327 } 4328 4329 return 0; 4330 } 4331 4332 static int check_ptr_off_reg(struct bpf_verifier_env *env, 4333 const struct bpf_reg_state *reg, int regno) 4334 { 4335 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 4336 } 4337 4338 static int map_kptr_match_type(struct bpf_verifier_env *env, 4339 struct btf_field *kptr_field, 4340 struct bpf_reg_state *reg, u32 regno) 4341 { 4342 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4343 int perm_flags; 4344 const char *reg_name = ""; 4345 4346 if (base_type(reg->type) != PTR_TO_BTF_ID) 4347 goto bad_type; 4348 4349 if (btf_is_kernel(reg->btf)) { 4350 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 4351 4352 /* Only unreferenced case accepts untrusted pointers */ 4353 if (kptr_field->type == BPF_KPTR_UNREF) 4354 perm_flags |= PTR_UNTRUSTED; 4355 } else { 4356 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 4357 if (kptr_field->type == BPF_KPTR_PERCPU) 4358 perm_flags |= MEM_PERCPU; 4359 } 4360 4361 if (type_flag(reg->type) & ~perm_flags) 4362 goto bad_type; 4363 4364 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4365 reg_name = btf_type_name(reg->btf, reg->btf_id); 4366 4367 /* For ref_ptr case, release function check should ensure we get one 4368 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4369 * normal store of unreferenced kptr, we must ensure var_off is zero. 4370 * Since ref_ptr cannot be accessed directly by BPF insns, check for 4371 * reg->id is not needed here. 4372 */ 4373 if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true)) 4374 return -EACCES; 4375 4376 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 4377 * we also need to take into account the reg->var_off. 4378 * 4379 * We want to support cases like: 4380 * 4381 * struct foo { 4382 * struct bar br; 4383 * struct baz bz; 4384 * }; 4385 * 4386 * struct foo *v; 4387 * v = func(); // PTR_TO_BTF_ID 4388 * val->foo = v; // reg->var_off is zero, btf and btf_id match type 4389 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with 4390 * // first member type of struct after comparison fails 4391 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked 4392 * // to match type 4393 * 4394 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off 4395 * is zero. We must also ensure that btf_struct_ids_match does not walk 4396 * the struct to match type against first member of struct, i.e. reject 4397 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4398 * strict mode to true for type match. 4399 */ 4400 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value, 4401 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4402 kptr_field->type != BPF_KPTR_UNREF, 4403 !type_is_alloc(reg->type))) 4404 goto bad_type; 4405 return 0; 4406 bad_type: 4407 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4408 reg_type_str(env, reg->type), reg_name); 4409 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4410 if (kptr_field->type == BPF_KPTR_UNREF) 4411 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4412 targ_name); 4413 else 4414 verbose(env, "\n"); 4415 return -EINVAL; 4416 } 4417 4418 static bool in_sleepable(struct bpf_verifier_env *env) 4419 { 4420 return env->cur_state->in_sleepable; 4421 } 4422 4423 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 4424 * can dereference RCU protected pointers and result is PTR_TRUSTED. 4425 */ 4426 static bool in_rcu_cs(struct bpf_verifier_env *env) 4427 { 4428 return env->cur_state->active_rcu_locks || 4429 env->cur_state->active_locks || 4430 !in_sleepable(env); 4431 } 4432 4433 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 4434 BTF_SET_START(rcu_protected_types) 4435 #ifdef CONFIG_NET 4436 BTF_ID(struct, prog_test_ref_kfunc) 4437 #endif 4438 #ifdef CONFIG_CGROUPS 4439 BTF_ID(struct, cgroup) 4440 #endif 4441 #ifdef CONFIG_BPF_JIT 4442 BTF_ID(struct, bpf_cpumask) 4443 #endif 4444 BTF_ID(struct, task_struct) 4445 #ifdef CONFIG_CRYPTO 4446 BTF_ID(struct, bpf_crypto_ctx) 4447 #endif 4448 BTF_SET_END(rcu_protected_types) 4449 4450 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 4451 { 4452 if (!btf_is_kernel(btf)) 4453 return true; 4454 return btf_id_set_contains(&rcu_protected_types, btf_id); 4455 } 4456 4457 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 4458 { 4459 struct btf_struct_meta *meta; 4460 4461 if (btf_is_kernel(kptr_field->kptr.btf)) 4462 return NULL; 4463 4464 meta = btf_find_struct_meta(kptr_field->kptr.btf, 4465 kptr_field->kptr.btf_id); 4466 4467 return meta ? meta->record : NULL; 4468 } 4469 4470 static bool rcu_safe_kptr(const struct btf_field *field) 4471 { 4472 const struct btf_field_kptr *kptr = &field->kptr; 4473 4474 return field->type == BPF_KPTR_PERCPU || 4475 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 4476 } 4477 4478 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 4479 { 4480 struct btf_record *rec; 4481 u32 ret; 4482 4483 ret = PTR_MAYBE_NULL; 4484 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 4485 ret |= MEM_RCU; 4486 if (kptr_field->type == BPF_KPTR_PERCPU) 4487 ret |= MEM_PERCPU; 4488 else if (!btf_is_kernel(kptr_field->kptr.btf)) 4489 ret |= MEM_ALLOC; 4490 4491 rec = kptr_pointee_btf_record(kptr_field); 4492 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 4493 ret |= NON_OWN_REF; 4494 } else { 4495 ret |= PTR_UNTRUSTED; 4496 } 4497 4498 return ret; 4499 } 4500 4501 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 4502 struct btf_field *field) 4503 { 4504 struct bpf_reg_state *reg; 4505 const struct btf_type *t; 4506 4507 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 4508 mark_reg_known_zero(env, cur_regs(env), regno); 4509 reg = reg_state(env, regno); 4510 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 4511 reg->mem_size = t->size; 4512 reg->id = ++env->id_gen; 4513 4514 return 0; 4515 } 4516 4517 static int check_map_kptr_access(struct bpf_verifier_env *env, 4518 int value_regno, int insn_idx, 4519 struct btf_field *kptr_field) 4520 { 4521 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4522 int class = BPF_CLASS(insn->code); 4523 struct bpf_reg_state *val_reg; 4524 int ret; 4525 4526 /* Things we already checked for in check_map_access and caller: 4527 * - Reject cases where variable offset may touch kptr 4528 * - size of access (must be BPF_DW) 4529 * - tnum_is_const(reg->var_off) 4530 * - kptr_field->offset == off + reg->var_off.value 4531 */ 4532 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4533 if (BPF_MODE(insn->code) != BPF_MEM) { 4534 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4535 return -EACCES; 4536 } 4537 4538 /* We only allow loading referenced kptr, since it will be marked as 4539 * untrusted, similar to unreferenced kptr. 4540 */ 4541 if (class != BPF_LDX && 4542 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 4543 verbose(env, "store to referenced kptr disallowed\n"); 4544 return -EACCES; 4545 } 4546 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 4547 verbose(env, "store to uptr disallowed\n"); 4548 return -EACCES; 4549 } 4550 4551 if (class == BPF_LDX) { 4552 if (kptr_field->type == BPF_UPTR) 4553 return mark_uptr_ld_reg(env, value_regno, kptr_field); 4554 4555 /* We can simply mark the value_regno receiving the pointer 4556 * value from map as PTR_TO_BTF_ID, with the correct type. 4557 */ 4558 ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, 4559 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4560 btf_ld_kptr_type(env, kptr_field)); 4561 if (ret < 0) 4562 return ret; 4563 } else if (class == BPF_STX) { 4564 val_reg = reg_state(env, value_regno); 4565 if (!bpf_register_is_null(val_reg) && 4566 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4567 return -EACCES; 4568 } else if (class == BPF_ST) { 4569 if (insn->imm) { 4570 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4571 kptr_field->offset); 4572 return -EACCES; 4573 } 4574 } else { 4575 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4576 return -EACCES; 4577 } 4578 return 0; 4579 } 4580 4581 /* 4582 * Return the size of the memory region accessible from a pointer to map value. 4583 * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible. 4584 */ 4585 static u32 map_mem_size(const struct bpf_map *map) 4586 { 4587 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) 4588 return map->max_entries * sizeof(long); 4589 4590 return map->value_size; 4591 } 4592 4593 /* check read/write into a map element with possible variable offset */ 4594 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4595 int off, int size, bool zero_size_allowed, 4596 enum bpf_access_src src) 4597 { 4598 struct bpf_map *map = reg->map_ptr; 4599 u32 mem_size = map_mem_size(map); 4600 struct btf_record *rec; 4601 int err, i; 4602 4603 err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed); 4604 if (err) 4605 return err; 4606 4607 if (IS_ERR_OR_NULL(map->record)) 4608 return 0; 4609 rec = map->record; 4610 for (i = 0; i < rec->cnt; i++) { 4611 struct btf_field *field = &rec->fields[i]; 4612 u32 p = field->offset; 4613 4614 /* If any part of a field can be touched by load/store, reject 4615 * this program. To check that [x1, x2) overlaps with [y1, y2), 4616 * it is sufficient to check x1 < y2 && y1 < x2. 4617 */ 4618 if (reg_smin(reg) + off < p + field->size && 4619 p < reg_umax(reg) + off + size) { 4620 switch (field->type) { 4621 case BPF_KPTR_UNREF: 4622 case BPF_KPTR_REF: 4623 case BPF_KPTR_PERCPU: 4624 case BPF_UPTR: 4625 if (src != ACCESS_DIRECT) { 4626 verbose(env, "%s cannot be accessed indirectly by helper\n", 4627 btf_field_type_name(field->type)); 4628 return -EACCES; 4629 } 4630 if (!tnum_is_const(reg->var_off)) { 4631 verbose(env, "%s access cannot have variable offset\n", 4632 btf_field_type_name(field->type)); 4633 return -EACCES; 4634 } 4635 if (p != off + reg->var_off.value) { 4636 verbose(env, "%s access misaligned expected=%u off=%llu\n", 4637 btf_field_type_name(field->type), 4638 p, off + reg->var_off.value); 4639 return -EACCES; 4640 } 4641 if (size != bpf_size_to_bytes(BPF_DW)) { 4642 verbose(env, "%s access size must be BPF_DW\n", 4643 btf_field_type_name(field->type)); 4644 return -EACCES; 4645 } 4646 break; 4647 default: 4648 verbose(env, "%s cannot be accessed directly by load/store\n", 4649 btf_field_type_name(field->type)); 4650 return -EACCES; 4651 } 4652 } 4653 } 4654 return 0; 4655 } 4656 4657 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4658 const struct bpf_func_proto *fn, 4659 enum bpf_access_type t) 4660 { 4661 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4662 4663 switch (prog_type) { 4664 /* Program types only with direct read access go here! */ 4665 case BPF_PROG_TYPE_LWT_IN: 4666 case BPF_PROG_TYPE_LWT_OUT: 4667 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4668 case BPF_PROG_TYPE_SK_REUSEPORT: 4669 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4670 case BPF_PROG_TYPE_CGROUP_SKB: 4671 if (t == BPF_WRITE) 4672 return false; 4673 fallthrough; 4674 4675 /* Program types with direct read + write access go here! */ 4676 case BPF_PROG_TYPE_SCHED_CLS: 4677 case BPF_PROG_TYPE_SCHED_ACT: 4678 case BPF_PROG_TYPE_XDP: 4679 case BPF_PROG_TYPE_LWT_XMIT: 4680 case BPF_PROG_TYPE_SK_SKB: 4681 case BPF_PROG_TYPE_SK_MSG: 4682 if (fn) 4683 return fn->pkt_access; 4684 4685 env->seen_direct_write = true; 4686 return true; 4687 4688 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4689 if (t == BPF_WRITE) 4690 env->seen_direct_write = true; 4691 4692 return true; 4693 4694 default: 4695 return false; 4696 } 4697 } 4698 4699 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 4700 int size, bool zero_size_allowed) 4701 { 4702 int err; 4703 4704 if (reg->range < 0) { 4705 verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno)); 4706 return -EINVAL; 4707 } 4708 4709 err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed); 4710 if (err) 4711 return err; 4712 4713 /* __check_mem_access has made sure "off + size - 1" is within u16. 4714 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff, 4715 * otherwise find_good_pkt_pointers would have refused to set range info 4716 * that __check_mem_access would have rejected this pkt access. 4717 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32. 4718 */ 4719 env->prog->aux->max_pkt_offset = 4720 max_t(u32, env->prog->aux->max_pkt_offset, 4721 off + reg_umax(reg) + size - 1); 4722 4723 return 0; 4724 } 4725 4726 static bool is_var_ctx_off_allowed(struct bpf_prog *prog) 4727 { 4728 return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL; 4729 } 4730 4731 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 4732 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 4733 enum bpf_access_type t, struct bpf_insn_access_aux *info) 4734 { 4735 if (env->ops->is_valid_access && 4736 env->ops->is_valid_access(off, size, t, env->prog, info)) { 4737 /* A non zero info.ctx_field_size indicates that this field is a 4738 * candidate for later verifier transformation to load the whole 4739 * field and then apply a mask when accessed with a narrower 4740 * access than actual ctx access size. A zero info.ctx_field_size 4741 * will only allow for whole field access and rejects any other 4742 * type of narrower access. 4743 */ 4744 if (base_type(info->reg_type) == PTR_TO_BTF_ID) { 4745 if (info->ref_id && 4746 !find_reference_state(env->cur_state, info->ref_id)) { 4747 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n", 4748 off); 4749 return -EACCES; 4750 } 4751 } else { 4752 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size; 4753 } 4754 /* remember the offset of last byte accessed in ctx */ 4755 if (env->prog->aux->max_ctx_offset < off + size) 4756 env->prog->aux->max_ctx_offset = off + size; 4757 return 0; 4758 } 4759 4760 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 4761 return -EACCES; 4762 } 4763 4764 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 4765 int off, int access_size, enum bpf_access_type t, 4766 struct bpf_insn_access_aux *info) 4767 { 4768 /* 4769 * Program types that don't rewrite ctx accesses can safely 4770 * dereference ctx pointers with fixed offsets. 4771 */ 4772 bool var_off_ok = is_var_ctx_off_allowed(env->prog); 4773 bool fixed_off_ok = !env->ops->convert_ctx_access; 4774 int err; 4775 4776 if (var_off_ok) 4777 err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false); 4778 else 4779 err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok); 4780 if (err) 4781 return err; 4782 off += reg_umax(reg); 4783 4784 err = __check_ctx_access(env, insn_idx, off, access_size, t, info); 4785 if (err) 4786 verbose_linfo(env, insn_idx, "; "); 4787 return err; 4788 } 4789 4790 static int check_flow_keys_access(struct bpf_verifier_env *env, 4791 struct bpf_reg_state *reg, argno_t argno, 4792 int off, int size) 4793 { 4794 /* Only a constant offset is allowed here; fold it into off. */ 4795 if (!tnum_is_const(reg->var_off)) { 4796 char tn_buf[48]; 4797 4798 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4799 verbose(env, "%s invalid variable offset to flow keys: off=%d, var_off=%s\n", 4800 reg_arg_name(env, argno), off, tn_buf); 4801 return -EACCES; 4802 } 4803 off += reg->var_off.value; 4804 4805 if (size < 0 || off < 0 || 4806 (u64)off + size > sizeof(struct bpf_flow_keys)) { 4807 verbose(env, "invalid access to flow keys off=%d size=%d\n", 4808 off, size); 4809 return -EACCES; 4810 } 4811 return 0; 4812 } 4813 4814 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 4815 struct bpf_reg_state *reg, argno_t argno, int off, int size, 4816 enum bpf_access_type t) 4817 { 4818 struct bpf_insn_access_aux info = {}; 4819 bool valid; 4820 4821 if (reg_smin(reg) < 0) { 4822 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4823 reg_arg_name(env, argno)); 4824 return -EACCES; 4825 } 4826 4827 switch (reg->type) { 4828 case PTR_TO_SOCK_COMMON: 4829 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 4830 break; 4831 case PTR_TO_SOCKET: 4832 valid = bpf_sock_is_valid_access(off, size, t, &info); 4833 break; 4834 case PTR_TO_TCP_SOCK: 4835 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 4836 break; 4837 case PTR_TO_XDP_SOCK: 4838 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 4839 break; 4840 default: 4841 valid = false; 4842 } 4843 4844 4845 if (valid) { 4846 env->insn_aux_data[insn_idx].ctx_field_size = 4847 info.ctx_field_size; 4848 return 0; 4849 } 4850 4851 verbose(env, "%s invalid %s access off=%d size=%d\n", 4852 reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size); 4853 4854 return -EACCES; 4855 } 4856 4857 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 4858 { 4859 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 4860 } 4861 4862 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 4863 { 4864 const struct bpf_reg_state *reg = reg_state(env, regno); 4865 4866 return reg->type == PTR_TO_CTX; 4867 } 4868 4869 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 4870 { 4871 const struct bpf_reg_state *reg = reg_state(env, regno); 4872 4873 return type_is_sk_pointer(reg->type); 4874 } 4875 4876 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 4877 { 4878 const struct bpf_reg_state *reg = reg_state(env, regno); 4879 4880 return type_is_pkt_pointer(reg->type); 4881 } 4882 4883 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 4884 { 4885 const struct bpf_reg_state *reg = reg_state(env, regno); 4886 4887 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 4888 return reg->type == PTR_TO_FLOW_KEYS; 4889 } 4890 4891 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 4892 { 4893 const struct bpf_reg_state *reg = reg_state(env, regno); 4894 4895 return reg->type == PTR_TO_ARENA; 4896 } 4897 4898 /* Return false if @regno contains a pointer whose type isn't supported for 4899 * atomic instruction @insn. 4900 */ 4901 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno, 4902 struct bpf_insn *insn) 4903 { 4904 if (is_ctx_reg(env, regno)) 4905 return false; 4906 if (is_pkt_reg(env, regno)) 4907 return false; 4908 if (is_flow_key_reg(env, regno)) 4909 return false; 4910 if (is_sk_reg(env, regno)) 4911 return false; 4912 if (is_arena_reg(env, regno)) 4913 return bpf_jit_supports_insn(insn, true); 4914 4915 return true; 4916 } 4917 4918 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 4919 #ifdef CONFIG_NET 4920 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 4921 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 4922 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 4923 #endif 4924 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 4925 }; 4926 4927 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 4928 { 4929 /* A referenced register is always trusted. */ 4930 if (reg_is_referenced(env, reg)) 4931 return true; 4932 4933 /* Types listed in the reg2btf_ids are always trusted */ 4934 if (reg2btf_ids[base_type(reg->type)] && 4935 !bpf_type_has_unsafe_modifiers(reg->type)) 4936 return true; 4937 4938 /* If a register is not referenced, it is trusted if it has the 4939 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 4940 * other type modifiers may be safe, but we elect to take an opt-in 4941 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 4942 * not. 4943 * 4944 * Eventually, we should make PTR_TRUSTED the single source of truth 4945 * for whether a register is trusted. 4946 */ 4947 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 4948 !bpf_type_has_unsafe_modifiers(reg->type); 4949 } 4950 4951 static bool is_rcu_reg(const struct bpf_reg_state *reg) 4952 { 4953 return reg->type & MEM_RCU; 4954 } 4955 4956 static void clear_trusted_flags(enum bpf_type_flag *flag) 4957 { 4958 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 4959 } 4960 4961 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 4962 const struct bpf_reg_state *reg, 4963 int off, int size, bool strict) 4964 { 4965 struct tnum reg_off; 4966 int ip_align; 4967 4968 /* Byte size accesses are always allowed. */ 4969 if (!strict || size == 1) 4970 return 0; 4971 4972 /* For platforms that do not have a Kconfig enabling 4973 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 4974 * NET_IP_ALIGN is universally set to '2'. And on platforms 4975 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 4976 * to this code only in strict mode where we want to emulate 4977 * the NET_IP_ALIGN==2 checking. Therefore use an 4978 * unconditional IP align value of '2'. 4979 */ 4980 ip_align = 2; 4981 4982 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off)); 4983 if (!tnum_is_aligned(reg_off, size)) { 4984 char tn_buf[48]; 4985 4986 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4987 verbose(env, 4988 "misaligned packet access off %d+%s+%d size %d\n", 4989 ip_align, tn_buf, off, size); 4990 return -EACCES; 4991 } 4992 4993 return 0; 4994 } 4995 4996 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 4997 const struct bpf_reg_state *reg, 4998 const char *pointer_desc, 4999 int off, int size, bool strict) 5000 { 5001 struct tnum reg_off; 5002 5003 /* Byte size accesses are always allowed. */ 5004 if (!strict || size == 1) 5005 return 0; 5006 5007 reg_off = tnum_add(reg->var_off, tnum_const(off)); 5008 if (!tnum_is_aligned(reg_off, size)) { 5009 char tn_buf[48]; 5010 5011 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5012 verbose(env, "misaligned %saccess off %s+%d size %d\n", 5013 pointer_desc, tn_buf, off, size); 5014 return -EACCES; 5015 } 5016 5017 return 0; 5018 } 5019 5020 static int check_ptr_alignment(struct bpf_verifier_env *env, 5021 const struct bpf_reg_state *reg, int off, 5022 int size, bool strict_alignment_once) 5023 { 5024 bool strict = env->strict_alignment || strict_alignment_once; 5025 const char *pointer_desc = ""; 5026 5027 switch (reg->type) { 5028 case PTR_TO_PACKET: 5029 case PTR_TO_PACKET_META: 5030 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5031 * right in front, treat it the very same way. 5032 */ 5033 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5034 case PTR_TO_FLOW_KEYS: 5035 pointer_desc = "flow keys "; 5036 break; 5037 case PTR_TO_MAP_KEY: 5038 pointer_desc = "key "; 5039 break; 5040 case PTR_TO_MAP_VALUE: 5041 pointer_desc = "value "; 5042 if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY) 5043 strict = true; 5044 break; 5045 case PTR_TO_CTX: 5046 pointer_desc = "context "; 5047 break; 5048 case PTR_TO_STACK: 5049 pointer_desc = "stack "; 5050 /* The stack spill tracking logic in check_stack_write_fixed_off() 5051 * and check_stack_read_fixed_off() relies on stack accesses being 5052 * aligned. 5053 */ 5054 strict = true; 5055 break; 5056 case PTR_TO_SOCKET: 5057 pointer_desc = "sock "; 5058 break; 5059 case PTR_TO_SOCK_COMMON: 5060 pointer_desc = "sock_common "; 5061 break; 5062 case PTR_TO_TCP_SOCK: 5063 pointer_desc = "tcp_sock "; 5064 break; 5065 case PTR_TO_XDP_SOCK: 5066 pointer_desc = "xdp_sock "; 5067 break; 5068 case PTR_TO_ARENA: 5069 return 0; 5070 default: 5071 break; 5072 } 5073 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5074 strict); 5075 } 5076 5077 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 5078 { 5079 if (!bpf_jit_supports_private_stack()) 5080 return NO_PRIV_STACK; 5081 5082 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 5083 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 5084 * explicitly. 5085 */ 5086 switch (prog->type) { 5087 case BPF_PROG_TYPE_KPROBE: 5088 case BPF_PROG_TYPE_TRACEPOINT: 5089 case BPF_PROG_TYPE_PERF_EVENT: 5090 case BPF_PROG_TYPE_RAW_TRACEPOINT: 5091 return PRIV_STACK_ADAPTIVE; 5092 case BPF_PROG_TYPE_TRACING: 5093 case BPF_PROG_TYPE_LSM: 5094 case BPF_PROG_TYPE_STRUCT_OPS: 5095 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 5096 return PRIV_STACK_ADAPTIVE; 5097 fallthrough; 5098 default: 5099 break; 5100 } 5101 5102 return NO_PRIV_STACK; 5103 } 5104 5105 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5106 { 5107 if (env->prog->jit_requested) 5108 return round_up(stack_depth, 16); 5109 5110 /* round up to 32-bytes, since this is granularity 5111 * of interpreter stack size 5112 */ 5113 return round_up(max_t(u32, stack_depth, 1), 32); 5114 } 5115 5116 /* temporary state used for call frame depth calculation */ 5117 struct bpf_subprog_call_depth_info { 5118 int ret_insn; /* caller instruction where we return to. */ 5119 int caller; /* caller subprogram idx */ 5120 int frame; /* # of consecutive static call stack frames on top of stack */ 5121 }; 5122 5123 /* starting from main bpf function walk all instructions of the function 5124 * and recursively walk all callees that given function can call. 5125 * Ignore jump and exit insns. 5126 */ 5127 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 5128 struct bpf_subprog_call_depth_info *dinfo, 5129 bool priv_stack_supported) 5130 { 5131 struct bpf_subprog_info *subprog = env->subprog_info; 5132 struct bpf_insn *insn = env->prog->insnsi; 5133 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 5134 bool tail_call_reachable = false; 5135 int total; 5136 int tmp; 5137 5138 /* no caller idx */ 5139 dinfo[idx].caller = -1; 5140 5141 i = subprog[idx].start; 5142 if (!priv_stack_supported) 5143 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5144 process_func: 5145 /* protect against potential stack overflow that might happen when 5146 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5147 * depth for such case down to 256 so that the worst case scenario 5148 * would result in 8k stack size (32 which is tailcall limit * 256 = 5149 * 8k). 5150 * 5151 * To get the idea what might happen, see an example: 5152 * func1 -> sub rsp, 128 5153 * subfunc1 -> sub rsp, 256 5154 * tailcall1 -> add rsp, 256 5155 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5156 * subfunc2 -> sub rsp, 64 5157 * subfunc22 -> sub rsp, 128 5158 * tailcall2 -> add rsp, 128 5159 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5160 * 5161 * tailcall will unwind the current stack frame but it will not get rid 5162 * of caller's stack as shown on the example above. 5163 */ 5164 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5165 verbose(env, 5166 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5167 depth); 5168 return -EACCES; 5169 } 5170 5171 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 5172 if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) { 5173 /* x86-64 uses R9 for both private stack frame pointer and arg6. */ 5174 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5175 } else if (priv_stack_supported) { 5176 /* Request private stack support only if the subprog stack 5177 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 5178 * avoid jit penalty if the stack usage is small. 5179 */ 5180 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 5181 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 5182 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 5183 } 5184 5185 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5186 if (subprog_depth > env->max_stack_depth) 5187 env->max_stack_depth = subprog_depth; 5188 if (subprog_depth > MAX_BPF_STACK) { 5189 verbose(env, "stack size of subprog %d is %d. Too large\n", 5190 idx, subprog_depth); 5191 return -EACCES; 5192 } 5193 } else { 5194 depth += subprog_depth; 5195 if (depth > env->max_stack_depth) 5196 env->max_stack_depth = depth; 5197 if (depth > MAX_BPF_STACK) { 5198 total = 0; 5199 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) 5200 total++; 5201 5202 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5203 total, depth); 5204 return -EACCES; 5205 } 5206 } 5207 continue_func: 5208 subprog_end = subprog[idx + 1].start; 5209 for (; i < subprog_end; i++) { 5210 int next_insn, sidx; 5211 5212 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5213 bool err = false; 5214 5215 if (!bpf_is_throw_kfunc(insn + i)) 5216 continue; 5217 for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) { 5218 if (subprog[tmp].is_cb) { 5219 err = true; 5220 break; 5221 } 5222 } 5223 if (!err) 5224 continue; 5225 verbose(env, 5226 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5227 i, idx); 5228 return -EINVAL; 5229 } 5230 5231 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5232 continue; 5233 /* remember insn and function to return to */ 5234 5235 /* find the callee */ 5236 next_insn = i + insn[i].imm + 1; 5237 sidx = bpf_find_subprog(env, next_insn); 5238 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn)) 5239 return -EFAULT; 5240 if (subprog[sidx].is_async_cb) { 5241 /* async callbacks don't increase bpf prog stack size unless called directly */ 5242 if (!bpf_pseudo_call(insn + i)) 5243 continue; 5244 if (subprog[sidx].is_exception_cb) { 5245 verbose(env, "insn %d cannot call exception cb directly", i); 5246 return -EINVAL; 5247 } 5248 } 5249 5250 /* store caller info for after we return from callee */ 5251 dinfo[idx].frame = frame; 5252 dinfo[idx].ret_insn = i + 1; 5253 5254 /* push caller idx into callee's dinfo */ 5255 dinfo[sidx].caller = idx; 5256 5257 i = next_insn; 5258 5259 idx = sidx; 5260 if (!priv_stack_supported) 5261 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5262 5263 /* sync tail_call_reachable with callee state on entry */ 5264 tail_call_reachable = subprog[idx].has_tail_call; 5265 5266 frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1; 5267 if (frame >= MAX_CALL_FRAMES) { 5268 verbose(env, "the call stack of %d frames is too deep !\n", 5269 frame); 5270 return -E2BIG; 5271 } 5272 goto process_func; 5273 } 5274 /* if tail call got detected across bpf2bpf calls then mark each of the 5275 * currently present subprog frames as tail call reachable subprogs; 5276 * this info will be utilized by JIT so that we will be preserving the 5277 * tail call counter throughout bpf2bpf calls combined with tailcalls 5278 */ 5279 if (tail_call_reachable) { 5280 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) { 5281 if (subprog[tmp].is_cb) { 5282 verbose(env, "cannot tail call within callback\n"); 5283 return -EINVAL; 5284 } 5285 if (subprog[tmp].stack_arg_cnt) { 5286 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5287 return -EINVAL; 5288 } 5289 subprog[tmp].tail_call_reachable = true; 5290 } 5291 } else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) { 5292 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5293 return -EINVAL; 5294 } 5295 5296 if (subprog[0].tail_call_reachable) 5297 env->prog->aux->tail_call_reachable = true; 5298 5299 /* end of for() loop means the last insn of the 'subprog' 5300 * was reached. Doesn't matter whether it was JA or EXIT 5301 */ 5302 if (frame == 0 && dinfo[idx].caller < 0) 5303 return 0; 5304 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 5305 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 5306 5307 /* pop caller idx from callee */ 5308 idx = dinfo[idx].caller; 5309 5310 /* retrieve caller state from its frame */ 5311 frame = dinfo[idx].frame; 5312 i = dinfo[idx].ret_insn; 5313 5314 /* reset tail_call_reachable to the parent's actual state */ 5315 tail_call_reachable = subprog[idx].tail_call_reachable; 5316 5317 goto continue_func; 5318 } 5319 5320 static int check_max_stack_depth(struct bpf_verifier_env *env) 5321 { 5322 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 5323 struct bpf_subprog_call_depth_info *dinfo; 5324 struct bpf_subprog_info *si = env->subprog_info; 5325 bool priv_stack_supported; 5326 int ret; 5327 5328 dinfo = kvcalloc(env->subprog_cnt, sizeof(*dinfo), GFP_KERNEL_ACCOUNT); 5329 if (!dinfo) 5330 return -ENOMEM; 5331 5332 for (int i = 0; i < env->subprog_cnt; i++) { 5333 if (si[i].has_tail_call) { 5334 priv_stack_mode = NO_PRIV_STACK; 5335 break; 5336 } 5337 } 5338 5339 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 5340 priv_stack_mode = bpf_enable_priv_stack(env->prog); 5341 5342 /* All async_cb subprogs use normal kernel stack. If a particular 5343 * subprog appears in both main prog and async_cb subtree, that 5344 * subprog will use normal kernel stack to avoid potential nesting. 5345 * The reverse subprog traversal ensures when main prog subtree is 5346 * checked, the subprogs appearing in async_cb subtrees are already 5347 * marked as using normal kernel stack, so stack size checking can 5348 * be done properly. 5349 */ 5350 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 5351 if (!i || si[i].is_async_cb) { 5352 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 5353 ret = check_max_stack_depth_subprog(env, i, dinfo, 5354 priv_stack_supported); 5355 if (ret < 0) { 5356 kvfree(dinfo); 5357 return ret; 5358 } 5359 } 5360 } 5361 5362 for (int i = 0; i < env->subprog_cnt; i++) { 5363 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5364 env->prog->aux->jits_use_priv_stack = true; 5365 break; 5366 } 5367 } 5368 5369 kvfree(dinfo); 5370 5371 return 0; 5372 } 5373 5374 static int __check_buffer_access(struct bpf_verifier_env *env, 5375 const char *buf_info, 5376 const struct bpf_reg_state *reg, 5377 argno_t argno, int off, int size, 5378 u32 *access_end) 5379 { 5380 s64 start; 5381 5382 if (!tnum_is_const(reg->var_off)) { 5383 char tn_buf[48]; 5384 5385 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5386 verbose(env, 5387 "%s invalid variable buffer offset: off=%d, var_off=%s\n", 5388 reg_arg_name(env, argno), off, tn_buf); 5389 return -EACCES; 5390 } 5391 5392 start = (s64)reg->var_off.value + off; 5393 if (start < 0) { 5394 verbose(env, 5395 "%s invalid negative %s buffer offset: off=%d, var_off=%lld\n", 5396 reg_arg_name(env, argno), buf_info, off, (s64)reg->var_off.value); 5397 return -EACCES; 5398 } 5399 5400 *access_end = start + size; 5401 return 0; 5402 } 5403 5404 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5405 const struct bpf_reg_state *reg, 5406 argno_t argno, int off, int size) 5407 { 5408 u32 access_end; 5409 int err; 5410 5411 err = __check_buffer_access(env, "tracepoint", reg, argno, off, size, &access_end); 5412 if (err) 5413 return err; 5414 5415 env->prog->aux->max_tp_access = max(access_end, env->prog->aux->max_tp_access); 5416 5417 return 0; 5418 } 5419 5420 static int check_buffer_access(struct bpf_verifier_env *env, 5421 const struct bpf_reg_state *reg, 5422 argno_t argno, int off, int size, 5423 bool zero_size_allowed, 5424 u32 *max_access) 5425 { 5426 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5427 u32 access_end; 5428 int err; 5429 5430 err = __check_buffer_access(env, buf_info, reg, argno, off, size, &access_end); 5431 if (err) 5432 return err; 5433 5434 *max_access = max(access_end, *max_access); 5435 5436 return 0; 5437 } 5438 5439 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5440 static void zext_32_to_64(struct bpf_reg_state *reg) 5441 { 5442 reg->var_off = tnum_subreg(reg->var_off); 5443 reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg)); 5444 } 5445 5446 /* truncate register to smaller size (in bytes) 5447 * must be called with size < BPF_REG_SIZE 5448 */ 5449 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5450 { 5451 u64 mask; 5452 5453 /* clear high bits in bit representation */ 5454 reg->var_off = tnum_cast(reg->var_off, size); 5455 5456 /* fix arithmetic bounds */ 5457 mask = ((u64)1 << (size * 8)) - 1; 5458 if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask)) 5459 reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask); 5460 else 5461 reg_set_urange64(reg, 0, mask); 5462 5463 /* If size is smaller than 32bit register the 32bit register 5464 * values are also truncated so we push 64-bit bounds into 5465 * 32-bit bounds. Above were truncated < 32-bits already. 5466 */ 5467 if (size < 4) 5468 __mark_reg32_unbounded(reg); 5469 5470 reg_bounds_sync(reg); 5471 } 5472 5473 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 5474 { 5475 if (size == 1) { 5476 reg_set_srange64(reg, S8_MIN, S8_MAX); 5477 reg_set_srange32(reg, S8_MIN, S8_MAX); 5478 } else if (size == 2) { 5479 reg_set_srange64(reg, S16_MIN, S16_MAX); 5480 reg_set_srange32(reg, S16_MIN, S16_MAX); 5481 } else { 5482 /* size == 4 */ 5483 reg_set_srange64(reg, S32_MIN, S32_MAX); 5484 reg_set_srange32(reg, S32_MIN, S32_MAX); 5485 } 5486 reg->var_off = tnum_unknown; 5487 } 5488 5489 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 5490 { 5491 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 5492 u64 top_smax_value, top_smin_value; 5493 u64 num_bits = size * 8; 5494 5495 if (tnum_is_const(reg->var_off)) { 5496 u64_cval = reg->var_off.value; 5497 if (size == 1) 5498 reg->var_off = tnum_const((s8)u64_cval); 5499 else if (size == 2) 5500 reg->var_off = tnum_const((s16)u64_cval); 5501 else 5502 /* size == 4 */ 5503 reg->var_off = tnum_const((s32)u64_cval); 5504 5505 u64_cval = reg->var_off.value; 5506 reg->r64 = cnum64_from_urange(u64_cval, u64_cval); 5507 reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval); 5508 return; 5509 } 5510 5511 top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits; 5512 top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits; 5513 5514 if (top_smax_value != top_smin_value) 5515 goto out; 5516 5517 /* find the s64_min and s64_min after sign extension */ 5518 if (size == 1) { 5519 init_s64_max = (s8)reg_smax(reg); 5520 init_s64_min = (s8)reg_smin(reg); 5521 } else if (size == 2) { 5522 init_s64_max = (s16)reg_smax(reg); 5523 init_s64_min = (s16)reg_smin(reg); 5524 } else { 5525 init_s64_max = (s32)reg_smax(reg); 5526 init_s64_min = (s32)reg_smin(reg); 5527 } 5528 5529 s64_max = max(init_s64_max, init_s64_min); 5530 s64_min = min(init_s64_max, init_s64_min); 5531 5532 /* both of s64_max/s64_min positive or negative */ 5533 if ((s64_max >= 0) == (s64_min >= 0)) { 5534 reg_set_srange64(reg, s64_min, s64_max); 5535 reg_set_srange32(reg, s64_min, s64_max); 5536 reg->var_off = tnum_range(s64_min, s64_max); 5537 return; 5538 } 5539 5540 out: 5541 set_sext64_default_val(reg, size); 5542 } 5543 5544 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 5545 { 5546 if (size == 1) 5547 reg_set_srange32(reg, S8_MIN, S8_MAX); 5548 else 5549 /* size == 2 */ 5550 reg_set_srange32(reg, S16_MIN, S16_MAX); 5551 reg->var_off = tnum_subreg(tnum_unknown); 5552 } 5553 5554 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 5555 { 5556 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 5557 u32 top_smax_value, top_smin_value; 5558 u32 num_bits = size * 8; 5559 5560 if (tnum_is_const(reg->var_off)) { 5561 u32_val = reg->var_off.value; 5562 if (size == 1) 5563 reg->var_off = tnum_const((s8)u32_val); 5564 else 5565 reg->var_off = tnum_const((s16)u32_val); 5566 5567 u32_val = reg->var_off.value; 5568 reg_set_srange32(reg, u32_val, u32_val); 5569 return; 5570 } 5571 5572 top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits; 5573 top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits; 5574 5575 if (top_smax_value != top_smin_value) 5576 goto out; 5577 5578 /* find the s32_min and s32_min after sign extension */ 5579 if (size == 1) { 5580 init_s32_max = (s8)reg_s32_max(reg); 5581 init_s32_min = (s8)reg_s32_min(reg); 5582 } else { 5583 /* size == 2 */ 5584 init_s32_max = (s16)reg_s32_max(reg); 5585 init_s32_min = (s16)reg_s32_min(reg); 5586 } 5587 s32_max = max(init_s32_max, init_s32_min); 5588 s32_min = min(init_s32_max, init_s32_min); 5589 5590 if ((s32_min >= 0) == (s32_max >= 0)) { 5591 reg_set_srange32(reg, s32_min, s32_max); 5592 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 5593 return; 5594 } 5595 5596 out: 5597 set_sext32_default_val(reg, size); 5598 } 5599 5600 bool bpf_map_is_rdonly(const struct bpf_map *map) 5601 { 5602 /* A map is considered read-only if the following condition are true: 5603 * 5604 * 1) BPF program side cannot change any of the map content. The 5605 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 5606 * and was set at map creation time. 5607 * 2) The map value(s) have been initialized from user space by a 5608 * loader and then "frozen", such that no new map update/delete 5609 * operations from syscall side are possible for the rest of 5610 * the map's lifetime from that point onwards. 5611 * 3) Any parallel/pending map update/delete operations from syscall 5612 * side have been completed. Only after that point, it's safe to 5613 * assume that map value(s) are immutable. 5614 */ 5615 return (map->map_flags & BPF_F_RDONLY_PROG) && 5616 READ_ONCE(map->frozen) && 5617 !bpf_map_write_active(map); 5618 } 5619 5620 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 5621 bool is_ldsx) 5622 { 5623 void *ptr; 5624 u64 addr; 5625 int err; 5626 5627 err = map->ops->map_direct_value_addr(map, &addr, off); 5628 if (err) 5629 return err; 5630 ptr = (void *)(long)addr + off; 5631 5632 switch (size) { 5633 case sizeof(u8): 5634 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 5635 break; 5636 case sizeof(u16): 5637 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 5638 break; 5639 case sizeof(u32): 5640 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 5641 break; 5642 case sizeof(u64): 5643 *val = *(u64 *)ptr; 5644 break; 5645 default: 5646 return -EINVAL; 5647 } 5648 return 0; 5649 } 5650 5651 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 5652 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 5653 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 5654 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 5655 5656 /* 5657 * Allow list few fields as RCU trusted or full trusted. 5658 * This logic doesn't allow mix tagging and will be removed once GCC supports 5659 * btf_type_tag. 5660 */ 5661 5662 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 5663 BTF_TYPE_SAFE_RCU(struct task_struct) { 5664 const cpumask_t *cpus_ptr; 5665 struct css_set __rcu *cgroups; 5666 struct task_struct __rcu *real_parent; 5667 struct task_struct *group_leader; 5668 }; 5669 5670 BTF_TYPE_SAFE_RCU(struct cgroup) { 5671 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 5672 struct kernfs_node *kn; 5673 }; 5674 5675 BTF_TYPE_SAFE_RCU(struct css_set) { 5676 struct cgroup *dfl_cgrp; 5677 }; 5678 5679 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) { 5680 struct cgroup *cgroup; 5681 }; 5682 5683 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 5684 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 5685 struct file __rcu *exe_file; 5686 #ifdef CONFIG_MEMCG 5687 struct task_struct __rcu *owner; 5688 #endif 5689 }; 5690 5691 /* skb->sk, req->sk are not RCU protected, but we mark them as such 5692 * because bpf prog accessible sockets are SOCK_RCU_FREE. 5693 */ 5694 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 5695 struct sock *sk; 5696 }; 5697 5698 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 5699 struct sock *sk; 5700 }; 5701 5702 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 5703 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 5704 struct seq_file *seq; 5705 }; 5706 5707 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 5708 struct bpf_iter_meta *meta; 5709 struct task_struct *task; 5710 }; 5711 5712 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 5713 struct file *file; 5714 }; 5715 5716 BTF_TYPE_SAFE_TRUSTED(struct file) { 5717 struct inode *f_inode; 5718 }; 5719 5720 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) { 5721 struct inode *d_inode; 5722 }; 5723 5724 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 5725 struct sock *sk; 5726 }; 5727 5728 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) { 5729 struct mm_struct *vm_mm; 5730 struct file *vm_file; 5731 }; 5732 5733 static bool type_is_rcu(struct bpf_verifier_env *env, 5734 struct bpf_reg_state *reg, 5735 const char *field_name, u32 btf_id) 5736 { 5737 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 5738 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 5739 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 5740 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)); 5741 5742 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 5743 } 5744 5745 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 5746 struct bpf_reg_state *reg, 5747 const char *field_name, u32 btf_id) 5748 { 5749 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 5750 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 5751 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 5752 5753 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 5754 } 5755 5756 static bool type_is_trusted(struct bpf_verifier_env *env, 5757 struct bpf_reg_state *reg, 5758 const char *field_name, u32 btf_id) 5759 { 5760 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 5761 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 5762 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 5763 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 5764 5765 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 5766 } 5767 5768 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 5769 struct bpf_reg_state *reg, 5770 const char *field_name, u32 btf_id) 5771 { 5772 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 5773 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)); 5774 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct)); 5775 5776 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 5777 "__safe_trusted_or_null"); 5778 } 5779 5780 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 5781 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5782 argno_t argno, int off, int size, 5783 enum bpf_access_type atype, 5784 int value_regno) 5785 { 5786 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 5787 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 5788 const char *field_name = NULL; 5789 enum bpf_type_flag flag = 0; 5790 u32 btf_id = 0; 5791 int ret; 5792 5793 if (!env->allow_ptr_leaks) { 5794 verbose(env, 5795 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5796 tname); 5797 return -EPERM; 5798 } 5799 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 5800 verbose(env, 5801 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 5802 tname); 5803 return -EINVAL; 5804 } 5805 5806 if (!tnum_is_const(reg->var_off)) { 5807 char tn_buf[48]; 5808 5809 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5810 verbose(env, 5811 "%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 5812 reg_arg_name(env, argno), tname, off, tn_buf); 5813 return -EACCES; 5814 } 5815 5816 off += reg->var_off.value; 5817 5818 if (off < 0) { 5819 verbose(env, 5820 "%s is ptr_%s invalid negative access: off=%d\n", 5821 reg_arg_name(env, argno), tname, off); 5822 return -EACCES; 5823 } 5824 5825 if (reg->type & MEM_USER) { 5826 verbose(env, 5827 "%s is ptr_%s access user memory: off=%d\n", 5828 reg_arg_name(env, argno), tname, off); 5829 return -EACCES; 5830 } 5831 5832 if (reg->type & MEM_PERCPU) { 5833 verbose(env, 5834 "%s is ptr_%s access percpu memory: off=%d\n", 5835 reg_arg_name(env, argno), tname, off); 5836 return -EACCES; 5837 } 5838 5839 if (atype != BPF_READ && (type_flag(reg->type) & PTR_UNTRUSTED)) { 5840 verbose(env, "only read is supported\n"); 5841 return -EACCES; 5842 } 5843 5844 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 5845 if (!btf_is_kernel(reg->btf)) { 5846 verifier_bug(env, "reg->btf must be kernel btf"); 5847 return -EFAULT; 5848 } 5849 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 5850 if (ret < 0) 5851 verbose(env, 5852 "%s cannot write into ptr_%s at off=%d size=%d\n", 5853 reg_arg_name(env, argno), tname, off, size); 5854 } else { 5855 /* Writes are permitted with default btf_struct_access for 5856 * program allocated objects (which always have id > 0). 5857 */ 5858 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 5859 verbose(env, "only read is supported\n"); 5860 return -EACCES; 5861 } 5862 5863 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 5864 !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) { 5865 verifier_bug(env, "allocated object must have a referenced id"); 5866 return -EFAULT; 5867 } 5868 5869 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 5870 } 5871 5872 if (ret < 0) 5873 return ret; 5874 5875 if (ret != PTR_TO_BTF_ID) { 5876 /* just mark; */ 5877 5878 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 5879 /* If this is an untrusted pointer, all pointers formed by walking it 5880 * also inherit the untrusted flag. 5881 */ 5882 flag = PTR_UNTRUSTED; 5883 5884 } else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) { 5885 /* By default any pointer obtained from walking a trusted pointer is no 5886 * longer trusted, unless the field being accessed has explicitly been 5887 * marked as inheriting its parent's state of trust (either full or RCU). 5888 * For example: 5889 * 'cgroups' pointer is untrusted if task->cgroups dereference 5890 * happened in a sleepable program outside of bpf_rcu_read_lock() 5891 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 5892 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 5893 * 5894 * A regular RCU-protected pointer with __rcu tag can also be deemed 5895 * trusted if we are in an RCU CS. Such pointer can be NULL. 5896 */ 5897 if (type_is_trusted(env, reg, field_name, btf_id)) { 5898 flag |= PTR_TRUSTED; 5899 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 5900 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 5901 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 5902 if (type_is_rcu(env, reg, field_name, btf_id)) { 5903 /* ignore __rcu tag and mark it MEM_RCU */ 5904 flag |= MEM_RCU; 5905 } else if (flag & MEM_RCU || 5906 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 5907 /* __rcu tagged pointers can be NULL */ 5908 flag |= MEM_RCU | PTR_MAYBE_NULL; 5909 5910 /* We always trust them */ 5911 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 5912 flag & PTR_UNTRUSTED) 5913 flag &= ~PTR_UNTRUSTED; 5914 } else if (flag & (MEM_PERCPU | MEM_USER)) { 5915 /* keep as-is */ 5916 } else { 5917 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 5918 clear_trusted_flags(&flag); 5919 } 5920 } else { 5921 /* 5922 * If not in RCU CS or MEM_RCU pointer can be NULL then 5923 * aggressively mark as untrusted otherwise such 5924 * pointers will be plain PTR_TO_BTF_ID without flags 5925 * and will be allowed to be passed into helpers for 5926 * compat reasons. 5927 */ 5928 flag = PTR_UNTRUSTED; 5929 } 5930 } else { 5931 /* Old compat. Deprecated */ 5932 clear_trusted_flags(&flag); 5933 } 5934 5935 if (atype == BPF_READ && value_regno >= 0) { 5936 ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5937 if (ret < 0) 5938 return ret; 5939 } 5940 5941 return 0; 5942 } 5943 5944 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5945 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5946 argno_t argno, int off, int size, 5947 enum bpf_access_type atype, 5948 int value_regno) 5949 { 5950 struct bpf_map *map = reg->map_ptr; 5951 struct bpf_reg_state map_reg; 5952 enum bpf_type_flag flag = 0; 5953 const struct btf_type *t; 5954 const char *tname; 5955 u32 btf_id; 5956 int ret; 5957 5958 if (!btf_vmlinux) { 5959 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5960 return -ENOTSUPP; 5961 } 5962 5963 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5964 verbose(env, "map_ptr access not supported for map type %d\n", 5965 map->map_type); 5966 return -ENOTSUPP; 5967 } 5968 5969 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5970 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5971 5972 if (!env->allow_ptr_leaks) { 5973 verbose(env, 5974 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5975 tname); 5976 return -EPERM; 5977 } 5978 5979 if (off < 0) { 5980 verbose(env, "%s is %s invalid negative access: off=%d\n", 5981 reg_arg_name(env, argno), tname, off); 5982 return -EACCES; 5983 } 5984 5985 if (atype != BPF_READ) { 5986 verbose(env, "only read from %s is supported\n", tname); 5987 return -EACCES; 5988 } 5989 5990 /* Simulate access to a PTR_TO_BTF_ID */ 5991 memset(&map_reg, 0, sizeof(map_reg)); 5992 ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, 5993 btf_vmlinux, *map->ops->map_btf_id, 0); 5994 if (ret < 0) 5995 return ret; 5996 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 5997 if (ret < 0) 5998 return ret; 5999 6000 if (value_regno >= 0) { 6001 ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6002 if (ret < 0) 6003 return ret; 6004 } 6005 6006 return 0; 6007 } 6008 6009 /* Check that the stack access at the given offset is within bounds. The 6010 * maximum valid offset is -1. 6011 * 6012 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6013 * -state->allocated_stack for reads. 6014 */ 6015 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6016 s64 off, 6017 struct bpf_func_state *state, 6018 enum bpf_access_type t) 6019 { 6020 int min_valid_off; 6021 6022 if (t == BPF_WRITE || env->allow_uninit_stack) 6023 min_valid_off = -MAX_BPF_STACK; 6024 else 6025 min_valid_off = -state->allocated_stack; 6026 6027 if (off < min_valid_off || off > -1) 6028 return -EACCES; 6029 return 0; 6030 } 6031 6032 /* Check that the stack access at 'regno + off' falls within the maximum stack 6033 * bounds. 6034 * 6035 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6036 */ 6037 static int check_stack_access_within_bounds( 6038 struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6039 argno_t argno, int off, int access_size, 6040 enum bpf_access_type type) 6041 { 6042 struct bpf_func_state *state = bpf_func(env, reg); 6043 s64 min_off, max_off; 6044 int err; 6045 char *err_extra; 6046 6047 if (type == BPF_READ) 6048 err_extra = " read from"; 6049 else 6050 err_extra = " write to"; 6051 6052 if (tnum_is_const(reg->var_off)) { 6053 min_off = (s64)reg->var_off.value + off; 6054 max_off = min_off + access_size; 6055 } else { 6056 if (reg_smax(reg) >= BPF_MAX_VAR_OFF || 6057 reg_smin(reg) <= -BPF_MAX_VAR_OFF) { 6058 verbose(env, "invalid unbounded variable-offset%s stack %s\n", 6059 err_extra, reg_arg_name(env, argno)); 6060 return -EACCES; 6061 } 6062 min_off = reg_smin(reg) + off; 6063 max_off = reg_smax(reg) + off + access_size; 6064 } 6065 6066 err = check_stack_slot_within_bounds(env, min_off, state, type); 6067 if (!err && max_off > 0) 6068 err = -EINVAL; /* out of stack access into non-negative offsets */ 6069 if (!err && access_size < 0) 6070 /* access_size should not be negative (or overflow an int); others checks 6071 * along the way should have prevented such an access. 6072 */ 6073 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6074 6075 if (err) { 6076 if (tnum_is_const(reg->var_off)) { 6077 verbose(env, "invalid%s stack %s off=%lld size=%d\n", 6078 err_extra, reg_arg_name(env, argno), min_off, access_size); 6079 } else { 6080 char tn_buf[48]; 6081 6082 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6083 verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n", 6084 err_extra, reg_arg_name(env, argno), tn_buf, off, access_size); 6085 } 6086 return err; 6087 } 6088 6089 /* Note that there is no stack access with offset zero, so the needed stack 6090 * size is -min_off, not -min_off+1. 6091 */ 6092 return grow_stack_state(env, state, -min_off /* size */); 6093 } 6094 6095 static bool get_func_retval_range(struct bpf_prog *prog, 6096 struct bpf_retval_range *range) 6097 { 6098 if (prog->type == BPF_PROG_TYPE_LSM && 6099 prog->expected_attach_type == BPF_LSM_MAC && 6100 !bpf_lsm_get_retval_range(prog, range)) { 6101 return true; 6102 } 6103 return false; 6104 } 6105 6106 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val) 6107 { 6108 struct bpf_reg_state fake_reg; 6109 6110 if (!val) 6111 return; 6112 6113 fake_reg.type = SCALAR_VALUE; 6114 __mark_reg_known(&fake_reg, val); 6115 6116 scalar32_min_max_add(dst_reg, &fake_reg); 6117 scalar_min_max_add(dst_reg, &fake_reg); 6118 dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off); 6119 6120 reg_bounds_sync(dst_reg); 6121 } 6122 6123 /* check whether memory at (regno + off) is accessible for t = (read | write) 6124 * if t==write, value_regno is a register which value is stored into memory 6125 * if t==read, value_regno is a register which will receive the value from memory 6126 * if t==write && value_regno==-1, some unknown value is stored into memory 6127 * if t==read && value_regno==-1, don't care what we read from memory 6128 */ 6129 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 6130 int off, int bpf_size, enum bpf_access_type t, 6131 int value_regno, bool strict_alignment_once, bool is_ldsx) 6132 { 6133 struct bpf_reg_state *regs = cur_regs(env); 6134 int size, err = 0; 6135 6136 size = bpf_size_to_bytes(bpf_size); 6137 if (size < 0) 6138 return size; 6139 6140 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6141 if (err) 6142 return err; 6143 6144 if (reg->type == PTR_TO_MAP_KEY) { 6145 if (t == BPF_WRITE) { 6146 verbose(env, "write to change key %s not allowed\n", 6147 reg_arg_name(env, argno)); 6148 return -EACCES; 6149 } 6150 6151 err = check_mem_region_access(env, reg, argno, off, size, 6152 reg->map_ptr->key_size, false); 6153 if (err) 6154 return err; 6155 if (value_regno >= 0) 6156 mark_reg_unknown(env, regs, value_regno); 6157 } else if (reg->type == PTR_TO_MAP_VALUE) { 6158 struct btf_field *kptr_field = NULL; 6159 6160 if (t == BPF_WRITE && value_regno >= 0 && 6161 is_pointer_value(env, value_regno)) { 6162 verbose(env, "R%d leaks addr into map\n", value_regno); 6163 return -EACCES; 6164 } 6165 err = check_map_access_type(env, reg, off, size, t); 6166 if (err) 6167 return err; 6168 err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT); 6169 if (err) 6170 return err; 6171 if (tnum_is_const(reg->var_off)) 6172 kptr_field = btf_record_find(reg->map_ptr->record, 6173 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 6174 if (kptr_field) { 6175 err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field); 6176 } else if (t == BPF_READ && value_regno >= 0) { 6177 struct bpf_map *map = reg->map_ptr; 6178 6179 /* 6180 * If map is read-only, track its contents as scalars, 6181 * unless it is an insn array (see the special case below) 6182 */ 6183 if (tnum_is_const(reg->var_off) && 6184 bpf_map_is_rdonly(map) && 6185 map->ops->map_direct_value_addr && 6186 map->map_type != BPF_MAP_TYPE_INSN_ARRAY) { 6187 int map_off = off + reg->var_off.value; 6188 u64 val = 0; 6189 6190 err = bpf_map_direct_read(map, map_off, size, 6191 &val, is_ldsx); 6192 if (err) 6193 return err; 6194 6195 regs[value_regno].type = SCALAR_VALUE; 6196 __mark_reg_known(®s[value_regno], val); 6197 } else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 6198 if (bpf_size != BPF_DW) { 6199 verbose(env, "Invalid read of %d bytes from insn_array\n", 6200 size); 6201 return -EACCES; 6202 } 6203 regs[value_regno] = *reg; 6204 add_scalar_to_reg(®s[value_regno], off); 6205 regs[value_regno].type = PTR_TO_INSN; 6206 } else { 6207 mark_reg_unknown(env, regs, value_regno); 6208 } 6209 } 6210 } else if (base_type(reg->type) == PTR_TO_MEM) { 6211 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6212 bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED); 6213 6214 if (type_may_be_null(reg->type)) { 6215 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6216 reg_type_str(env, reg->type)); 6217 return -EACCES; 6218 } 6219 6220 if (t == BPF_WRITE && rdonly_mem) { 6221 verbose(env, "%s cannot write into %s\n", 6222 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6223 return -EACCES; 6224 } 6225 6226 if (t == BPF_WRITE && value_regno >= 0 && 6227 is_pointer_value(env, value_regno)) { 6228 verbose(env, "R%d leaks addr into mem\n", value_regno); 6229 return -EACCES; 6230 } 6231 6232 /* 6233 * Accesses to untrusted PTR_TO_MEM are done through probe 6234 * instructions, hence no need to check bounds in that case. 6235 */ 6236 if (!rdonly_untrusted) 6237 err = check_mem_region_access(env, reg, argno, off, size, 6238 reg->mem_size, false); 6239 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6240 mark_reg_unknown(env, regs, value_regno); 6241 } else if (reg->type == PTR_TO_CTX) { 6242 struct bpf_insn_access_aux info = { 6243 .reg_type = SCALAR_VALUE, 6244 .is_ldsx = is_ldsx, 6245 .log = &env->log, 6246 }; 6247 struct bpf_retval_range range; 6248 6249 if (t == BPF_WRITE && value_regno >= 0 && 6250 is_pointer_value(env, value_regno)) { 6251 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6252 return -EACCES; 6253 } 6254 6255 err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info); 6256 if (!err && t == BPF_READ && value_regno >= 0) { 6257 /* ctx access returns either a scalar, or a 6258 * PTR_TO_PACKET[_META,_END]. In the latter 6259 * case, we know the offset is zero. 6260 */ 6261 if (info.reg_type == SCALAR_VALUE) { 6262 if (info.is_retval && get_func_retval_range(env->prog, &range)) { 6263 mark_reg_unknown(env, regs, value_regno); 6264 err = __mark_reg_s32_range(env, regs, value_regno, 6265 range.minval, range.maxval); 6266 if (err) 6267 return err; 6268 } else { 6269 mark_reg_unknown(env, regs, value_regno); 6270 } 6271 } else { 6272 mark_reg_known_zero(env, regs, 6273 value_regno); 6274 /* A load of ctx field could have different 6275 * actual load size with the one encoded in the 6276 * insn. When the dst is PTR, it is for sure not 6277 * a sub-register. 6278 */ 6279 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6280 if (base_type(info.reg_type) == PTR_TO_BTF_ID) { 6281 regs[value_regno].btf = info.btf; 6282 regs[value_regno].btf_id = info.btf_id; 6283 regs[value_regno].id = info.ref_id; 6284 } 6285 if (type_may_be_null(info.reg_type) && !regs[value_regno].id) 6286 regs[value_regno].id = ++env->id_gen; 6287 } 6288 regs[value_regno].type = info.reg_type; 6289 } 6290 6291 } else if (reg->type == PTR_TO_STACK) { 6292 /* Basic bounds checks. */ 6293 err = check_stack_access_within_bounds(env, reg, argno, off, size, t); 6294 if (err) 6295 return err; 6296 6297 if (t == BPF_READ) 6298 err = check_stack_read(env, reg, argno, off, size, 6299 value_regno); 6300 else 6301 err = check_stack_write(env, reg, off, size, 6302 value_regno, insn_idx); 6303 } else if (reg_is_pkt_pointer(reg)) { 6304 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6305 verbose(env, "cannot write into packet\n"); 6306 return -EACCES; 6307 } 6308 if (t == BPF_WRITE && value_regno >= 0 && 6309 is_pointer_value(env, value_regno)) { 6310 verbose(env, "R%d leaks addr into packet\n", 6311 value_regno); 6312 return -EACCES; 6313 } 6314 err = check_packet_access(env, reg, argno, off, size, false); 6315 if (!err && t == BPF_READ && value_regno >= 0) 6316 mark_reg_unknown(env, regs, value_regno); 6317 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6318 if (t == BPF_WRITE && value_regno >= 0 && 6319 is_pointer_value(env, value_regno)) { 6320 verbose(env, "R%d leaks addr into flow keys\n", 6321 value_regno); 6322 return -EACCES; 6323 } 6324 6325 err = check_flow_keys_access(env, reg, argno, off, size); 6326 if (!err && t == BPF_READ && value_regno >= 0) 6327 mark_reg_unknown(env, regs, value_regno); 6328 } else if (type_is_sk_pointer(reg->type)) { 6329 if (t == BPF_WRITE) { 6330 verbose(env, "%s cannot write into %s\n", 6331 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6332 return -EACCES; 6333 } 6334 err = check_sock_access(env, insn_idx, reg, argno, off, size, t); 6335 if (!err && value_regno >= 0) 6336 mark_reg_unknown(env, regs, value_regno); 6337 } else if (reg->type == PTR_TO_TP_BUFFER) { 6338 err = check_tp_buffer_access(env, reg, argno, off, size); 6339 if (!err && t == BPF_READ && value_regno >= 0) 6340 mark_reg_unknown(env, regs, value_regno); 6341 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6342 !type_may_be_null(reg->type)) { 6343 err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t, 6344 value_regno); 6345 } else if (reg->type == CONST_PTR_TO_MAP) { 6346 err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t, 6347 value_regno); 6348 } else if (base_type(reg->type) == PTR_TO_BUF && 6349 !type_may_be_null(reg->type)) { 6350 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6351 u32 *max_access; 6352 6353 if (rdonly_mem) { 6354 if (t == BPF_WRITE) { 6355 verbose(env, "%s cannot write into %s\n", 6356 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6357 return -EACCES; 6358 } 6359 max_access = &env->prog->aux->max_rdonly_access; 6360 } else { 6361 max_access = &env->prog->aux->max_rdwr_access; 6362 } 6363 6364 err = check_buffer_access(env, reg, argno, off, size, false, 6365 max_access); 6366 6367 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6368 mark_reg_unknown(env, regs, value_regno); 6369 } else if (reg->type == PTR_TO_ARENA) { 6370 if (t == BPF_READ && value_regno >= 0) 6371 mark_reg_unknown(env, regs, value_regno); 6372 } else { 6373 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6374 reg_type_str(env, reg->type)); 6375 return -EACCES; 6376 } 6377 6378 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6379 regs[value_regno].type == SCALAR_VALUE) { 6380 if (!is_ldsx) { 6381 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6382 coerce_reg_to_size(®s[value_regno], size); 6383 } else { 6384 /* 6385 * Sign-extension can change the register value relative 6386 * to a scalar it is linked with by id (e.g. a zero- 6387 * extending fill of the same spilled stack slot), thus 6388 * drop the shared id in that case. 6389 */ 6390 bool no_sext = reg_umax(®s[value_regno]) < 6391 (1ULL << (size * BITS_PER_BYTE - 1)); 6392 6393 coerce_reg_to_size_sx(®s[value_regno], size); 6394 if (!no_sext) 6395 clear_scalar_id(®s[value_regno]); 6396 } 6397 } 6398 return err; 6399 } 6400 6401 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 6402 bool allow_trust_mismatch); 6403 6404 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn, 6405 bool strict_alignment_once, bool is_ldsx, 6406 bool allow_trust_mismatch, const char *ctx) 6407 { 6408 struct bpf_verifier_state *vstate = env->cur_state; 6409 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6410 struct bpf_reg_state *regs = cur_regs(env); 6411 enum bpf_reg_type src_reg_type; 6412 int err; 6413 6414 /* Handle stack arg read */ 6415 if (is_stack_arg_ldx(insn)) { 6416 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6417 if (err) 6418 return err; 6419 return check_stack_arg_read(env, state, insn->off, insn->dst_reg); 6420 } 6421 6422 /* check src operand */ 6423 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6424 if (err) 6425 return err; 6426 6427 /* check dst operand */ 6428 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6429 if (err) 6430 return err; 6431 6432 src_reg_type = regs[insn->src_reg].type; 6433 6434 /* Check if (src_reg + off) is readable. The state of dst_reg will be 6435 * updated by this call. 6436 */ 6437 err = check_mem_access(env, env->insn_idx, regs + insn->src_reg, argno_from_reg(insn->src_reg), insn->off, 6438 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg, 6439 strict_alignment_once, is_ldsx); 6440 err = err ?: save_aux_ptr_type(env, src_reg_type, 6441 allow_trust_mismatch); 6442 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx); 6443 6444 return err; 6445 } 6446 6447 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn, 6448 bool strict_alignment_once) 6449 { 6450 struct bpf_verifier_state *vstate = env->cur_state; 6451 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6452 struct bpf_reg_state *regs = cur_regs(env); 6453 enum bpf_reg_type dst_reg_type; 6454 int err; 6455 6456 /* Handle stack arg write */ 6457 if (is_stack_arg_stx(insn)) { 6458 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6459 if (err) 6460 return err; 6461 return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg); 6462 } 6463 6464 /* check src1 operand */ 6465 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6466 if (err) 6467 return err; 6468 6469 /* check src2 operand */ 6470 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6471 if (err) 6472 return err; 6473 6474 dst_reg_type = regs[insn->dst_reg].type; 6475 6476 /* Check if (dst_reg + off) is writeable. */ 6477 err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6478 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg, 6479 strict_alignment_once, false); 6480 err = err ?: save_aux_ptr_type(env, dst_reg_type, false); 6481 6482 return err; 6483 } 6484 6485 static int check_atomic_rmw(struct bpf_verifier_env *env, 6486 struct bpf_insn *insn) 6487 { 6488 struct bpf_reg_state *dst_reg; 6489 int load_reg; 6490 int err; 6491 6492 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6493 verbose(env, "invalid atomic operand size\n"); 6494 return -EINVAL; 6495 } 6496 6497 /* check src1 operand */ 6498 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6499 if (err) 6500 return err; 6501 6502 /* check src2 operand */ 6503 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6504 if (err) 6505 return err; 6506 6507 if (insn->imm == BPF_CMPXCHG) { 6508 /* Check comparison of R0 with memory location */ 6509 const u32 aux_reg = BPF_REG_0; 6510 6511 err = check_reg_arg(env, aux_reg, SRC_OP); 6512 if (err) 6513 return err; 6514 6515 if (is_pointer_value(env, aux_reg)) { 6516 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6517 return -EACCES; 6518 } 6519 } 6520 6521 if (is_pointer_value(env, insn->src_reg)) { 6522 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6523 return -EACCES; 6524 } 6525 6526 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6527 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6528 insn->dst_reg, 6529 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6530 return -EACCES; 6531 } 6532 6533 if (insn->imm & BPF_FETCH) { 6534 if (insn->imm == BPF_CMPXCHG) 6535 load_reg = BPF_REG_0; 6536 else 6537 load_reg = insn->src_reg; 6538 6539 /* check and record load of old value */ 6540 err = check_reg_arg(env, load_reg, DST_OP); 6541 if (err) 6542 return err; 6543 } else { 6544 /* This instruction accesses a memory location but doesn't 6545 * actually load it into a register. 6546 */ 6547 load_reg = -1; 6548 } 6549 6550 dst_reg = cur_regs(env) + insn->dst_reg; 6551 6552 /* Check whether we can read the memory, with second call for fetch 6553 * case to simulate the register fill. 6554 */ 6555 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6556 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6557 if (!err && load_reg >= 0) 6558 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), 6559 insn->off, BPF_SIZE(insn->code), 6560 BPF_READ, load_reg, true, false); 6561 if (err) 6562 return err; 6563 6564 if (is_arena_reg(env, insn->dst_reg)) { 6565 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 6566 if (err) 6567 return err; 6568 } 6569 /* Check whether we can write into the same memory. */ 6570 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6571 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6572 if (err) 6573 return err; 6574 return 0; 6575 } 6576 6577 static int check_atomic_load(struct bpf_verifier_env *env, 6578 struct bpf_insn *insn) 6579 { 6580 int err; 6581 6582 err = check_load_mem(env, insn, true, false, false, "atomic_load"); 6583 if (err) 6584 return err; 6585 6586 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) { 6587 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n", 6588 insn->src_reg, 6589 reg_type_str(env, reg_state(env, insn->src_reg)->type)); 6590 return -EACCES; 6591 } 6592 6593 return 0; 6594 } 6595 6596 static int check_atomic_store(struct bpf_verifier_env *env, 6597 struct bpf_insn *insn) 6598 { 6599 int err; 6600 6601 err = check_store_reg(env, insn, true); 6602 if (err) 6603 return err; 6604 6605 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6606 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6607 insn->dst_reg, 6608 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6609 return -EACCES; 6610 } 6611 6612 return 0; 6613 } 6614 6615 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn) 6616 { 6617 switch (insn->imm) { 6618 case BPF_ADD: 6619 case BPF_ADD | BPF_FETCH: 6620 case BPF_AND: 6621 case BPF_AND | BPF_FETCH: 6622 case BPF_OR: 6623 case BPF_OR | BPF_FETCH: 6624 case BPF_XOR: 6625 case BPF_XOR | BPF_FETCH: 6626 case BPF_XCHG: 6627 case BPF_CMPXCHG: 6628 return check_atomic_rmw(env, insn); 6629 case BPF_LOAD_ACQ: 6630 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6631 verbose(env, 6632 "64-bit load-acquires are only supported on 64-bit arches\n"); 6633 return -EOPNOTSUPP; 6634 } 6635 return check_atomic_load(env, insn); 6636 case BPF_STORE_REL: 6637 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6638 verbose(env, 6639 "64-bit store-releases are only supported on 64-bit arches\n"); 6640 return -EOPNOTSUPP; 6641 } 6642 return check_atomic_store(env, insn); 6643 default: 6644 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", 6645 insn->imm); 6646 return -EINVAL; 6647 } 6648 } 6649 6650 /* When register 'regno' is used to read the stack (either directly or through 6651 * a helper function) make sure that it's within stack boundary and, depending 6652 * on the access type and privileges, that all elements of the stack are 6653 * initialized. 6654 * 6655 * All registers that have been spilled on the stack in the slots within the 6656 * read offsets are marked as read. 6657 */ 6658 static int check_stack_range_initialized( 6659 struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 6660 int access_size, bool zero_size_allowed, 6661 enum bpf_access_type type, struct bpf_call_arg_meta *meta) 6662 { 6663 struct bpf_func_state *state = bpf_func(env, reg); 6664 int err, min_off, max_off, i, j, slot, spi; 6665 /* Some accesses can write anything into the stack, others are 6666 * read-only. 6667 */ 6668 bool clobber = type == BPF_WRITE; 6669 /* 6670 * Negative access_size signals global subprog/kfunc arg check where 6671 * STACK_POISON slots are acceptable. static stack liveness 6672 * might have determined that subprog doesn't read them, 6673 * but BTF based global subprog validation isn't accurate enough. 6674 */ 6675 bool allow_poison = access_size < 0 || clobber; 6676 /* The call will initialize the memory; uninitialized stack allowed */ 6677 bool raw_mode = meta && meta->arg_raw_mem.regno == reg_from_argno(argno); 6678 6679 access_size = abs(access_size); 6680 6681 if (access_size == 0 && !zero_size_allowed) { 6682 verbose(env, "invalid zero-sized read\n"); 6683 return -EACCES; 6684 } 6685 6686 err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type); 6687 if (err) 6688 return err; 6689 6690 6691 if (tnum_is_const(reg->var_off)) { 6692 min_off = max_off = reg->var_off.value + off; 6693 } else { 6694 /* Variable offset is prohibited for unprivileged mode for 6695 * simplicity since it requires corresponding support in 6696 * Spectre masking for stack ALU. 6697 * See also retrieve_ptr_limit(). 6698 */ 6699 if (!env->bypass_spec_v1) { 6700 char tn_buf[48]; 6701 6702 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6703 verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n", 6704 reg_arg_name(env, argno), tn_buf); 6705 return -EACCES; 6706 } 6707 /* Only initialized buffer on stack is allowed to be accessed 6708 * with variable offset. With uninitialized buffer it's hard to 6709 * guarantee that whole memory is marked as initialized on 6710 * helper return since specific bounds are unknown what may 6711 * cause uninitialized stack leaking. 6712 */ 6713 raw_mode = false; 6714 6715 min_off = reg_smin(reg) + off; 6716 max_off = reg_smax(reg) + off; 6717 } 6718 6719 if (raw_mode) { 6720 meta->arg_raw_mem.size = access_size; 6721 return 0; 6722 } 6723 6724 for (i = min_off; i < max_off + access_size; i++) { 6725 u8 *stype; 6726 6727 slot = -i - 1; 6728 spi = slot / BPF_REG_SIZE; 6729 if (state->allocated_stack <= slot) { 6730 verbose(env, "allocated_stack too small\n"); 6731 return -EFAULT; 6732 } 6733 6734 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 6735 if (*stype == STACK_MISC) 6736 goto mark; 6737 if ((*stype == STACK_ZERO) || 6738 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 6739 if (clobber) { 6740 /* helper can write anything into the stack */ 6741 *stype = STACK_MISC; 6742 } 6743 goto mark; 6744 } 6745 6746 if (bpf_is_spilled_reg(&state->stack[spi]) && 6747 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 6748 env->allow_ptr_leaks)) { 6749 if (clobber) { 6750 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 6751 for (j = 0; j < BPF_REG_SIZE; j++) 6752 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 6753 } 6754 goto mark; 6755 } 6756 6757 if (*stype == STACK_POISON) { 6758 if (allow_poison) 6759 goto mark; 6760 verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n", 6761 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6762 } else if (tnum_is_const(reg->var_off)) { 6763 verbose(env, "invalid read from stack %s off %d+%d size %d\n", 6764 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6765 } else { 6766 char tn_buf[48]; 6767 6768 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6769 verbose(env, "invalid read from stack %s var_off %s+%d size %d\n", 6770 reg_arg_name(env, argno), tn_buf, i - min_off, access_size); 6771 } 6772 return -EACCES; 6773 mark: 6774 ; 6775 } 6776 return 0; 6777 } 6778 6779 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 6780 int access_size, enum bpf_access_type access_type, 6781 bool zero_size_allowed, 6782 struct bpf_call_arg_meta *meta) 6783 { 6784 struct bpf_reg_state *regs = cur_regs(env); 6785 u32 *max_access; 6786 6787 switch (base_type(reg->type)) { 6788 case PTR_TO_PACKET: 6789 case PTR_TO_PACKET_META: 6790 return check_packet_access(env, reg, argno, 0, access_size, 6791 zero_size_allowed); 6792 case PTR_TO_MAP_KEY: 6793 if (access_type == BPF_WRITE) { 6794 verbose(env, "%s cannot write into %s\n", 6795 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6796 return -EACCES; 6797 } 6798 return check_mem_region_access(env, reg, argno, 0, access_size, 6799 reg->map_ptr->key_size, false); 6800 case PTR_TO_MAP_VALUE: 6801 if (check_map_access_type(env, reg, 0, access_size, access_type)) 6802 return -EACCES; 6803 return check_map_access(env, reg, argno, 0, access_size, 6804 zero_size_allowed, ACCESS_HELPER); 6805 case PTR_TO_MEM: 6806 if (type_is_rdonly_mem(reg->type)) { 6807 if (access_type == BPF_WRITE) { 6808 verbose(env, "%s cannot write into %s\n", 6809 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6810 return -EACCES; 6811 } 6812 } 6813 return check_mem_region_access(env, reg, argno, 0, 6814 access_size, reg->mem_size, 6815 zero_size_allowed); 6816 case PTR_TO_BUF: 6817 if (type_is_rdonly_mem(reg->type)) { 6818 if (access_type == BPF_WRITE) { 6819 verbose(env, "%s cannot write into %s\n", 6820 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6821 return -EACCES; 6822 } 6823 6824 max_access = &env->prog->aux->max_rdonly_access; 6825 } else { 6826 max_access = &env->prog->aux->max_rdwr_access; 6827 } 6828 return check_buffer_access(env, reg, argno, 0, 6829 access_size, zero_size_allowed, 6830 max_access); 6831 case PTR_TO_STACK: 6832 return check_stack_range_initialized( 6833 env, reg, 6834 argno, 0, access_size, 6835 zero_size_allowed, access_type, meta); 6836 case PTR_TO_BTF_ID: 6837 return check_ptr_to_btf_access(env, regs, reg, argno, 0, 6838 access_size, access_type, -1); 6839 case PTR_TO_CTX: 6840 /* Only permit reading or writing syscall context using helper calls. */ 6841 if (is_var_ctx_off_allowed(env->prog)) { 6842 int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX, 6843 zero_size_allowed); 6844 if (err) 6845 return err; 6846 if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size) 6847 env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size; 6848 return 0; 6849 } 6850 fallthrough; 6851 default: /* scalar_value or invalid ptr */ 6852 /* Allow zero-byte read from NULL, regardless of pointer type */ 6853 if (zero_size_allowed && access_size == 0 && 6854 bpf_register_is_null(reg)) 6855 return 0; 6856 6857 verbose(env, "%s type=%s ", reg_arg_name(env, argno), 6858 reg_type_str(env, reg->type)); 6859 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 6860 return -EACCES; 6861 } 6862 } 6863 6864 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 6865 * size. 6866 * 6867 * @mem_reg contains the pointer, @size_reg contains the access size. 6868 */ 6869 static int check_mem_size_reg(struct bpf_verifier_env *env, 6870 struct bpf_reg_state *mem_reg, 6871 struct bpf_reg_state *size_reg, argno_t mem_argno, 6872 argno_t size_argno, enum bpf_access_type access_type, 6873 bool zero_size_allowed, 6874 struct bpf_call_arg_meta *meta) 6875 { 6876 int err; 6877 6878 /* This is used to refine r0 return value bounds for helpers 6879 * that enforce this value as an upper bound on return values. 6880 * See do_refine_retval_range() for helpers that can refine 6881 * the return value. C type of helper is u32 so we pull register 6882 * bound from umax_value however, if negative verifier errors 6883 * out. Only upper bounds can be learned because retval is an 6884 * int type and negative retvals are allowed. 6885 */ 6886 meta->msize_max_value = reg_umax(size_reg); 6887 6888 /* The register is SCALAR_VALUE; the access check happens using 6889 * its boundaries. For unprivileged variable accesses, disable 6890 * raw mode so that the program is required to initialize all 6891 * the memory that the helper could just partially fill up. 6892 */ 6893 if (!tnum_is_const(size_reg->var_off)) 6894 meta = NULL; 6895 6896 if (reg_smin(size_reg) < 0) { 6897 verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n", 6898 reg_arg_name(env, size_argno)); 6899 return -EACCES; 6900 } 6901 6902 if (reg_umin(size_reg) == 0 && !zero_size_allowed) { 6903 verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n", 6904 reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg)); 6905 return -EACCES; 6906 } 6907 6908 if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) { 6909 verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 6910 reg_arg_name(env, size_argno)); 6911 return -EACCES; 6912 } 6913 err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg), 6914 access_type, zero_size_allowed, meta); 6915 if (!err) { 6916 int regno = reg_from_argno(size_argno); 6917 6918 if (regno >= 0) 6919 err = mark_chain_precision(env, regno); 6920 else 6921 err = mark_stack_arg_precision(env, arg_idx_from_argno(size_argno)); 6922 } 6923 return err; 6924 } 6925 6926 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6927 argno_t argno, u32 mem_size) 6928 { 6929 bool may_be_null = type_may_be_null(reg->type); 6930 struct bpf_reg_state saved_reg; 6931 int err; 6932 6933 if (bpf_register_is_null(reg)) 6934 return 0; 6935 6936 if (mem_size > S32_MAX) { 6937 verbose(env, "%s memory size %u is too large\n", 6938 reg_arg_name(env, argno), mem_size); 6939 return -EACCES; 6940 } 6941 6942 /* Assuming that the register contains a value check if the memory 6943 * access is safe. Temporarily save and restore the register's state as 6944 * the conversion shouldn't be visible to a caller. 6945 */ 6946 if (may_be_null) { 6947 saved_reg = *reg; 6948 mark_ptr_not_null_reg(reg); 6949 } 6950 6951 int size = base_type(reg->type) == PTR_TO_STACK ? -(int)mem_size : mem_size; 6952 6953 err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, NULL); 6954 err = err ?: check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, NULL); 6955 6956 if (may_be_null) 6957 *reg = saved_reg; 6958 6959 return err; 6960 } 6961 6962 static int process_const_alloc_mem_size(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6963 argno_t argno, struct ret_mem_desc *ret_mem) 6964 { 6965 int regno = reg_from_argno(argno); 6966 int err; 6967 6968 if (ret_mem->found) { 6969 verifier_bug(env, "only one allocation size argument permitted"); 6970 return -EFAULT; 6971 } 6972 6973 if (!tnum_is_const(reg->var_off)) { 6974 verbose(env, "%s is not a const\n", reg_arg_name(env, argno)); 6975 return -EINVAL; 6976 } 6977 6978 if (reg->var_off.value > U32_MAX) { 6979 verbose(env, "%s allocation size exceeds u32 max\n", reg_arg_name(env, argno)); 6980 return -EINVAL; 6981 } 6982 6983 if (regno >= 0) 6984 err = mark_chain_precision(env, regno); 6985 else 6986 err = mark_stack_arg_precision(env, arg_idx_from_argno(argno)); 6987 if (err) 6988 return err; 6989 6990 ret_mem->size = reg->var_off.value; 6991 ret_mem->found = true; 6992 6993 return 0; 6994 } 6995 6996 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *mem_reg, 6997 struct bpf_reg_state *size_reg, argno_t mem_argno, argno_t size_argno) 6998 { 6999 bool may_be_null = type_may_be_null(mem_reg->type); 7000 struct bpf_reg_state saved_reg; 7001 struct bpf_call_arg_meta meta; 7002 int err; 7003 7004 memset(&meta, 0, sizeof(meta)); 7005 7006 if (may_be_null) { 7007 saved_reg = *mem_reg; 7008 mark_ptr_not_null_reg(mem_reg); 7009 } 7010 7011 err = check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_READ, true, &meta); 7012 err = err ?: check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_WRITE, true, &meta); 7013 7014 if (may_be_null) 7015 *mem_reg = saved_reg; 7016 7017 return err; 7018 } 7019 7020 enum { 7021 PROCESS_SPIN_LOCK = (1 << 0), 7022 PROCESS_RES_LOCK = (1 << 1), 7023 PROCESS_LOCK_IRQ = (1 << 2), 7024 }; 7025 7026 /* Implementation details: 7027 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7028 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7029 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7030 * Two separate bpf_obj_new will also have different reg->id. 7031 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7032 * clears reg->id after value_or_null->value transition, since the verifier only 7033 * cares about the range of access to valid map value pointer and doesn't care 7034 * about actual address of the map element. 7035 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7036 * reg->id > 0 after value_or_null->value transition. By doing so 7037 * two bpf_map_lookups will be considered two different pointers that 7038 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7039 * returned from bpf_obj_new. 7040 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7041 * dead-locks. 7042 * Since only one bpf_spin_lock is allowed the checks are simpler than 7043 * reg_is_refcounted() logic. The verifier needs to remember only 7044 * one spin_lock instead of array of acquired_refs. 7045 * env->cur_state->active_locks remembers which map value element or allocated 7046 * object got locked and clears it after bpf_spin_unlock. 7047 */ 7048 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags) 7049 { 7050 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK; 7051 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin"; 7052 struct bpf_verifier_state *cur = env->cur_state; 7053 bool is_const = tnum_is_const(reg->var_off); 7054 bool is_irq = flags & PROCESS_LOCK_IRQ; 7055 u64 val = reg->var_off.value; 7056 struct bpf_map *map = NULL; 7057 struct btf *btf = NULL; 7058 struct btf_record *rec; 7059 u32 spin_lock_off; 7060 int err; 7061 7062 if (!is_const) { 7063 verbose(env, 7064 "%s doesn't have constant offset. %s_lock has to be at the constant offset\n", 7065 reg_arg_name(env, argno), lock_str); 7066 return -EINVAL; 7067 } 7068 if (reg->type == PTR_TO_MAP_VALUE) { 7069 map = reg->map_ptr; 7070 if (!map->btf) { 7071 verbose(env, 7072 "map '%s' has to have BTF in order to use %s_lock\n", 7073 map->name, lock_str); 7074 return -EINVAL; 7075 } 7076 } else { 7077 btf = reg->btf; 7078 } 7079 7080 rec = reg_btf_record(reg); 7081 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) { 7082 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local", 7083 map ? map->name : "kptr", lock_str); 7084 return -EINVAL; 7085 } 7086 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off; 7087 if (spin_lock_off != val) { 7088 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n", 7089 val, lock_str, spin_lock_off); 7090 return -EINVAL; 7091 } 7092 if (is_lock) { 7093 void *ptr; 7094 int type; 7095 7096 if (map) 7097 ptr = map; 7098 else 7099 ptr = btf; 7100 7101 if (!is_res_lock && cur->active_locks) { 7102 if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) { 7103 verbose(env, 7104 "Locking two bpf_spin_locks are not allowed\n"); 7105 return -EINVAL; 7106 } 7107 } else if (is_res_lock && cur->active_locks) { 7108 if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) { 7109 verbose(env, "Acquiring the same lock again, AA deadlock detected\n"); 7110 return -EINVAL; 7111 } 7112 } 7113 7114 if (is_res_lock && is_irq) 7115 type = REF_TYPE_RES_LOCK_IRQ; 7116 else if (is_res_lock) 7117 type = REF_TYPE_RES_LOCK; 7118 else 7119 type = REF_TYPE_LOCK; 7120 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr); 7121 if (err < 0) { 7122 verbose(env, "Failed to acquire lock state\n"); 7123 return err; 7124 } 7125 } else { 7126 void *ptr; 7127 int type; 7128 7129 if (map) 7130 ptr = map; 7131 else 7132 ptr = btf; 7133 7134 if (!cur->active_locks) { 7135 verbose(env, "%s_unlock without taking a lock\n", lock_str); 7136 return -EINVAL; 7137 } 7138 7139 if (is_res_lock && is_irq) 7140 type = REF_TYPE_RES_LOCK_IRQ; 7141 else if (is_res_lock) 7142 type = REF_TYPE_RES_LOCK; 7143 else 7144 type = REF_TYPE_LOCK; 7145 if (!find_lock_state(cur, type, reg->id, ptr)) { 7146 verbose(env, "%s_unlock of different lock\n", lock_str); 7147 return -EINVAL; 7148 } 7149 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) { 7150 verbose(env, "%s_unlock cannot be out of order\n", lock_str); 7151 return -EINVAL; 7152 } 7153 if (release_lock_state(cur, type, reg->id, ptr)) { 7154 verbose(env, "%s_unlock of different lock\n", lock_str); 7155 return -EINVAL; 7156 } 7157 7158 invalidate_non_owning_refs(env); 7159 } 7160 return 0; 7161 } 7162 7163 /* Check if @regno is a pointer to a specific field in a map value */ 7164 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7165 enum btf_field_type field_type, 7166 struct bpf_map_desc *map_desc) 7167 { 7168 bool is_const = tnum_is_const(reg->var_off); 7169 struct bpf_map *map = reg->map_ptr; 7170 u64 val = reg->var_off.value; 7171 const char *struct_name = btf_field_type_name(field_type); 7172 int field_off = -1; 7173 7174 if (!is_const) { 7175 verbose(env, 7176 "%s doesn't have constant offset. %s has to be at the constant offset\n", 7177 reg_arg_name(env, argno), struct_name); 7178 return -EINVAL; 7179 } 7180 if (!map->btf) { 7181 verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name, 7182 struct_name); 7183 return -EINVAL; 7184 } 7185 if (!btf_record_has_field(map->record, field_type)) { 7186 verbose(env, "map '%s' has no valid %s\n", map->name, struct_name); 7187 return -EINVAL; 7188 } 7189 switch (field_type) { 7190 case BPF_TIMER: 7191 field_off = map->record->timer_off; 7192 break; 7193 case BPF_TASK_WORK: 7194 field_off = map->record->task_work_off; 7195 break; 7196 case BPF_WORKQUEUE: 7197 field_off = map->record->wq_off; 7198 break; 7199 default: 7200 verifier_bug(env, "unsupported BTF field type: %s\n", struct_name); 7201 return -EINVAL; 7202 } 7203 if (field_off != val) { 7204 verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n", 7205 val, struct_name, field_off); 7206 return -EINVAL; 7207 } 7208 if (map_desc->ptr) { 7209 verifier_bug(env, "Two map pointers in a %s helper", struct_name); 7210 return -EFAULT; 7211 } 7212 map_desc->uid = reg->map_uid; 7213 map_desc->ptr = map; 7214 return 0; 7215 } 7216 7217 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7218 struct bpf_map_desc *map) 7219 { 7220 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 7221 verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n"); 7222 return -EOPNOTSUPP; 7223 } 7224 return check_map_field_pointer(env, reg, argno, BPF_TIMER, map); 7225 } 7226 7227 static int process_timer_helper(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7228 struct bpf_call_arg_meta *meta) 7229 { 7230 return process_timer_func(env, reg, argno, &meta->map); 7231 } 7232 7233 static int process_timer_kfunc(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7234 struct bpf_call_arg_meta *meta) 7235 { 7236 return process_timer_func(env, reg, argno, &meta->map); 7237 } 7238 7239 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7240 struct bpf_call_arg_meta *meta) 7241 { 7242 struct bpf_reg_state *reg = reg_state(env, regno); 7243 struct btf_field *kptr_field; 7244 struct bpf_map *map_ptr; 7245 struct btf_record *rec; 7246 u32 kptr_off; 7247 7248 if (type_is_ptr_alloc_obj(reg->type)) { 7249 rec = reg_btf_record(reg); 7250 } else { /* PTR_TO_MAP_VALUE */ 7251 map_ptr = reg->map_ptr; 7252 if (!map_ptr->btf) { 7253 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7254 map_ptr->name); 7255 return -EINVAL; 7256 } 7257 rec = map_ptr->record; 7258 meta->map.ptr = map_ptr; 7259 } 7260 7261 if (!tnum_is_const(reg->var_off)) { 7262 verbose(env, 7263 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7264 regno); 7265 return -EINVAL; 7266 } 7267 7268 if (!btf_record_has_field(rec, BPF_KPTR)) { 7269 verbose(env, "R%d has no valid kptr\n", regno); 7270 return -EINVAL; 7271 } 7272 7273 kptr_off = reg->var_off.value; 7274 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 7275 if (!kptr_field) { 7276 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7277 return -EACCES; 7278 } 7279 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7280 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7281 return -EACCES; 7282 } 7283 meta->kptr_field = kptr_field; 7284 return 0; 7285 } 7286 7287 /* 7288 * Validate dynptr arguments for helper, kfunc and subprog. 7289 * 7290 * @dynptr is both input and output. It is populated when the argument is 7291 * tagged with MEM_UNINIT (i.e., the dynptr argument that will be constructed) 7292 * and consumed when the argument is expecting to be an initialized dynptr. 7293 * @parent_id is used to track the referenced parent object (e.g., file or skb in 7294 * qdisc program) when constructing a dynptr. 7295 * 7296 * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7297 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7298 * 7299 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7300 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7301 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7302 * 7303 * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the 7304 * dynptr points to. At the first level, the verifier will make sure a 7305 * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of 7306 * a dynptr's view (i.e., start and offset) is not tracked as there is not such 7307 * use case. The second level is tracked using the upper bit of bpf_dynptr->size 7308 * and checked dynamically during runtime. 7309 */ 7310 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7311 argno_t argno, int insn_idx, enum bpf_arg_type arg_type, 7312 struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr) 7313 { 7314 int spi, err = 0; 7315 7316 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 7317 verbose(env, 7318 "%s expected pointer to stack or const struct bpf_dynptr\n", 7319 reg_arg_name(env, argno)); 7320 return -EINVAL; 7321 } 7322 7323 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7324 * constructing a mutable bpf_dynptr object. 7325 * 7326 * Currently, this is only possible with PTR_TO_STACK 7327 * pointing to a region of at least 16 bytes which doesn't 7328 * contain an existing bpf_dynptr. 7329 * 7330 * OBJ_RELEASE - Points to a initialized bpf_dynptr that will be 7331 * destroyed. 7332 * 7333 * None - Points to a initialized dynptr that cannot be 7334 * reinitialized or destroyed. However, the view of the 7335 * dynptr and the memory it points to may be mutated. 7336 */ 7337 if (arg_type & MEM_UNINIT) { 7338 int i; 7339 7340 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7341 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7342 return -EINVAL; 7343 } 7344 7345 /* we write BPF_DW bits (8 bytes) at a time */ 7346 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7347 err = check_mem_access(env, insn_idx, reg, argno, 7348 i, BPF_DW, BPF_WRITE, -1, false, false); 7349 if (err) 7350 return err; 7351 } 7352 7353 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, ref_obj, dynptr); 7354 } else /* OBJ_RELEASE and None case from above */ { 7355 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7356 if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) { 7357 verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n"); 7358 return -EINVAL; 7359 } 7360 7361 if (!is_dynptr_reg_valid_init(env, reg)) { 7362 verbose(env, "Expected an initialized dynptr as %s\n", 7363 reg_arg_name(env, argno)); 7364 return -EINVAL; 7365 } 7366 7367 /* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */ 7368 if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) { 7369 verbose(env, 7370 "Expected a dynptr of type %s as %s\n", 7371 dynptr_type_str(arg_to_dynptr_type(arg_type)), 7372 reg_arg_name(env, argno)); 7373 return -EINVAL; 7374 } 7375 7376 if (reg->type != CONST_PTR_TO_DYNPTR) { 7377 struct bpf_func_state *state = bpf_func(env, reg); 7378 7379 spi = dynptr_get_spi(env, reg); 7380 if (spi < 0) 7381 return spi; 7382 7383 /* 7384 * For CONST_PTR_TO_DYNPTR, reg is already scratched by check_reg_arg 7385 * in check_helper_call and mark_btf_func_reg_size in check_kfunc_call. 7386 */ 7387 mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS); 7388 7389 reg = &state->stack[spi].spilled_ptr; 7390 } 7391 7392 if (dynptr) { 7393 dynptr->type = reg->dynptr.type; 7394 dynptr->id = reg->id; 7395 dynptr->parent_id = reg->parent_id; 7396 } 7397 } 7398 return err; 7399 } 7400 7401 static bool is_iter_kfunc(struct bpf_call_arg_meta *meta) 7402 { 7403 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7404 } 7405 7406 static bool is_iter_new_kfunc(struct bpf_call_arg_meta *meta) 7407 { 7408 return meta->kfunc_flags & KF_ITER_NEW; 7409 } 7410 7411 7412 static bool is_iter_destroy_kfunc(struct bpf_call_arg_meta *meta) 7413 { 7414 return meta->kfunc_flags & KF_ITER_DESTROY; 7415 } 7416 7417 static bool is_kfunc_arg_iter(struct bpf_call_arg_meta *meta, int arg_idx, 7418 const struct btf_param *arg) 7419 { 7420 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7421 * kfunc is iter state pointer 7422 */ 7423 if (is_iter_kfunc(meta)) 7424 return arg_idx == 0; 7425 7426 /* iter passed as an argument to a generic kfunc */ 7427 return btf_param_match_suffix(meta->btf, arg, "__iter"); 7428 } 7429 7430 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx, 7431 struct bpf_call_arg_meta *meta) 7432 { 7433 struct bpf_func_state *state = bpf_func(env, reg); 7434 const struct btf_type *t; 7435 u32 arg_idx = arg_idx_from_argno(argno); 7436 int spi, err, i, nr_slots, btf_id; 7437 7438 if (reg->type != PTR_TO_STACK) { 7439 verbose(env, "%s expected pointer to an iterator on stack\n", 7440 reg_arg_name(env, argno)); 7441 return -EINVAL; 7442 } 7443 7444 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 7445 * ensures struct convention, so we wouldn't need to do any BTF 7446 * validation here. But given iter state can be passed as a parameter 7447 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 7448 * conservative here. 7449 */ 7450 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg_idx); 7451 if (btf_id < 0) { 7452 verbose(env, "expected valid iter pointer as %s\n", 7453 reg_arg_name(env, argno)); 7454 return -EINVAL; 7455 } 7456 t = btf_type_by_id(meta->btf, btf_id); 7457 nr_slots = t->size / BPF_REG_SIZE; 7458 7459 if (is_iter_new_kfunc(meta)) { 7460 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7461 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7462 verbose(env, "expected uninitialized iter_%s as %s\n", 7463 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7464 return -EINVAL; 7465 } 7466 7467 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7468 err = check_mem_access(env, insn_idx, reg, argno, 7469 i, BPF_DW, BPF_WRITE, -1, false, false); 7470 if (err) 7471 return err; 7472 } 7473 7474 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7475 if (err) 7476 return err; 7477 } else { 7478 /* iter_next() or iter_destroy(), as well as any kfunc 7479 * accepting iter argument, expect initialized iter state 7480 */ 7481 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7482 switch (err) { 7483 case 0: 7484 break; 7485 case -EINVAL: 7486 verbose(env, "expected an initialized iter_%s as %s\n", 7487 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7488 return err; 7489 case -EPROTO: 7490 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7491 return err; 7492 default: 7493 return err; 7494 } 7495 7496 spi = iter_get_spi(env, reg, nr_slots); 7497 if (spi < 0) 7498 return spi; 7499 7500 mark_stack_slots_scratched(env, spi, nr_slots); 7501 7502 /* remember meta->iter info for process_iter_next_call() */ 7503 meta->iter.spi = spi; 7504 meta->iter.frameno = reg->frameno; 7505 update_ref_obj(&meta->ref_obj, &state->stack[spi].spilled_ptr); 7506 7507 if (is_iter_destroy_kfunc(meta)) { 7508 err = unmark_stack_slots_iter(env, reg, nr_slots); 7509 if (err) 7510 return err; 7511 } 7512 } 7513 7514 return 0; 7515 } 7516 7517 /* Look for a previous loop entry at insn_idx: nearest parent state 7518 * stopped at insn_idx with callsites matching those in cur->frame. 7519 */ 7520 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7521 struct bpf_verifier_state *cur, 7522 int insn_idx) 7523 { 7524 struct bpf_verifier_state_list *sl; 7525 struct bpf_verifier_state *st; 7526 struct list_head *pos, *head; 7527 7528 /* Explored states are pushed in stack order, most recent states come first */ 7529 head = bpf_explored_state(env, insn_idx); 7530 list_for_each(pos, head) { 7531 sl = container_of(pos, struct bpf_verifier_state_list, node); 7532 /* If st->branches != 0 state is a part of current DFS verification path, 7533 * hence cur & st for a loop. 7534 */ 7535 st = &sl->state; 7536 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7537 st->dfs_depth < cur->dfs_depth) 7538 return st; 7539 } 7540 7541 return NULL; 7542 } 7543 7544 /* 7545 * Check if scalar registers are exact for the purpose of not widening. 7546 * More lenient than regs_exact() 7547 */ 7548 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold, 7549 const struct bpf_reg_state *rcur) 7550 { 7551 return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)); 7552 } 7553 7554 static void maybe_widen_reg(struct bpf_verifier_env *env, 7555 struct bpf_reg_state *rold, struct bpf_reg_state *rcur) 7556 { 7557 if (rold->type != SCALAR_VALUE) 7558 return; 7559 if (rold->type != rcur->type) 7560 return; 7561 if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur)) 7562 return; 7563 __mark_reg_unknown(env, rcur); 7564 } 7565 7566 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7567 struct bpf_verifier_state *old, 7568 struct bpf_verifier_state *cur) 7569 { 7570 struct bpf_func_state *fold, *fcur; 7571 int i, fr, num_slots; 7572 7573 for (fr = old->curframe; fr >= 0; fr--) { 7574 fold = old->frame[fr]; 7575 fcur = cur->frame[fr]; 7576 7577 for (i = 0; i < MAX_BPF_REG; i++) 7578 maybe_widen_reg(env, 7579 &fold->regs[i], 7580 &fcur->regs[i]); 7581 7582 num_slots = min(fold->allocated_stack / BPF_REG_SIZE, 7583 fcur->allocated_stack / BPF_REG_SIZE); 7584 for (i = 0; i < num_slots; i++) { 7585 if (!bpf_is_spilled_reg(&fold->stack[i]) || 7586 !bpf_is_spilled_reg(&fcur->stack[i])) 7587 continue; 7588 7589 maybe_widen_reg(env, 7590 &fold->stack[i].spilled_ptr, 7591 &fcur->stack[i].spilled_ptr); 7592 } 7593 } 7594 return 0; 7595 } 7596 7597 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 7598 struct bpf_call_arg_meta *meta) 7599 { 7600 int iter_frameno = meta->iter.frameno; 7601 int iter_spi = meta->iter.spi; 7602 7603 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7604 } 7605 7606 /* process_iter_next_call() is called when verifier gets to iterator's next 7607 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7608 * to it as just "iter_next()" in comments below. 7609 * 7610 * BPF verifier relies on a crucial contract for any iter_next() 7611 * implementation: it should *eventually* return NULL, and once that happens 7612 * it should keep returning NULL. That is, once iterator exhausts elements to 7613 * iterate, it should never reset or spuriously return new elements. 7614 * 7615 * With the assumption of such contract, process_iter_next_call() simulates 7616 * a fork in the verifier state to validate loop logic correctness and safety 7617 * without having to simulate infinite amount of iterations. 7618 * 7619 * In current state, we first assume that iter_next() returned NULL and 7620 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7621 * conditions we should not form an infinite loop and should eventually reach 7622 * exit. 7623 * 7624 * Besides that, we also fork current state and enqueue it for later 7625 * verification. In a forked state we keep iterator state as ACTIVE 7626 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7627 * also bump iteration depth to prevent erroneous infinite loop detection 7628 * later on (see iter_active_depths_differ() comment for details). In this 7629 * state we assume that we'll eventually loop back to another iter_next() 7630 * calls (it could be in exactly same location or in some other instruction, 7631 * it doesn't matter, we don't make any unnecessary assumptions about this, 7632 * everything revolves around iterator state in a stack slot, not which 7633 * instruction is calling iter_next()). When that happens, we either will come 7634 * to iter_next() with equivalent state and can conclude that next iteration 7635 * will proceed in exactly the same way as we just verified, so it's safe to 7636 * assume that loop converges. If not, we'll go on another iteration 7637 * simulation with a different input state, until all possible starting states 7638 * are validated or we reach maximum number of instructions limit. 7639 * 7640 * This way, we will either exhaustively discover all possible input states 7641 * that iterator loop can start with and eventually will converge, or we'll 7642 * effectively regress into bounded loop simulation logic and either reach 7643 * maximum number of instructions if loop is not provably convergent, or there 7644 * is some statically known limit on number of iterations (e.g., if there is 7645 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7646 * 7647 * Iteration convergence logic in is_state_visited() relies on exact 7648 * states comparison, which ignores read and precision marks. 7649 * This is necessary because read and precision marks are not finalized 7650 * while in the loop. Exact comparison might preclude convergence for 7651 * simple programs like below: 7652 * 7653 * i = 0; 7654 * while(iter_next(&it)) 7655 * i++; 7656 * 7657 * At each iteration step i++ would produce a new distinct state and 7658 * eventually instruction processing limit would be reached. 7659 * 7660 * To avoid such behavior speculatively forget (widen) range for 7661 * imprecise scalar registers, if those registers were not precise at the 7662 * end of the previous iteration and do not match exactly. 7663 * 7664 * This is a conservative heuristic that allows to verify wide range of programs, 7665 * however it precludes verification of programs that conjure an 7666 * imprecise value on the first loop iteration and use it as precise on a second. 7667 * For example, the following safe program would fail to verify: 7668 * 7669 * struct bpf_num_iter it; 7670 * int arr[10]; 7671 * int i = 0, a = 0; 7672 * bpf_iter_num_new(&it, 0, 10); 7673 * while (bpf_iter_num_next(&it)) { 7674 * if (a == 0) { 7675 * a = 1; 7676 * i = 7; // Because i changed verifier would forget 7677 * // it's range on second loop entry. 7678 * } else { 7679 * arr[i] = 42; // This would fail to verify. 7680 * } 7681 * } 7682 * bpf_iter_num_destroy(&it); 7683 */ 7684 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7685 struct bpf_call_arg_meta *meta) 7686 { 7687 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7688 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7689 struct bpf_reg_state *cur_iter, *queued_iter; 7690 7691 BTF_TYPE_EMIT(struct bpf_iter); 7692 7693 cur_iter = get_iter_from_state(cur_st, meta); 7694 7695 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7696 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7697 verifier_bug(env, "unexpected iterator state %d (%s)", 7698 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7699 return -EFAULT; 7700 } 7701 7702 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7703 /* Because iter_next() call is a checkpoint is_state_visitied() 7704 * should guarantee parent state with same call sites and insn_idx. 7705 */ 7706 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7707 !same_callsites(cur_st->parent, cur_st)) { 7708 verifier_bug(env, "bad parent state for iter next call"); 7709 return -EFAULT; 7710 } 7711 /* Note cur_st->parent in the call below, it is necessary to skip 7712 * checkpoint created for cur_st by is_state_visited() 7713 * right at this instruction. 7714 */ 7715 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7716 /* branch out active iter state */ 7717 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7718 if (IS_ERR(queued_st)) 7719 return PTR_ERR(queued_st); 7720 7721 queued_iter = get_iter_from_state(queued_st, meta); 7722 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7723 queued_iter->iter.depth++; 7724 if (prev_st) 7725 widen_imprecise_scalars(env, prev_st, queued_st); 7726 7727 queued_fr = queued_st->frame[queued_st->curframe]; 7728 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7729 } 7730 7731 /* switch to DRAINED state, but keep the depth unchanged */ 7732 /* mark current iter state as drained and assume returned NULL */ 7733 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7734 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7735 7736 return 0; 7737 } 7738 7739 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7740 { 7741 return type == ARG_CONST_SIZE || 7742 type == ARG_CONST_SIZE_OR_ZERO; 7743 } 7744 7745 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 7746 { 7747 /* 7748 * A map value output buffer (e.g. bpf_map_pop_elem) is also a raw 7749 * (uninitialized) memory argument, and like ARG_PTR_TO_MEM it may be 7750 * passed as a PTR_TO_STACK that reaches check_stack_range_initialized(). 7751 */ 7752 return (base_type(type) == ARG_PTR_TO_MEM || 7753 base_type(type) == ARG_PTR_TO_MAP_VALUE) && 7754 type & MEM_UNINIT; 7755 } 7756 7757 static bool arg_type_is_release(enum bpf_arg_type type) 7758 { 7759 return type & OBJ_RELEASE; 7760 } 7761 7762 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7763 { 7764 return base_type(type) == ARG_PTR_TO_DYNPTR; 7765 } 7766 7767 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7768 const struct bpf_call_arg_meta *meta, 7769 enum bpf_arg_type *arg_type) 7770 { 7771 if (!meta->map.ptr) { 7772 /* kernel subsystem misconfigured verifier */ 7773 verifier_bug(env, "invalid map_ptr to access map->type"); 7774 return -EFAULT; 7775 } 7776 7777 switch (meta->map.ptr->map_type) { 7778 case BPF_MAP_TYPE_SOCKMAP: 7779 case BPF_MAP_TYPE_SOCKHASH: 7780 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7781 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7782 } else { 7783 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7784 return -EINVAL; 7785 } 7786 break; 7787 case BPF_MAP_TYPE_BLOOM_FILTER: 7788 if (meta->func_id == BPF_FUNC_map_peek_elem) 7789 *arg_type = ARG_PTR_TO_MAP_VALUE; 7790 break; 7791 default: 7792 break; 7793 } 7794 return 0; 7795 } 7796 7797 struct bpf_reg_types { 7798 const enum bpf_reg_type types[10]; 7799 u32 *btf_id; 7800 }; 7801 7802 static const struct bpf_reg_types sock_types = { 7803 .types = { 7804 PTR_TO_SOCK_COMMON, 7805 PTR_TO_SOCKET, 7806 PTR_TO_TCP_SOCK, 7807 PTR_TO_XDP_SOCK, 7808 }, 7809 }; 7810 7811 #ifdef CONFIG_NET 7812 static const struct bpf_reg_types btf_id_sock_common_types = { 7813 .types = { 7814 PTR_TO_SOCK_COMMON, 7815 PTR_TO_SOCKET, 7816 PTR_TO_TCP_SOCK, 7817 PTR_TO_XDP_SOCK, 7818 PTR_TO_BTF_ID, 7819 PTR_TO_BTF_ID | PTR_TRUSTED, 7820 }, 7821 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7822 }; 7823 #endif 7824 7825 static const struct bpf_reg_types mem_types = { 7826 .types = { 7827 PTR_TO_STACK, 7828 PTR_TO_PACKET, 7829 PTR_TO_PACKET_META, 7830 PTR_TO_MAP_KEY, 7831 PTR_TO_MAP_VALUE, 7832 PTR_TO_MEM, 7833 PTR_TO_MEM | MEM_RINGBUF, 7834 PTR_TO_BUF, 7835 PTR_TO_BTF_ID | PTR_TRUSTED, 7836 PTR_TO_CTX, 7837 }, 7838 }; 7839 7840 static const struct bpf_reg_types spin_lock_types = { 7841 .types = { 7842 PTR_TO_MAP_VALUE, 7843 PTR_TO_BTF_ID | MEM_ALLOC, 7844 } 7845 }; 7846 7847 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7848 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7849 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7850 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7851 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7852 static const struct bpf_reg_types btf_ptr_types = { 7853 .types = { 7854 PTR_TO_BTF_ID, 7855 PTR_TO_BTF_ID | PTR_TRUSTED, 7856 PTR_TO_BTF_ID | MEM_RCU, 7857 }, 7858 }; 7859 static const struct bpf_reg_types percpu_btf_ptr_types = { 7860 .types = { 7861 PTR_TO_BTF_ID | MEM_PERCPU, 7862 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 7863 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7864 } 7865 }; 7866 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7867 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7868 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7869 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7870 static const struct bpf_reg_types kptr_xchg_dest_types = { 7871 .types = { 7872 PTR_TO_MAP_VALUE, 7873 PTR_TO_BTF_ID | MEM_ALLOC, 7874 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF, 7875 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU, 7876 } 7877 }; 7878 static const struct bpf_reg_types dynptr_types = { 7879 .types = { 7880 PTR_TO_STACK, 7881 CONST_PTR_TO_DYNPTR, 7882 } 7883 }; 7884 7885 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7886 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7887 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7888 [ARG_CONST_SIZE] = &scalar_types, 7889 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7890 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7891 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7892 [ARG_PTR_TO_CTX] = &context_types, 7893 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7894 #ifdef CONFIG_NET 7895 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7896 #endif 7897 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7898 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7899 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7900 [ARG_PTR_TO_MEM] = &mem_types, 7901 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7902 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7903 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7904 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7905 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7906 [ARG_PTR_TO_TIMER] = &timer_types, 7907 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 7908 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7909 }; 7910 7911 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7912 enum bpf_arg_type arg_type, 7913 const u32 *arg_btf_id, 7914 struct bpf_call_arg_meta *meta) 7915 { 7916 enum bpf_reg_type expected, type = reg->type; 7917 const struct bpf_reg_types *compatible; 7918 int i, j, err; 7919 7920 compatible = compatible_reg_types[base_type(arg_type)]; 7921 if (!compatible) { 7922 verifier_bug(env, "unsupported arg type %d", arg_type); 7923 return -EFAULT; 7924 } 7925 7926 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7927 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7928 * 7929 * Same for MAYBE_NULL: 7930 * 7931 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7932 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7933 * 7934 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 7935 * 7936 * Therefore we fold these flags depending on the arg_type before comparison. 7937 */ 7938 if (arg_type & MEM_RDONLY) 7939 type &= ~MEM_RDONLY; 7940 if (arg_type & PTR_MAYBE_NULL) 7941 type &= ~PTR_MAYBE_NULL; 7942 if (base_type(arg_type) == ARG_PTR_TO_MEM) 7943 type &= ~DYNPTR_TYPE_FLAG_MASK; 7944 7945 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 7946 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && reg_from_argno(argno) == BPF_REG_2) { 7947 type &= ~MEM_ALLOC; 7948 type &= ~MEM_PERCPU; 7949 } 7950 7951 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7952 expected = compatible->types[i]; 7953 if (expected == NOT_INIT) 7954 break; 7955 7956 if (type == expected) 7957 goto found; 7958 } 7959 7960 verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7961 for (j = 0; j + 1 < i; j++) 7962 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7963 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7964 return -EACCES; 7965 7966 found: 7967 if (base_type(reg->type) != PTR_TO_BTF_ID) 7968 return 0; 7969 7970 if (compatible == &mem_types) { 7971 if (!(arg_type & MEM_RDONLY)) { 7972 verbose(env, 7973 "%s() may write into memory pointed by %s type=%s\n", 7974 func_id_name(meta->func_id), 7975 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7976 return -EACCES; 7977 } 7978 return 0; 7979 } 7980 7981 switch ((int)reg->type) { 7982 case PTR_TO_BTF_ID: 7983 case PTR_TO_BTF_ID | PTR_TRUSTED: 7984 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 7985 case PTR_TO_BTF_ID | MEM_RCU: 7986 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 7987 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 7988 { 7989 /* For bpf_sk_release, it needs to match against first member 7990 * 'struct sock_common', hence make an exception for it. This 7991 * allows bpf_sk_release to work for multiple socket types. 7992 */ 7993 bool strict_type_match = arg_type_is_release(arg_type) && 7994 meta->func_id != BPF_FUNC_sk_release; 7995 7996 if (type_may_be_null(reg->type) && 7997 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 7998 verbose(env, "Possibly NULL pointer passed to helper %s\n", 7999 reg_arg_name(env, argno)); 8000 return -EACCES; 8001 } 8002 8003 if (!arg_btf_id) { 8004 if (!compatible->btf_id) { 8005 verifier_bug(env, "missing arg compatible BTF ID"); 8006 return -EFAULT; 8007 } 8008 arg_btf_id = compatible->btf_id; 8009 } 8010 8011 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8012 if (map_kptr_match_type(env, meta->kptr_field, reg, reg_from_argno(argno))) 8013 return -EACCES; 8014 } else { 8015 if (arg_btf_id == BPF_PTR_POISON) { 8016 verbose(env, "verifier internal error:"); 8017 verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n", 8018 reg_arg_name(env, argno)); 8019 return -EACCES; 8020 } 8021 8022 err = __check_ptr_off_reg(env, reg, argno, true); 8023 if (err) 8024 return err; 8025 8026 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 8027 reg->var_off.value, btf_vmlinux, *arg_btf_id, 8028 strict_type_match, !type_is_alloc(reg->type))) { 8029 verbose(env, "%s is of type %s but %s is expected\n", 8030 reg_arg_name(env, argno), 8031 btf_type_name(reg->btf, reg->btf_id), 8032 btf_type_name(btf_vmlinux, *arg_btf_id)); 8033 return -EACCES; 8034 } 8035 } 8036 break; 8037 } 8038 case PTR_TO_BTF_ID | MEM_ALLOC: 8039 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8040 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8041 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8042 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8043 meta->func_id != BPF_FUNC_kptr_xchg) { 8044 verifier_bug(env, "unimplemented handling of MEM_ALLOC"); 8045 return -EFAULT; 8046 } 8047 /* Check if local kptr in src arg matches kptr in dst arg */ 8048 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8049 int regno = reg_from_argno(argno); 8050 8051 if (regno == BPF_REG_2 && 8052 map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8053 return -EACCES; 8054 } 8055 break; 8056 case PTR_TO_BTF_ID | MEM_PERCPU: 8057 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8058 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8059 /* Handled by helper specific checks */ 8060 break; 8061 default: 8062 verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match"); 8063 return -EFAULT; 8064 } 8065 return 0; 8066 } 8067 8068 static struct btf_field * 8069 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8070 { 8071 struct btf_field *field; 8072 struct btf_record *rec; 8073 8074 rec = reg_btf_record(reg); 8075 if (!rec) 8076 return NULL; 8077 8078 field = btf_record_find(rec, off, fields); 8079 if (!field) 8080 return NULL; 8081 8082 return field; 8083 } 8084 8085 static int __check_func_arg_reg_off(struct bpf_verifier_env *env, 8086 const struct bpf_reg_state *reg, argno_t argno, 8087 enum bpf_arg_type arg_type, 8088 bool btf_id_fixed_off_ok) 8089 { 8090 u32 type = reg->type; 8091 8092 /* When referenced register is passed to release function, its fixed 8093 * offset must be 0. 8094 * 8095 * We will check arg_type_is_release reg has id when storing 8096 * meta->release_regno. 8097 */ 8098 if (arg_type_is_release(arg_type)) { 8099 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8100 * may not directly point to the object being released, but to 8101 * dynptr pointing to such object, which might be at some offset 8102 * on the stack. In that case, we simply to fallback to the 8103 * default handling. 8104 */ 8105 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8106 return 0; 8107 8108 /* Doing check_ptr_off_reg check for the offset will catch this 8109 * because fixed_off_ok is false, but checking here allows us 8110 * to give the user a better error message. 8111 */ 8112 if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) { 8113 verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n", 8114 reg_arg_name(env, argno)); 8115 return -EINVAL; 8116 } 8117 } 8118 8119 switch (type) { 8120 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8121 case PTR_TO_STACK: 8122 case PTR_TO_PACKET: 8123 case PTR_TO_PACKET_META: 8124 case PTR_TO_MAP_KEY: 8125 case PTR_TO_MAP_VALUE: 8126 case PTR_TO_MEM: 8127 case PTR_TO_MEM | MEM_RDONLY: 8128 case PTR_TO_MEM | MEM_RINGBUF: 8129 case PTR_TO_BUF: 8130 case PTR_TO_BUF | MEM_RDONLY: 8131 case PTR_TO_ARENA: 8132 case SCALAR_VALUE: 8133 return 0; 8134 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8135 * fixed offset. 8136 */ 8137 case PTR_TO_BTF_ID: 8138 case PTR_TO_BTF_ID | MEM_ALLOC: 8139 case PTR_TO_BTF_ID | PTR_TRUSTED: 8140 case PTR_TO_BTF_ID | MEM_RCU: 8141 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8142 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8143 /* When referenced PTR_TO_BTF_ID is passed to release function, 8144 * its fixed offset must be 0. In the other cases, fixed offset 8145 * can be non-zero unless the caller requires otherwise. 8146 * var_off always must be 0 for PTR_TO_BTF_ID, hence we still 8147 * need to do checks instead of returning. 8148 */ 8149 return __check_ptr_off_reg(env, reg, argno, btf_id_fixed_off_ok); 8150 case PTR_TO_CTX: 8151 /* 8152 * Allow fixed and variable offsets for syscall context, but 8153 * only when the argument is passed as memory, not ctx, 8154 * otherwise we may get modified ctx in tail called programs and 8155 * global subprogs (that may act as extension prog hooks). 8156 */ 8157 if (arg_type != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog)) 8158 return 0; 8159 fallthrough; 8160 default: 8161 return __check_ptr_off_reg(env, reg, argno, false); 8162 } 8163 } 8164 8165 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8166 const struct bpf_reg_state *reg, argno_t argno, 8167 enum bpf_arg_type arg_type) 8168 { 8169 return __check_func_arg_reg_off(env, reg, argno, arg_type, true); 8170 } 8171 8172 static int check_arg_const_str(struct bpf_verifier_env *env, 8173 struct bpf_reg_state *reg, argno_t argno) 8174 { 8175 struct bpf_map *map = reg->map_ptr; 8176 int err; 8177 int map_off; 8178 u64 map_addr; 8179 char *str_ptr; 8180 8181 if (reg->type != PTR_TO_MAP_VALUE) 8182 return -EINVAL; 8183 8184 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 8185 verbose(env, "%s points to insn_array map which cannot be used as const string\n", 8186 reg_arg_name(env, argno)); 8187 return -EACCES; 8188 } 8189 8190 if (!bpf_map_is_rdonly(map)) { 8191 verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno)); 8192 return -EACCES; 8193 } 8194 8195 if (!tnum_is_const(reg->var_off)) { 8196 verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno)); 8197 return -EACCES; 8198 } 8199 8200 if (!map->ops->map_direct_value_addr) { 8201 verbose(env, "no direct value access support for this map type\n"); 8202 return -EACCES; 8203 } 8204 8205 err = check_map_access(env, reg, argno, 0, 8206 map->value_size - reg->var_off.value, false, 8207 ACCESS_HELPER); 8208 if (err) 8209 return err; 8210 8211 map_off = reg->var_off.value; 8212 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8213 if (err) { 8214 verbose(env, "direct value access on string failed\n"); 8215 return err; 8216 } 8217 8218 str_ptr = (char *)(long)(map_addr); 8219 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8220 verbose(env, "string is not zero-terminated\n"); 8221 return -EINVAL; 8222 } 8223 return 0; 8224 } 8225 8226 /* Returns constant key value in `value` if possible, else negative error */ 8227 static int get_constant_map_key(struct bpf_verifier_env *env, 8228 struct bpf_reg_state *key, 8229 u32 key_size, 8230 s64 *value) 8231 { 8232 struct bpf_func_state *state = bpf_func(env, key); 8233 struct bpf_reg_state *reg; 8234 int slot, spi, off; 8235 int spill_size = 0; 8236 int zero_size = 0; 8237 int stack_off; 8238 int i, err; 8239 u8 *stype; 8240 8241 if (!env->bpf_capable) 8242 return -EOPNOTSUPP; 8243 if (key->type != PTR_TO_STACK) 8244 return -EOPNOTSUPP; 8245 if (!tnum_is_const(key->var_off)) 8246 return -EOPNOTSUPP; 8247 8248 stack_off = key->var_off.value; 8249 slot = -stack_off - 1; 8250 spi = slot / BPF_REG_SIZE; 8251 off = slot % BPF_REG_SIZE; 8252 stype = state->stack[spi].slot_type; 8253 8254 /* First handle precisely tracked STACK_ZERO */ 8255 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) 8256 zero_size++; 8257 if (zero_size >= key_size) { 8258 *value = 0; 8259 return 0; 8260 } 8261 8262 /* Check that stack contains a scalar spill of expected size */ 8263 if (!bpf_is_spilled_scalar_reg(&state->stack[spi])) 8264 return -EOPNOTSUPP; 8265 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) 8266 spill_size++; 8267 if (spill_size != key_size) 8268 return -EOPNOTSUPP; 8269 8270 reg = &state->stack[spi].spilled_ptr; 8271 if (!tnum_is_const(reg->var_off)) 8272 /* Stack value not statically known */ 8273 return -EOPNOTSUPP; 8274 8275 /* We are relying on a constant value. So mark as precise 8276 * to prevent pruning on it. 8277 */ 8278 bpf_bt_set_frame_slot(&env->bt, key->frameno, spi); 8279 err = mark_chain_precision_batch(env, env->cur_state); 8280 if (err < 0) 8281 return err; 8282 8283 *value = reg->var_off.value; 8284 return 0; 8285 } 8286 8287 static bool can_elide_value_nullness(const struct bpf_map *map); 8288 8289 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8290 struct bpf_call_arg_meta *meta, 8291 const struct bpf_func_proto *fn, 8292 int insn_idx) 8293 { 8294 u32 regno = BPF_REG_1 + arg; 8295 struct bpf_reg_state *reg = reg_state(env, regno); 8296 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8297 argno_t argno = argno_from_reg(regno); 8298 enum bpf_reg_type type = reg->type; 8299 u32 *arg_btf_id = NULL; 8300 u32 key_size; 8301 int err = 0; 8302 8303 if (arg_type == ARG_DONTCARE) 8304 return 0; 8305 8306 err = check_reg_arg(env, regno, SRC_OP); 8307 if (err) 8308 return err; 8309 8310 if (arg_type == ARG_ANYTHING) { 8311 if (is_pointer_value(env, regno)) { 8312 verbose(env, "R%d leaks addr into helper function\n", 8313 regno); 8314 return -EACCES; 8315 } 8316 return 0; 8317 } 8318 8319 if (type_is_pkt_pointer(type) && 8320 !may_access_direct_pkt_data(env, fn, BPF_READ)) { 8321 verbose(env, "helper access to the packet is not allowed\n"); 8322 return -EACCES; 8323 } 8324 8325 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8326 err = resolve_map_arg_type(env, meta, &arg_type); 8327 if (err) 8328 return err; 8329 } 8330 8331 if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) 8332 /* A NULL register has a SCALAR_VALUE type, so skip 8333 * type checking. 8334 */ 8335 goto skip_type_check; 8336 8337 /* arg_btf_id and arg_size are in a union. */ 8338 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8339 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8340 arg_btf_id = fn->arg_btf_id[arg]; 8341 8342 err = check_reg_type(env, reg, argno, arg_type, arg_btf_id, meta); 8343 if (err) 8344 return err; 8345 8346 err = check_func_arg_reg_off(env, reg, argno, arg_type); 8347 if (err) 8348 return err; 8349 8350 skip_type_check: 8351 if (arg_type_is_release(arg_type) && !arg_type_is_dynptr(arg_type) && 8352 !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) { 8353 verbose(env, "release helper %s expects referenced PTR_TO_BTF_ID passed to %s\n", 8354 func_id_name(meta->func_id), reg_arg_name(env, argno)); 8355 return -EINVAL; 8356 } 8357 8358 if (reg_is_referenced(env, reg)) 8359 update_ref_obj(&meta->ref_obj, reg); 8360 8361 switch (base_type(arg_type)) { 8362 case ARG_CONST_MAP_PTR: 8363 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8364 if (meta->map.ptr) { 8365 /* Use map_uid (which is unique id of inner map) to reject: 8366 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8367 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8368 * if (inner_map1 && inner_map2) { 8369 * timer = bpf_map_lookup_elem(inner_map1); 8370 * if (timer) 8371 * // mismatch would have been allowed 8372 * bpf_timer_init(timer, inner_map2); 8373 * } 8374 * 8375 * Comparing map_ptr is enough to distinguish normal and outer maps. 8376 */ 8377 if (meta->map.ptr != reg->map_ptr || 8378 meta->map.uid != reg->map_uid) { 8379 verbose(env, 8380 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8381 meta->map.uid, reg->map_uid); 8382 return -EINVAL; 8383 } 8384 } 8385 meta->map.ptr = reg->map_ptr; 8386 meta->map.uid = reg->map_uid; 8387 break; 8388 case ARG_PTR_TO_MAP_KEY: 8389 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8390 * check that [key, key + map->key_size) are within 8391 * stack limits and initialized 8392 */ 8393 if (!meta->map.ptr) { 8394 /* in function declaration map_ptr must come before 8395 * map_key, so that it's verified and known before 8396 * we have to check map_key here. Otherwise it means 8397 * that kernel subsystem misconfigured verifier 8398 */ 8399 verifier_bug(env, "invalid map_ptr to access map->key"); 8400 return -EFAULT; 8401 } 8402 key_size = meta->map.ptr->key_size; 8403 err = check_helper_mem_access(env, reg, argno, key_size, BPF_READ, false, NULL); 8404 if (err) 8405 return err; 8406 if (can_elide_value_nullness(meta->map.ptr)) { 8407 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key); 8408 if (err < 0) { 8409 meta->const_map_key = -1; 8410 if (err == -EOPNOTSUPP) 8411 err = 0; 8412 else 8413 return err; 8414 } 8415 } 8416 break; 8417 case ARG_PTR_TO_MAP_VALUE: 8418 if (type_may_be_null(arg_type) && bpf_register_is_null(reg)) 8419 return 0; 8420 8421 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8422 * check [value, value + map->value_size) validity 8423 */ 8424 if (!meta->map.ptr) { 8425 /* kernel subsystem misconfigured verifier */ 8426 verifier_bug(env, "invalid map_ptr to access map->value"); 8427 return -EFAULT; 8428 } 8429 8430 /* 8431 * Disable raw mode for bpf_map_peek_elem() on a bloom filter. The helper reads 8432 * the value buffer as an input rather than filling it. 8433 */ 8434 if (meta->func_id == BPF_FUNC_map_peek_elem && 8435 meta->map.ptr->map_type == BPF_MAP_TYPE_BLOOM_FILTER) 8436 meta->arg_raw_mem.regno = 0; 8437 8438 err = check_helper_mem_access(env, reg, argno, meta->map.ptr->value_size, 8439 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8440 false, meta); 8441 break; 8442 case ARG_PTR_TO_PERCPU_BTF_ID: 8443 if (!reg->btf_id) { 8444 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8445 return -EACCES; 8446 } 8447 meta->ret_btf = reg->btf; 8448 meta->ret_btf_id = reg->btf_id; 8449 break; 8450 case ARG_PTR_TO_SPIN_LOCK: 8451 if (in_rbtree_lock_required_cb(env)) { 8452 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8453 return -EACCES; 8454 } 8455 if (meta->func_id == BPF_FUNC_spin_lock) { 8456 err = process_spin_lock(env, reg, argno, PROCESS_SPIN_LOCK); 8457 if (err) 8458 return err; 8459 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8460 err = process_spin_lock(env, reg, argno, 0); 8461 if (err) 8462 return err; 8463 } else { 8464 verifier_bug(env, "spin lock arg on unexpected helper"); 8465 return -EFAULT; 8466 } 8467 break; 8468 case ARG_PTR_TO_TIMER: 8469 err = process_timer_helper(env, reg, argno, meta); 8470 if (err) 8471 return err; 8472 break; 8473 case ARG_PTR_TO_FUNC: 8474 meta->subprogno = reg->subprogno; 8475 break; 8476 case ARG_PTR_TO_MEM: 8477 /* The access to this pointer is only checked when we hit the 8478 * next is_mem_size argument below. 8479 */ 8480 if (arg_type & MEM_FIXED_SIZE) { 8481 err = check_helper_mem_access(env, reg, argno, fn->arg_size[arg], 8482 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8483 false, meta); 8484 if (err) 8485 return err; 8486 if (arg_type & MEM_ALIGNED) 8487 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 8488 } 8489 break; 8490 case ARG_CONST_SIZE: 8491 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, 8492 argno_from_reg(regno - 1), argno, 8493 fn->arg_type[arg - 1] & MEM_WRITE ? BPF_WRITE : BPF_READ, 8494 false, meta); 8495 break; 8496 case ARG_CONST_SIZE_OR_ZERO: 8497 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, 8498 argno_from_reg(regno - 1), argno, 8499 fn->arg_type[arg - 1] & MEM_WRITE ? BPF_WRITE : BPF_READ, 8500 true, meta); 8501 break; 8502 case ARG_PTR_TO_DYNPTR: 8503 err = process_dynptr_func(env, reg, argno, insn_idx, arg_type, &meta->ref_obj, 8504 &meta->dynptr); 8505 if (err) 8506 return err; 8507 break; 8508 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8509 err = process_const_alloc_mem_size(env, reg, argno, &meta->ret_mem); 8510 if (err) 8511 return err; 8512 break; 8513 case ARG_PTR_TO_CONST_STR: 8514 { 8515 err = check_arg_const_str(env, reg, argno); 8516 if (err) 8517 return err; 8518 break; 8519 } 8520 case ARG_KPTR_XCHG_DEST: 8521 err = process_kptr_func(env, regno, meta); 8522 if (err) 8523 return err; 8524 break; 8525 } 8526 8527 return err; 8528 } 8529 8530 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8531 { 8532 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8533 enum bpf_prog_type type = resolve_prog_type(env->prog); 8534 8535 if (func_id != BPF_FUNC_map_update_elem && 8536 func_id != BPF_FUNC_map_delete_elem) 8537 return false; 8538 8539 /* It's not possible to get access to a locked struct sock in these 8540 * contexts, so updating is safe. 8541 */ 8542 switch (type) { 8543 case BPF_PROG_TYPE_TRACING: 8544 if (eatype == BPF_TRACE_ITER) 8545 return true; 8546 break; 8547 case BPF_PROG_TYPE_SOCK_OPS: 8548 /* map_update allowed only via dedicated helpers with event type checks */ 8549 if (func_id == BPF_FUNC_map_delete_elem) 8550 return true; 8551 break; 8552 case BPF_PROG_TYPE_SK_REUSEPORT: 8553 case BPF_PROG_TYPE_SK_LOOKUP: 8554 return true; 8555 default: 8556 break; 8557 } 8558 8559 verbose(env, "cannot update sockmap in this context\n"); 8560 return false; 8561 } 8562 8563 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8564 { 8565 return env->prog->jit_requested && 8566 bpf_jit_supports_subprog_tailcalls(); 8567 } 8568 8569 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8570 struct bpf_map *map, int func_id) 8571 { 8572 if (!map) 8573 return 0; 8574 8575 /* We need a two way check, first is from map perspective ... */ 8576 switch (map->map_type) { 8577 case BPF_MAP_TYPE_PROG_ARRAY: 8578 if (func_id != BPF_FUNC_tail_call) 8579 goto error; 8580 break; 8581 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8582 if (func_id != BPF_FUNC_perf_event_read && 8583 func_id != BPF_FUNC_perf_event_output && 8584 func_id != BPF_FUNC_skb_output && 8585 func_id != BPF_FUNC_perf_event_read_value && 8586 func_id != BPF_FUNC_xdp_output) 8587 goto error; 8588 break; 8589 case BPF_MAP_TYPE_RINGBUF: 8590 if (func_id != BPF_FUNC_ringbuf_output && 8591 func_id != BPF_FUNC_ringbuf_reserve && 8592 func_id != BPF_FUNC_ringbuf_query && 8593 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8594 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8595 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8596 goto error; 8597 break; 8598 case BPF_MAP_TYPE_USER_RINGBUF: 8599 if (func_id != BPF_FUNC_user_ringbuf_drain) 8600 goto error; 8601 break; 8602 case BPF_MAP_TYPE_STACK_TRACE: 8603 if (func_id != BPF_FUNC_get_stackid) 8604 goto error; 8605 break; 8606 case BPF_MAP_TYPE_CGROUP_ARRAY: 8607 if (func_id != BPF_FUNC_skb_under_cgroup && 8608 func_id != BPF_FUNC_current_task_under_cgroup) 8609 goto error; 8610 break; 8611 case BPF_MAP_TYPE_CGROUP_STORAGE: 8612 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8613 if (func_id != BPF_FUNC_get_local_storage) 8614 goto error; 8615 break; 8616 case BPF_MAP_TYPE_DEVMAP: 8617 case BPF_MAP_TYPE_DEVMAP_HASH: 8618 if (func_id != BPF_FUNC_redirect_map && 8619 func_id != BPF_FUNC_map_lookup_elem) 8620 goto error; 8621 break; 8622 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8623 * appear. 8624 */ 8625 case BPF_MAP_TYPE_CPUMAP: 8626 if (func_id != BPF_FUNC_redirect_map) 8627 goto error; 8628 break; 8629 case BPF_MAP_TYPE_XSKMAP: 8630 if (func_id != BPF_FUNC_redirect_map && 8631 func_id != BPF_FUNC_map_lookup_elem) 8632 goto error; 8633 break; 8634 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8635 case BPF_MAP_TYPE_HASH_OF_MAPS: 8636 if (func_id != BPF_FUNC_map_lookup_elem) 8637 goto error; 8638 break; 8639 case BPF_MAP_TYPE_SOCKMAP: 8640 if (func_id != BPF_FUNC_sk_redirect_map && 8641 func_id != BPF_FUNC_sock_map_update && 8642 func_id != BPF_FUNC_msg_redirect_map && 8643 func_id != BPF_FUNC_sk_select_reuseport && 8644 func_id != BPF_FUNC_map_lookup_elem && 8645 !may_update_sockmap(env, func_id)) 8646 goto error; 8647 break; 8648 case BPF_MAP_TYPE_SOCKHASH: 8649 if (func_id != BPF_FUNC_sk_redirect_hash && 8650 func_id != BPF_FUNC_sock_hash_update && 8651 func_id != BPF_FUNC_msg_redirect_hash && 8652 func_id != BPF_FUNC_sk_select_reuseport && 8653 func_id != BPF_FUNC_map_lookup_elem && 8654 !may_update_sockmap(env, func_id)) 8655 goto error; 8656 break; 8657 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8658 if (func_id != BPF_FUNC_sk_select_reuseport) 8659 goto error; 8660 break; 8661 case BPF_MAP_TYPE_QUEUE: 8662 case BPF_MAP_TYPE_STACK: 8663 if (func_id != BPF_FUNC_map_peek_elem && 8664 func_id != BPF_FUNC_map_pop_elem && 8665 func_id != BPF_FUNC_map_push_elem) 8666 goto error; 8667 break; 8668 case BPF_MAP_TYPE_SK_STORAGE: 8669 if (func_id != BPF_FUNC_sk_storage_get && 8670 func_id != BPF_FUNC_sk_storage_delete && 8671 func_id != BPF_FUNC_kptr_xchg) 8672 goto error; 8673 break; 8674 case BPF_MAP_TYPE_INODE_STORAGE: 8675 if (func_id != BPF_FUNC_inode_storage_get && 8676 func_id != BPF_FUNC_inode_storage_delete && 8677 func_id != BPF_FUNC_kptr_xchg) 8678 goto error; 8679 break; 8680 case BPF_MAP_TYPE_TASK_STORAGE: 8681 if (func_id != BPF_FUNC_task_storage_get && 8682 func_id != BPF_FUNC_task_storage_delete && 8683 func_id != BPF_FUNC_kptr_xchg) 8684 goto error; 8685 break; 8686 case BPF_MAP_TYPE_CGRP_STORAGE: 8687 if (func_id != BPF_FUNC_cgrp_storage_get && 8688 func_id != BPF_FUNC_cgrp_storage_delete && 8689 func_id != BPF_FUNC_kptr_xchg) 8690 goto error; 8691 break; 8692 case BPF_MAP_TYPE_BLOOM_FILTER: 8693 if (func_id != BPF_FUNC_map_peek_elem && 8694 func_id != BPF_FUNC_map_push_elem) 8695 goto error; 8696 break; 8697 case BPF_MAP_TYPE_INSN_ARRAY: 8698 goto error; 8699 default: 8700 break; 8701 } 8702 8703 /* ... and second from the function itself. */ 8704 switch (func_id) { 8705 case BPF_FUNC_tail_call: 8706 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8707 goto error; 8708 if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) { 8709 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n"); 8710 return -EINVAL; 8711 } 8712 break; 8713 case BPF_FUNC_perf_event_read: 8714 case BPF_FUNC_perf_event_output: 8715 case BPF_FUNC_perf_event_read_value: 8716 case BPF_FUNC_skb_output: 8717 case BPF_FUNC_xdp_output: 8718 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8719 goto error; 8720 break; 8721 case BPF_FUNC_ringbuf_output: 8722 case BPF_FUNC_ringbuf_reserve: 8723 case BPF_FUNC_ringbuf_query: 8724 case BPF_FUNC_ringbuf_reserve_dynptr: 8725 case BPF_FUNC_ringbuf_submit_dynptr: 8726 case BPF_FUNC_ringbuf_discard_dynptr: 8727 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8728 goto error; 8729 break; 8730 case BPF_FUNC_user_ringbuf_drain: 8731 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8732 goto error; 8733 break; 8734 case BPF_FUNC_get_stackid: 8735 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8736 goto error; 8737 break; 8738 case BPF_FUNC_current_task_under_cgroup: 8739 case BPF_FUNC_skb_under_cgroup: 8740 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8741 goto error; 8742 break; 8743 case BPF_FUNC_redirect_map: 8744 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8745 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8746 map->map_type != BPF_MAP_TYPE_CPUMAP && 8747 map->map_type != BPF_MAP_TYPE_XSKMAP) 8748 goto error; 8749 break; 8750 case BPF_FUNC_sk_redirect_map: 8751 case BPF_FUNC_msg_redirect_map: 8752 case BPF_FUNC_sock_map_update: 8753 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8754 goto error; 8755 break; 8756 case BPF_FUNC_sk_redirect_hash: 8757 case BPF_FUNC_msg_redirect_hash: 8758 case BPF_FUNC_sock_hash_update: 8759 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8760 goto error; 8761 break; 8762 case BPF_FUNC_get_local_storage: 8763 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8764 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8765 goto error; 8766 break; 8767 case BPF_FUNC_sk_select_reuseport: 8768 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8769 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8770 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8771 goto error; 8772 break; 8773 case BPF_FUNC_map_pop_elem: 8774 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8775 map->map_type != BPF_MAP_TYPE_STACK) 8776 goto error; 8777 break; 8778 case BPF_FUNC_map_peek_elem: 8779 case BPF_FUNC_map_push_elem: 8780 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8781 map->map_type != BPF_MAP_TYPE_STACK && 8782 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8783 goto error; 8784 break; 8785 case BPF_FUNC_map_lookup_percpu_elem: 8786 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8787 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8788 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8789 goto error; 8790 break; 8791 case BPF_FUNC_sk_storage_get: 8792 case BPF_FUNC_sk_storage_delete: 8793 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8794 goto error; 8795 break; 8796 case BPF_FUNC_inode_storage_get: 8797 case BPF_FUNC_inode_storage_delete: 8798 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8799 goto error; 8800 break; 8801 case BPF_FUNC_task_storage_get: 8802 case BPF_FUNC_task_storage_delete: 8803 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8804 goto error; 8805 break; 8806 case BPF_FUNC_cgrp_storage_get: 8807 case BPF_FUNC_cgrp_storage_delete: 8808 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8809 goto error; 8810 break; 8811 default: 8812 break; 8813 } 8814 8815 return 0; 8816 error: 8817 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8818 map->map_type, func_id_name(func_id), func_id); 8819 return -EINVAL; 8820 } 8821 8822 static bool check_raw_mode_ok(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8823 { 8824 int i; 8825 8826 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8827 if (!arg_type_is_raw_mem(fn->arg_type[i])) 8828 continue; 8829 if (meta->arg_raw_mem.regno) 8830 return false; 8831 meta->arg_raw_mem.regno = i + 1; 8832 } 8833 8834 return true; 8835 } 8836 8837 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8838 { 8839 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8840 bool has_size = fn->arg_size[arg] != 0; 8841 bool is_next_size = false; 8842 8843 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8844 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8845 8846 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8847 return is_next_size; 8848 8849 return has_size == is_next_size || is_next_size == is_fixed; 8850 } 8851 8852 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8853 { 8854 /* bpf_xxx(..., buf, len) call will access 'len' 8855 * bytes from memory 'buf'. Both arg types need 8856 * to be paired, so make sure there's no buggy 8857 * helper function specification. 8858 */ 8859 if (arg_type_is_mem_size(fn->arg1_type) || 8860 check_args_pair_invalid(fn, 0) || 8861 check_args_pair_invalid(fn, 1) || 8862 check_args_pair_invalid(fn, 2) || 8863 check_args_pair_invalid(fn, 3) || 8864 check_args_pair_invalid(fn, 4)) 8865 return false; 8866 8867 return true; 8868 } 8869 8870 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8871 { 8872 int i; 8873 8874 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8875 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8876 return !!fn->arg_btf_id[i]; 8877 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8878 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8879 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8880 /* arg_btf_id and arg_size are in a union. */ 8881 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8882 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8883 return false; 8884 } 8885 8886 return true; 8887 } 8888 8889 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn) 8890 { 8891 int i; 8892 8893 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8894 enum bpf_arg_type arg_type = fn->arg_type[i]; 8895 8896 if (base_type(arg_type) != ARG_PTR_TO_MEM) 8897 continue; 8898 if (!(arg_type & (MEM_WRITE | MEM_RDONLY))) 8899 return false; 8900 } 8901 8902 return true; 8903 } 8904 8905 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8906 { 8907 int i; 8908 8909 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8910 enum bpf_arg_type arg_type = fn->arg_type[i]; 8911 8912 if (arg_type_is_release(arg_type)) { 8913 if (meta->release_regno) 8914 return false; 8915 meta->release_regno = i + 1; 8916 } 8917 } 8918 8919 return true; 8920 } 8921 8922 static int check_func_proto(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8923 { 8924 return check_raw_mode_ok(fn, meta) && 8925 check_arg_pair_ok(fn) && 8926 check_mem_arg_rw_flag_ok(fn) && 8927 check_proto_release_reg(fn, meta) && 8928 check_btf_id_ok(fn) ? 0 : -EINVAL; 8929 } 8930 8931 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8932 * are now invalid, so turn them into unknown SCALAR_VALUE. 8933 * 8934 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8935 * since these slices point to packet data. 8936 */ 8937 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8938 { 8939 struct bpf_func_state *state; 8940 struct bpf_reg_state *reg; 8941 8942 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8943 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8944 mark_reg_invalid(env, reg); 8945 })); 8946 } 8947 8948 enum { 8949 AT_PKT_END = -1, 8950 BEYOND_PKT_END = -2, 8951 }; 8952 8953 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8954 { 8955 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8956 struct bpf_reg_state *reg = &state->regs[regn]; 8957 8958 if (reg->type != PTR_TO_PACKET) 8959 /* PTR_TO_PACKET_META is not supported yet */ 8960 return; 8961 8962 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8963 * How far beyond pkt_end it goes is unknown. 8964 * if (!range_open) it's the case of pkt >= pkt_end 8965 * if (range_open) it's the case of pkt > pkt_end 8966 * hence this pointer is at least 1 byte bigger than pkt_end 8967 */ 8968 if (range_open) 8969 reg->range = BEYOND_PKT_END; 8970 else 8971 reg->range = AT_PKT_END; 8972 } 8973 8974 static int release_reference_nomark(struct bpf_verifier_state *state, int id) 8975 { 8976 int i; 8977 8978 for (i = 0; i < state->acquired_refs; i++) { 8979 if (state->refs[i].type != REF_TYPE_PTR) 8980 continue; 8981 if (state->refs[i].id == id) { 8982 release_reference_state(state, i); 8983 return 0; 8984 } 8985 } 8986 return -EINVAL; 8987 } 8988 8989 static int idstack_push(struct bpf_idmap *idmap, u32 id) 8990 { 8991 int i; 8992 8993 if (!id) 8994 return 0; 8995 8996 for (i = 0; i < idmap->cnt; i++) 8997 if (idmap->map[i].old == id) 8998 return 0; 8999 9000 if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE)) 9001 return -EFAULT; 9002 9003 idmap->map[idmap->cnt++].old = id; 9004 return 0; 9005 } 9006 9007 static int idstack_pop(struct bpf_idmap *idmap) 9008 { 9009 if (!idmap->cnt) 9010 return 0; 9011 9012 return idmap->map[--idmap->cnt].old; 9013 } 9014 9015 /* Release id and objects derived from it iteratively in a DFS manner */ 9016 static int release_reference(struct bpf_verifier_env *env, int id) 9017 { 9018 u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR); 9019 struct bpf_verifier_state *vstate = env->cur_state; 9020 struct bpf_idmap *idstack = &env->idmap_scratch; 9021 struct bpf_stack_state *stack; 9022 struct bpf_func_state *state; 9023 struct bpf_reg_state *reg; 9024 int i, err; 9025 9026 idstack->cnt = 0; 9027 err = idstack_push(idstack, id); 9028 if (err) 9029 return err; 9030 9031 if (find_reference_state(vstate, id)) 9032 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 9033 9034 while ((id = idstack_pop(idstack))) { 9035 /* 9036 * Child references are inaccessible after parent is released, 9037 * any child references that exist at this point are a leak. 9038 */ 9039 for (i = 0; i < vstate->acquired_refs; i++) { 9040 if (vstate->refs[i].type != REF_TYPE_PTR) 9041 continue; 9042 if (vstate->refs[i].parent_id != id) 9043 continue; 9044 verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n", 9045 vstate->refs[i].id, vstate->refs[i].insn_idx); 9046 return -EINVAL; 9047 } 9048 9049 bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({ 9050 if (reg->id != id && reg->parent_id != id) 9051 continue; 9052 9053 /* Free objects derived from the current object */ 9054 if (reg->parent_id == id) { 9055 err = idstack_push(idstack, reg->id); 9056 if (err) 9057 return err; 9058 } 9059 9060 if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL) 9061 mark_reg_invalid(env, reg); 9062 else if (stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR) 9063 invalidate_dynptr(env, stack); 9064 })); 9065 } 9066 9067 return 0; 9068 } 9069 9070 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9071 { 9072 struct bpf_func_state *unused; 9073 struct bpf_reg_state *reg; 9074 9075 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9076 if (type_is_non_owning_ref(reg->type)) 9077 mark_reg_invalid(env, reg); 9078 })); 9079 } 9080 9081 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env) 9082 { 9083 struct bpf_stack_state *stack; 9084 struct bpf_func_state *state; 9085 struct bpf_reg_state *reg; 9086 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 9087 9088 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({ 9089 if (reg->type & MEM_RCU) { 9090 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 9091 reg->type |= PTR_UNTRUSTED; 9092 } 9093 })); 9094 } 9095 9096 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id) 9097 { 9098 struct bpf_func_state *state; 9099 struct bpf_reg_state *reg; 9100 int err; 9101 9102 err = release_reference_nomark(env->cur_state, id); 9103 9104 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9105 if (reg->id != id) 9106 continue; 9107 if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 9108 reg->id = 0; 9109 reg->type &= ~MEM_ALLOC; 9110 reg->type |= MEM_RCU; 9111 } 9112 })); 9113 9114 return err; 9115 } 9116 9117 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9118 struct bpf_reg_state *regs) 9119 { 9120 int i; 9121 9122 /* after the call registers r0 - r5 were scratched */ 9123 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9124 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 9125 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9126 } 9127 } 9128 9129 static void invalidate_outgoing_stack_args(const struct bpf_verifier_env *env, 9130 struct bpf_func_state *state) 9131 { 9132 int i, nslots = state->out_stack_arg_cnt; 9133 9134 for (i = 0; i < nslots; i++) 9135 bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]); 9136 } 9137 9138 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9139 struct bpf_func_state *caller, 9140 struct bpf_func_state *callee, 9141 int insn_idx); 9142 9143 static int set_callee_state(struct bpf_verifier_env *env, 9144 struct bpf_func_state *caller, 9145 struct bpf_func_state *callee, int insn_idx); 9146 9147 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9148 set_callee_state_fn set_callee_state_cb, 9149 struct bpf_verifier_state *state) 9150 { 9151 struct bpf_func_state *caller, *callee; 9152 int err; 9153 9154 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9155 verbose(env, "the call stack of %d frames is too deep\n", 9156 state->curframe + 2); 9157 return -E2BIG; 9158 } 9159 9160 if (state->frame[state->curframe + 1]) { 9161 verifier_bug(env, "Frame %d already allocated", state->curframe + 1); 9162 return -EFAULT; 9163 } 9164 9165 caller = state->frame[state->curframe]; 9166 callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT); 9167 if (!callee) 9168 return -ENOMEM; 9169 state->frame[state->curframe + 1] = callee; 9170 9171 /* callee cannot access r0, r6 - r9 for reading and has to write 9172 * into its own stack before reading from it. 9173 * callee can read/write into caller's stack 9174 */ 9175 init_func_state(env, callee, 9176 /* remember the callsite, it will be used by bpf_exit */ 9177 callsite, 9178 state->curframe + 1 /* frameno within this callchain */, 9179 subprog /* subprog number within this prog */); 9180 err = set_callee_state_cb(env, caller, callee, callsite); 9181 if (err) 9182 goto err_out; 9183 9184 /* only increment it after check_reg_arg() finished */ 9185 state->curframe++; 9186 9187 return 0; 9188 9189 err_out: 9190 free_func_state(callee); 9191 state->frame[state->curframe + 1] = NULL; 9192 return err; 9193 } 9194 9195 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9196 const struct btf *btf, 9197 struct bpf_reg_state *regs) 9198 { 9199 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9200 struct bpf_func_state *caller = cur_func(env); 9201 struct bpf_verifier_log *log = &env->log; 9202 struct ref_obj_desc ref_obj = {}; 9203 u32 i; 9204 int ret, err; 9205 9206 ret = btf_prepare_func_args(env, subprog); 9207 if (ret) { 9208 if (bpf_in_stack_arg_cnt(sub) > 0) { 9209 err = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9210 if (err) 9211 return err; 9212 } 9213 return ret; 9214 } 9215 9216 ret = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9217 if (ret) 9218 return ret; 9219 9220 /* check that BTF function arguments match actual types that the 9221 * verifier sees. 9222 */ 9223 for (i = 0; i < sub->arg_cnt; i++) { 9224 argno_t argno = argno_from_arg(i + 1); 9225 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 9226 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9227 9228 if (arg->arg_type == ARG_ANYTHING) { 9229 if (reg->type != SCALAR_VALUE) { 9230 bpf_log(log, "%s is not a scalar\n", reg_arg_name(env, argno)); 9231 return -EINVAL; 9232 } 9233 } else if (arg->arg_type & PTR_UNTRUSTED) { 9234 /* 9235 * Anything is allowed for untrusted arguments, as these are 9236 * read-only and probe read instructions would protect against 9237 * invalid memory access. 9238 */ 9239 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9240 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_CTX); 9241 if (ret < 0) 9242 return ret; 9243 /* If function expects ctx type in BTF check that caller 9244 * is passing PTR_TO_CTX. 9245 */ 9246 if (reg->type != PTR_TO_CTX) { 9247 bpf_log(log, "%s expects pointer to ctx\n", 9248 reg_arg_name(env, argno)); 9249 return -EINVAL; 9250 } 9251 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9252 ret = check_func_arg_reg_off(env, reg, argno, ARG_DONTCARE); 9253 if (ret < 0) 9254 return ret; 9255 if (check_mem_reg(env, reg, argno, arg->mem_size)) 9256 return -EINVAL; 9257 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9258 bpf_log(log, "%s is expected to be non-NULL\n", 9259 reg_arg_name(env, argno)); 9260 return -EINVAL; 9261 } 9262 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9263 /* 9264 * Can pass any value and the kernel won't crash, but 9265 * only PTR_TO_ARENA or SCALAR make sense. Everything 9266 * else is a bug in the bpf program. Point it out to 9267 * the user at the verification time instead of 9268 * run-time debug nightmare. 9269 */ 9270 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9271 bpf_log(log, "%s is not a pointer to arena or scalar.\n", 9272 reg_arg_name(env, argno)); 9273 return -EINVAL; 9274 } 9275 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 9276 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_DYNPTR); 9277 if (ret) 9278 return ret; 9279 9280 ret = process_dynptr_func(env, reg, argno, -1, arg->arg_type, &ref_obj, NULL); 9281 if (ret) 9282 return ret; 9283 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9284 struct bpf_call_arg_meta meta; 9285 int err; 9286 9287 if (bpf_register_is_null(reg) && type_may_be_null(arg->arg_type)) 9288 continue; 9289 9290 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9291 err = check_reg_type(env, reg, argno, arg->arg_type, &arg->btf_id, &meta); 9292 err = err ?: check_func_arg_reg_off(env, reg, argno, arg->arg_type); 9293 if (err) 9294 return err; 9295 } else { 9296 verifier_bug(env, "unrecognized %s type %d", 9297 reg_arg_name(env, argno), arg->arg_type); 9298 return -EFAULT; 9299 } 9300 } 9301 9302 return 0; 9303 } 9304 9305 /* Compare BTF of a function call with given bpf_reg_state. 9306 * Returns: 9307 * EFAULT - there is a verifier bug. Abort verification. 9308 * EINVAL - there is a type mismatch or BTF is not available. 9309 * 0 - BTF matches with what bpf_reg_state expects. 9310 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9311 */ 9312 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9313 struct bpf_reg_state *regs) 9314 { 9315 struct bpf_prog *prog = env->prog; 9316 struct btf *btf = prog->aux->btf; 9317 u32 btf_id; 9318 int err; 9319 9320 if (!prog->aux->func_info) 9321 return -EINVAL; 9322 9323 btf_id = prog->aux->func_info[subprog].type_id; 9324 if (!btf_id) 9325 return -EFAULT; 9326 9327 if (prog->aux->func_info_aux[subprog].unreliable) 9328 return -EINVAL; 9329 9330 err = btf_check_func_arg_match(env, subprog, btf, regs); 9331 /* Compiler optimizations can remove arguments from static functions 9332 * or mismatched type can be passed into a global function. 9333 * In such cases mark the function as unreliable from BTF point of view. 9334 */ 9335 if (err) 9336 prog->aux->func_info_aux[subprog].unreliable = true; 9337 return err; 9338 } 9339 9340 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9341 int insn_idx, int subprog, 9342 set_callee_state_fn set_callee_state_cb) 9343 { 9344 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9345 struct bpf_func_state *caller, *callee; 9346 int err; 9347 9348 caller = state->frame[state->curframe]; 9349 err = btf_check_subprog_call(env, subprog, caller->regs); 9350 if (err == -EFAULT) 9351 return err; 9352 9353 /* set_callee_state is used for direct subprog calls, but we are 9354 * interested in validating only BPF helpers that can call subprogs as 9355 * callbacks 9356 */ 9357 env->subprog_info[subprog].is_cb = true; 9358 if (bpf_pseudo_kfunc_call(insn) && 9359 !is_callback_calling_kfunc(insn->imm)) { 9360 verifier_bug(env, "kfunc %s#%d not marked as callback-calling", 9361 func_id_name(insn->imm), insn->imm); 9362 return -EFAULT; 9363 } else if (!bpf_pseudo_kfunc_call(insn) && 9364 !is_callback_calling_function(insn->imm)) { /* helper */ 9365 verifier_bug(env, "helper %s#%d not marked as callback-calling", 9366 func_id_name(insn->imm), insn->imm); 9367 return -EFAULT; 9368 } 9369 9370 if (bpf_is_async_callback_calling_insn(insn)) { 9371 struct bpf_verifier_state *async_cb; 9372 9373 /* there is no real recursion here. timer and workqueue callbacks are async */ 9374 env->subprog_info[subprog].is_async_cb = true; 9375 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9376 insn_idx, subprog, 9377 is_async_cb_sleepable(env, insn)); 9378 if (IS_ERR(async_cb)) 9379 return PTR_ERR(async_cb); 9380 callee = async_cb->frame[0]; 9381 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9382 9383 /* Convert bpf_timer_set_callback() args into timer callback args */ 9384 err = set_callee_state_cb(env, caller, callee, insn_idx); 9385 if (err) 9386 return err; 9387 9388 return 0; 9389 } 9390 9391 /* for callback functions enqueue entry to callback and 9392 * proceed with next instruction within current frame. 9393 */ 9394 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9395 if (IS_ERR(callback_state)) 9396 return PTR_ERR(callback_state); 9397 9398 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9399 callback_state); 9400 if (err) 9401 return err; 9402 9403 callback_state->callback_unroll_depth++; 9404 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9405 caller->callback_depth = 0; 9406 return 0; 9407 } 9408 9409 static int process_bpf_exit_full(struct bpf_verifier_env *env, 9410 bool *do_print_state, bool exception_exit); 9411 9412 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9413 int *insn_idx) 9414 { 9415 struct bpf_verifier_state *state = env->cur_state; 9416 struct bpf_subprog_info *caller_info; 9417 u16 callee_incoming, stack_arg_cnt; 9418 struct bpf_func_state *caller; 9419 int err, subprog, target_insn; 9420 9421 target_insn = *insn_idx + insn->imm + 1; 9422 subprog = bpf_find_subprog(env, target_insn); 9423 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program", 9424 target_insn)) 9425 return -EFAULT; 9426 9427 caller = state->frame[state->curframe]; 9428 err = btf_check_subprog_call(env, subprog, caller->regs); 9429 if (err == -EFAULT) 9430 return err; 9431 if (bpf_subprog_is_global(env, subprog)) { 9432 const char *sub_name = subprog_name(env, subprog); 9433 9434 if (env->cur_state->active_locks) { 9435 verbose(env, "global function calls are not allowed while holding a lock,\n" 9436 "use static function instead\n"); 9437 return -EINVAL; 9438 } 9439 9440 if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) { 9441 verbose(env, "sleepable global function %s() called in %s\n", 9442 sub_name, non_sleepable_context_description(env)); 9443 return -EINVAL; 9444 } 9445 9446 if (err) { 9447 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9448 subprog, sub_name); 9449 return err; 9450 } 9451 9452 if (env->log.level & BPF_LOG_LEVEL) 9453 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9454 subprog, sub_name); 9455 if (env->subprog_info[subprog].changes_pkt_data) 9456 clear_all_pkt_pointers(env); 9457 /* mark global subprog for verifying after main prog */ 9458 subprog_aux(env, subprog)->called = true; 9459 clear_caller_saved_regs(env, caller->regs); 9460 invalidate_outgoing_stack_args(env, cur_func(env)); 9461 9462 /* All non-void global functions return a 64-bit SCALAR_VALUE. */ 9463 if (!subprog_returns_void(env, subprog)) { 9464 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9465 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9466 } 9467 9468 if (env->subprog_info[subprog].might_throw) { 9469 struct bpf_verifier_state *branch; 9470 9471 branch = push_stack(env, *insn_idx + 1, *insn_idx, false); 9472 if (IS_ERR(branch)) { 9473 verbose(env, "failed to push state for global subprog exception path\n"); 9474 return PTR_ERR(branch); 9475 } 9476 return process_bpf_exit_full(env, NULL, true); 9477 } 9478 9479 /* continue with next insn after call */ 9480 return 0; 9481 } 9482 9483 /* 9484 * Track caller's total stack arg count (incoming + max outgoing). 9485 * This is needed so the JIT knows how much stack arg space to allocate. 9486 */ 9487 caller_info = &env->subprog_info[caller->subprogno]; 9488 callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]); 9489 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming; 9490 if (stack_arg_cnt > caller_info->stack_arg_cnt) 9491 caller_info->stack_arg_cnt = stack_arg_cnt; 9492 9493 /* for regular function entry setup new frame and continue 9494 * from that frame. 9495 */ 9496 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9497 if (err) 9498 return err; 9499 9500 clear_caller_saved_regs(env, caller->regs); 9501 9502 /* and go analyze first insn of the callee */ 9503 *insn_idx = env->subprog_info[subprog].start - 1; 9504 9505 if (env->log.level & BPF_LOG_LEVEL) { 9506 verbose(env, "caller:\n"); 9507 print_verifier_state(env, state, caller->frameno, true); 9508 verbose(env, "callee:\n"); 9509 print_verifier_state(env, state, state->curframe, true); 9510 } 9511 9512 return 0; 9513 } 9514 9515 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9516 struct bpf_func_state *caller, 9517 struct bpf_func_state *callee) 9518 { 9519 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9520 * void *callback_ctx, u64 flags); 9521 * callback_fn(struct bpf_map *map, void *key, void *value, 9522 * void *callback_ctx); 9523 */ 9524 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9525 9526 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9527 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9528 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9529 9530 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9531 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9532 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9533 9534 /* pointer to stack or null */ 9535 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9536 9537 /* unused */ 9538 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9539 return 0; 9540 } 9541 9542 static int set_callee_state(struct bpf_verifier_env *env, 9543 struct bpf_func_state *caller, 9544 struct bpf_func_state *callee, int insn_idx) 9545 { 9546 int i; 9547 9548 /* copy r1 - r5 args that callee can access. The copy includes parent 9549 * pointers, which connects us up to the liveness chain 9550 */ 9551 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9552 callee->regs[i] = caller->regs[i]; 9553 return 0; 9554 } 9555 9556 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9557 struct bpf_func_state *caller, 9558 struct bpf_func_state *callee, 9559 int insn_idx) 9560 { 9561 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9562 struct bpf_map *map; 9563 int err; 9564 9565 /* valid map_ptr and poison value does not matter */ 9566 map = insn_aux->map_ptr_state.map_ptr; 9567 if (!map->ops->map_set_for_each_callback_args || 9568 !map->ops->map_for_each_callback) { 9569 verbose(env, "callback function not allowed for map\n"); 9570 return -ENOTSUPP; 9571 } 9572 9573 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9574 if (err) 9575 return err; 9576 9577 callee->in_callback_fn = true; 9578 callee->callback_ret_range = retval_range(0, 1); 9579 return 0; 9580 } 9581 9582 static int set_loop_callback_state(struct bpf_verifier_env *env, 9583 struct bpf_func_state *caller, 9584 struct bpf_func_state *callee, 9585 int insn_idx) 9586 { 9587 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9588 * u64 flags); 9589 * callback_fn(u64 index, void *callback_ctx); 9590 */ 9591 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9592 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9593 9594 /* unused */ 9595 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9596 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9597 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9598 9599 callee->in_callback_fn = true; 9600 callee->callback_ret_range = retval_range(0, 1); 9601 return 0; 9602 } 9603 9604 static int set_timer_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 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9610 9611 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9612 * callback_fn(struct bpf_map *map, void *key, void *value); 9613 */ 9614 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9615 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9616 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9617 9618 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9619 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9620 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9621 9622 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9623 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9624 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9625 9626 /* unused */ 9627 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9628 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9629 callee->in_async_callback_fn = true; 9630 callee->callback_ret_range = retval_range(0, 0); 9631 return 0; 9632 } 9633 9634 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9635 struct bpf_func_state *caller, 9636 struct bpf_func_state *callee, 9637 int insn_idx) 9638 { 9639 /* bpf_find_vma(struct task_struct *task, u64 addr, 9640 * void *callback_fn, void *callback_ctx, u64 flags) 9641 * (callback_fn)(struct task_struct *task, 9642 * struct vm_area_struct *vma, void *callback_ctx); 9643 */ 9644 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9645 9646 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9647 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9648 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9649 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9650 9651 /* pointer to stack or null */ 9652 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9653 9654 /* unused */ 9655 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9656 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9657 callee->in_callback_fn = true; 9658 callee->callback_ret_range = retval_range(0, 1); 9659 return 0; 9660 } 9661 9662 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9663 struct bpf_func_state *caller, 9664 struct bpf_func_state *callee, 9665 int insn_idx) 9666 { 9667 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9668 * callback_ctx, u64 flags); 9669 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9670 */ 9671 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9672 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9673 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9674 9675 /* unused */ 9676 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9677 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9678 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9679 9680 callee->in_callback_fn = true; 9681 callee->callback_ret_range = retval_range(0, 1); 9682 return 0; 9683 } 9684 9685 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9686 struct bpf_func_state *caller, 9687 struct bpf_func_state *callee, 9688 int insn_idx) 9689 { 9690 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9691 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9692 * 9693 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9694 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9695 * by this point, so look at 'root' 9696 */ 9697 struct btf_field *field; 9698 9699 field = reg_find_field_offset(&caller->regs[BPF_REG_1], 9700 caller->regs[BPF_REG_1].var_off.value, 9701 BPF_RB_ROOT); 9702 if (!field || !field->graph_root.value_btf_id) 9703 return -EFAULT; 9704 9705 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9706 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9707 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9708 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9709 9710 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 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_callback_fn = true; 9714 callee->callback_ret_range = retval_range(0, 1); 9715 return 0; 9716 } 9717 9718 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env, 9719 struct bpf_func_state *caller, 9720 struct bpf_func_state *callee, 9721 int insn_idx) 9722 { 9723 struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr; 9724 9725 /* 9726 * callback_fn(struct bpf_map *map, void *key, void *value); 9727 */ 9728 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9729 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9730 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9731 9732 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9733 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9734 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9735 9736 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9737 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9738 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9739 9740 /* unused */ 9741 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9742 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9743 callee->in_async_callback_fn = true; 9744 callee->callback_ret_range = retval_range(S32_MIN, S32_MAX); 9745 return 0; 9746 } 9747 9748 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9749 9750 /* Are we currently verifying the callback for a rbtree helper that must 9751 * be called with lock held? If so, no need to complain about unreleased 9752 * lock 9753 */ 9754 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9755 { 9756 struct bpf_verifier_state *state = env->cur_state; 9757 struct bpf_insn *insn = env->prog->insnsi; 9758 struct bpf_func_state *callee; 9759 int kfunc_btf_id; 9760 9761 if (!state->curframe) 9762 return false; 9763 9764 callee = state->frame[state->curframe]; 9765 9766 if (!callee->in_callback_fn) 9767 return false; 9768 9769 kfunc_btf_id = insn[callee->callsite].imm; 9770 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9771 } 9772 9773 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9774 { 9775 if (range.return_32bit) 9776 return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval; 9777 else 9778 return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval; 9779 } 9780 9781 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9782 { 9783 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9784 struct bpf_func_state *caller, *callee; 9785 struct bpf_reg_state *r0; 9786 bool in_callback_fn; 9787 int err; 9788 9789 callee = state->frame[state->curframe]; 9790 r0 = &callee->regs[BPF_REG_0]; 9791 if (r0->type == PTR_TO_STACK) { 9792 /* technically it's ok to return caller's stack pointer 9793 * (or caller's caller's pointer) back to the caller, 9794 * since these pointers are valid. Only current stack 9795 * pointer will be invalid as soon as function exits, 9796 * but let's be conservative 9797 */ 9798 verbose(env, "cannot return stack pointer to the caller\n"); 9799 return -EINVAL; 9800 } 9801 9802 caller = state->frame[state->curframe - 1]; 9803 if (callee->in_callback_fn) { 9804 if (r0->type != SCALAR_VALUE) { 9805 verbose(env, "R0 not a scalar value\n"); 9806 return -EACCES; 9807 } 9808 9809 /* we are going to rely on register's precise value */ 9810 err = mark_chain_precision(env, BPF_REG_0); 9811 if (err) 9812 return err; 9813 9814 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 9815 if (!retval_range_within(callee->callback_ret_range, r0)) { 9816 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9817 "At callback return", "R0"); 9818 return -EINVAL; 9819 } 9820 if (!bpf_calls_callback(env, callee->callsite)) { 9821 verifier_bug(env, "in callback at %d, callsite %d !calls_callback", 9822 *insn_idx, callee->callsite); 9823 return -EFAULT; 9824 } 9825 } else { 9826 /* return to the caller whatever r0 had in the callee */ 9827 caller->regs[BPF_REG_0] = *r0; 9828 } 9829 9830 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9831 * there function call logic would reschedule callback visit. If iteration 9832 * converges is_state_visited() would prune that visit eventually. 9833 */ 9834 in_callback_fn = callee->in_callback_fn; 9835 if (in_callback_fn) 9836 *insn_idx = callee->callsite; 9837 else 9838 *insn_idx = callee->callsite + 1; 9839 9840 if (env->log.level & BPF_LOG_LEVEL) { 9841 verbose(env, "returning from callee:\n"); 9842 print_verifier_state(env, state, callee->frameno, true); 9843 verbose(env, "to caller at %d:\n", *insn_idx); 9844 print_verifier_state(env, state, caller->frameno, true); 9845 } 9846 /* clear everything in the callee. In case of exceptional exits using 9847 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9848 free_func_state(callee); 9849 state->frame[state->curframe--] = NULL; 9850 invalidate_outgoing_stack_args(env, caller); 9851 9852 /* for callbacks widen imprecise scalars to make programs like below verify: 9853 * 9854 * struct ctx { int i; } 9855 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9856 * ... 9857 * struct ctx = { .i = 0; } 9858 * bpf_loop(100, cb, &ctx, 0); 9859 * 9860 * This is similar to what is done in process_iter_next_call() for open 9861 * coded iterators. 9862 */ 9863 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9864 if (prev_st) { 9865 err = widen_imprecise_scalars(env, prev_st, state); 9866 if (err) 9867 return err; 9868 } 9869 return 0; 9870 } 9871 9872 static int do_refine_retval_range(struct bpf_verifier_env *env, 9873 struct bpf_reg_state *regs, int ret_type, 9874 int func_id, 9875 struct bpf_call_arg_meta *meta) 9876 { 9877 struct bpf_retval_range range; 9878 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9879 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9880 9881 if (ret_type != RET_INTEGER) 9882 return 0; 9883 9884 switch (func_id) { 9885 case BPF_FUNC_get_stack: 9886 case BPF_FUNC_get_task_stack: 9887 case BPF_FUNC_probe_read_str: 9888 case BPF_FUNC_probe_read_kernel_str: 9889 case BPF_FUNC_probe_read_user_str: 9890 reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9891 reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9892 reg_bounds_sync(ret_reg); 9893 break; 9894 case BPF_FUNC_get_smp_processor_id: 9895 reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1); 9896 reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1); 9897 reg_bounds_sync(ret_reg); 9898 break; 9899 case BPF_FUNC_get_retval: 9900 /* 9901 * bpf_get_retval may see arbitrary value passed by bpf_prog_run_array_cg for 9902 * CGROUP_GETSOCKOPT type. 9903 */ 9904 if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT && 9905 env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) 9906 break; 9907 9908 if (prog_type == BPF_PROG_TYPE_LSM && 9909 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 9910 if (!env->prog->aux->attach_func_proto->type) 9911 break; 9912 bpf_lsm_get_retval_range(env->prog, &range); 9913 } else { 9914 range.minval = -MAX_ERRNO; 9915 range.maxval = 0; 9916 } 9917 9918 reg_set_srange64(ret_reg, range.minval, range.maxval); 9919 reg_set_srange32(ret_reg, range.minval, range.maxval); 9920 reg_bounds_sync(ret_reg); 9921 break; 9922 } 9923 9924 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9925 } 9926 9927 static int 9928 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9929 int func_id, int insn_idx) 9930 { 9931 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9932 struct bpf_map *map = meta->map.ptr; 9933 9934 if (func_id != BPF_FUNC_tail_call && 9935 func_id != BPF_FUNC_map_lookup_elem && 9936 func_id != BPF_FUNC_map_update_elem && 9937 func_id != BPF_FUNC_map_delete_elem && 9938 func_id != BPF_FUNC_map_push_elem && 9939 func_id != BPF_FUNC_map_pop_elem && 9940 func_id != BPF_FUNC_map_peek_elem && 9941 func_id != BPF_FUNC_for_each_map_elem && 9942 func_id != BPF_FUNC_redirect_map && 9943 func_id != BPF_FUNC_map_lookup_percpu_elem) 9944 return 0; 9945 9946 if (map == NULL) { 9947 verifier_bug(env, "expected map for helper call"); 9948 return -EFAULT; 9949 } 9950 9951 /* In case of read-only, some additional restrictions 9952 * need to be applied in order to prevent altering the 9953 * state of the map from program side. 9954 */ 9955 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9956 (func_id == BPF_FUNC_map_delete_elem || 9957 func_id == BPF_FUNC_map_update_elem || 9958 func_id == BPF_FUNC_map_push_elem || 9959 func_id == BPF_FUNC_map_pop_elem)) { 9960 verbose(env, "write into map forbidden\n"); 9961 return -EACCES; 9962 } 9963 9964 if (!aux->map_ptr_state.map_ptr) 9965 bpf_map_ptr_store(aux, meta->map.ptr, 9966 !meta->map.ptr->bypass_spec_v1, false); 9967 else if (aux->map_ptr_state.map_ptr != meta->map.ptr) 9968 bpf_map_ptr_store(aux, meta->map.ptr, 9969 !meta->map.ptr->bypass_spec_v1, true); 9970 return 0; 9971 } 9972 9973 static int 9974 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9975 int func_id, int insn_idx) 9976 { 9977 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9978 struct bpf_reg_state *reg; 9979 struct bpf_map *map = meta->map.ptr; 9980 u64 val, max; 9981 int err; 9982 9983 if (func_id != BPF_FUNC_tail_call) 9984 return 0; 9985 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9986 verbose(env, "expected prog array map for tail call"); 9987 return -EINVAL; 9988 } 9989 9990 reg = reg_state(env, BPF_REG_3); 9991 val = reg->var_off.value; 9992 max = map->max_entries; 9993 9994 if (!(is_reg_const(reg, false) && val < max)) { 9995 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9996 return 0; 9997 } 9998 9999 err = mark_chain_precision(env, BPF_REG_3); 10000 if (err) 10001 return err; 10002 if (bpf_map_key_unseen(aux)) 10003 bpf_map_key_store(aux, val); 10004 else if (!bpf_map_key_poisoned(aux) && 10005 bpf_map_key_immediate(aux) != val) 10006 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10007 return 0; 10008 } 10009 10010 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 10011 { 10012 struct bpf_verifier_state *state = env->cur_state; 10013 enum bpf_prog_type type = resolve_prog_type(env->prog); 10014 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 10015 bool refs_lingering = false; 10016 int i; 10017 10018 if (!exception_exit && cur_func(env)->frameno) 10019 return 0; 10020 10021 for (i = 0; i < state->acquired_refs; i++) { 10022 if (state->refs[i].type != REF_TYPE_PTR) 10023 continue; 10024 /* Allow struct_ops programs to return a referenced kptr back to 10025 * kernel. Type checks are performed later in check_return_code. 10026 */ 10027 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && 10028 reg->id == state->refs[i].id) 10029 continue; 10030 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 10031 state->refs[i].id, state->refs[i].insn_idx); 10032 refs_lingering = true; 10033 } 10034 return refs_lingering ? -EINVAL : 0; 10035 } 10036 10037 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 10038 { 10039 int err; 10040 10041 if (check_lock && env->cur_state->active_locks) { 10042 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 10043 return -EINVAL; 10044 } 10045 10046 err = check_reference_leak(env, exception_exit); 10047 if (err) { 10048 verbose(env, "%s would lead to reference leak\n", prefix); 10049 return err; 10050 } 10051 10052 if (check_lock && env->cur_state->active_irq_id) { 10053 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix); 10054 return -EINVAL; 10055 } 10056 10057 if (check_lock && env->cur_state->active_rcu_locks) { 10058 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 10059 return -EINVAL; 10060 } 10061 10062 if (check_lock && env->cur_state->active_preempt_locks) { 10063 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 10064 return -EINVAL; 10065 } 10066 10067 return 0; 10068 } 10069 10070 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10071 struct bpf_reg_state *regs) 10072 { 10073 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10074 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10075 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10076 struct bpf_bprintf_data data = {}; 10077 int err, fmt_map_off, num_args; 10078 u64 fmt_addr; 10079 char *fmt; 10080 10081 /* data must be an array of u64 */ 10082 if (data_len_reg->var_off.value % 8) 10083 return -EINVAL; 10084 num_args = data_len_reg->var_off.value / 8; 10085 10086 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10087 * and map_direct_value_addr is set. 10088 */ 10089 fmt_map_off = fmt_reg->var_off.value; 10090 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10091 fmt_map_off); 10092 if (err) { 10093 verbose(env, "failed to retrieve map value address\n"); 10094 return -EFAULT; 10095 } 10096 fmt = (char *)(long)fmt_addr + fmt_map_off; 10097 10098 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10099 * can focus on validating the format specifiers. 10100 */ 10101 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10102 if (err < 0) 10103 verbose(env, "Invalid format string\n"); 10104 10105 return err; 10106 } 10107 10108 static int check_get_func_ip(struct bpf_verifier_env *env) 10109 { 10110 enum bpf_prog_type type = resolve_prog_type(env->prog); 10111 int func_id = BPF_FUNC_get_func_ip; 10112 10113 if (type == BPF_PROG_TYPE_TRACING) { 10114 if (!bpf_prog_has_trampoline(env->prog)) { 10115 verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n", 10116 func_id_name(func_id), func_id); 10117 return -ENOTSUPP; 10118 } 10119 return 0; 10120 } else if (type == BPF_PROG_TYPE_KPROBE) { 10121 return 0; 10122 } 10123 10124 verbose(env, "func %s#%d not supported for program type %d\n", 10125 func_id_name(func_id), func_id, type); 10126 return -ENOTSUPP; 10127 } 10128 10129 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env) 10130 { 10131 return &env->insn_aux_data[env->insn_idx]; 10132 } 10133 10134 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10135 { 10136 struct bpf_reg_state *reg = reg_state(env, BPF_REG_4); 10137 bool reg_is_null = bpf_register_is_null(reg); 10138 10139 if (reg_is_null) 10140 mark_chain_precision(env, BPF_REG_4); 10141 10142 return reg_is_null; 10143 } 10144 10145 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10146 { 10147 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10148 10149 if (!state->initialized) { 10150 state->initialized = 1; 10151 state->fit_for_inline = loop_flag_is_zero(env); 10152 state->callback_subprogno = subprogno; 10153 return; 10154 } 10155 10156 if (!state->fit_for_inline) 10157 return; 10158 10159 state->fit_for_inline = (loop_flag_is_zero(env) && 10160 state->callback_subprogno == subprogno); 10161 } 10162 10163 /* Returns whether or not the given map can potentially elide 10164 * lookup return value nullness check. This is possible if the key 10165 * is statically known. 10166 */ 10167 static bool can_elide_value_nullness(const struct bpf_map *map) 10168 { 10169 if (map->map_flags & BPF_F_INNER_MAP) 10170 return false; 10171 10172 switch (map->map_type) { 10173 case BPF_MAP_TYPE_ARRAY: 10174 case BPF_MAP_TYPE_PERCPU_ARRAY: 10175 return true; 10176 default: 10177 return false; 10178 } 10179 } 10180 10181 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id, 10182 const struct bpf_func_proto **ptr) 10183 { 10184 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 10185 return -ERANGE; 10186 10187 if (!env->ops->get_func_proto) 10188 return -EINVAL; 10189 10190 *ptr = env->ops->get_func_proto(func_id, env->prog); 10191 return *ptr && (*ptr)->func ? 0 : -EINVAL; 10192 } 10193 10194 /* Check if we're in a sleepable context. */ 10195 static inline bool in_sleepable_context(struct bpf_verifier_env *env) 10196 { 10197 return !env->cur_state->active_rcu_locks && 10198 !env->cur_state->active_preempt_locks && 10199 !env->cur_state->active_locks && 10200 !env->cur_state->active_irq_id && 10201 in_sleepable(env); 10202 } 10203 10204 static const char *non_sleepable_context_description(struct bpf_verifier_env *env) 10205 { 10206 if (env->cur_state->active_rcu_locks) 10207 return "rcu_read_lock region"; 10208 if (env->cur_state->active_preempt_locks) 10209 return "non-preemptible region"; 10210 if (env->cur_state->active_irq_id) 10211 return "IRQ-disabled region"; 10212 if (env->cur_state->active_locks) 10213 return "lock region"; 10214 return "non-sleepable prog"; 10215 } 10216 10217 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 10218 bool convert_rcu, bool release_dynptr) 10219 { 10220 int err = -EINVAL; 10221 10222 if (bpf_register_is_null(reg)) 10223 return 0; 10224 10225 if (release_dynptr) 10226 err = unmark_stack_slots_dynptr(env, reg); 10227 else if (convert_rcu) 10228 err = ref_convert_alloc_rcu_protected(env, reg->id); 10229 else if (reg_is_referenced(env, reg)) 10230 err = release_reference(env, reg->id); 10231 10232 return err; 10233 } 10234 10235 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10236 int *insn_idx_p) 10237 { 10238 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10239 bool returns_cpu_specific_alloc_ptr = false; 10240 const struct bpf_func_proto *fn = NULL; 10241 enum bpf_return_type ret_type; 10242 enum bpf_type_flag ret_flag; 10243 struct bpf_reg_state *regs; 10244 struct bpf_call_arg_meta meta; 10245 int insn_idx = *insn_idx_p; 10246 bool changes_data; 10247 int i, err, func_id; 10248 10249 /* find function prototype */ 10250 func_id = insn->imm; 10251 err = bpf_get_helper_proto(env, insn->imm, &fn); 10252 if (err == -ERANGE) { 10253 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 10254 return -EINVAL; 10255 } 10256 10257 if (err) { 10258 verbose(env, "program of this type cannot use helper %s#%d\n", 10259 func_id_name(func_id), func_id); 10260 return err; 10261 } 10262 10263 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10264 if (!env->prog->gpl_compatible && fn->gpl_only) { 10265 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10266 return -EINVAL; 10267 } 10268 10269 if (fn->allowed && !fn->allowed(env->prog)) { 10270 verbose(env, "helper call is not allowed in probe\n"); 10271 return -EINVAL; 10272 } 10273 10274 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10275 changes_data = bpf_helper_changes_pkt_data(func_id); 10276 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10277 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id); 10278 return -EFAULT; 10279 } 10280 10281 memset(&meta, 0, sizeof(meta)); 10282 10283 err = check_func_proto(fn, &meta); 10284 if (err) { 10285 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id); 10286 return err; 10287 } 10288 10289 if (fn->might_sleep && !in_sleepable_context(env)) { 10290 verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id, 10291 non_sleepable_context_description(env)); 10292 return -EINVAL; 10293 } 10294 10295 /* Track non-sleepable context for helpers. */ 10296 if (!in_sleepable_context(env)) 10297 env->insn_aux_data[insn_idx].non_sleepable = true; 10298 10299 meta.func_id = func_id; 10300 /* check args */ 10301 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10302 err = check_func_arg(env, i, &meta, fn, insn_idx); 10303 if (err) 10304 return err; 10305 } 10306 10307 err = record_func_map(env, &meta, func_id, insn_idx); 10308 if (err) 10309 return err; 10310 10311 err = record_func_key(env, &meta, func_id, insn_idx); 10312 if (err) 10313 return err; 10314 10315 regs = cur_regs(env); 10316 10317 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10318 * is inferred from register state. 10319 */ 10320 for (i = 0; i < meta.arg_raw_mem.size; i++) { 10321 err = check_mem_access(env, insn_idx, regs + meta.arg_raw_mem.regno, 10322 argno_from_reg(meta.arg_raw_mem.regno), i, BPF_B, 10323 BPF_WRITE, -1, false, false); 10324 if (err) 10325 return err; 10326 } 10327 10328 if (meta.release_regno) { 10329 struct bpf_reg_state *reg = ®s[meta.release_regno]; 10330 bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) && 10331 (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU); 10332 10333 err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id); 10334 if (err) 10335 return err; 10336 } 10337 10338 switch (func_id) { 10339 case BPF_FUNC_tail_call: 10340 err = check_resource_leak(env, false, true, "tail_call"); 10341 if (err) 10342 return err; 10343 break; 10344 case BPF_FUNC_get_local_storage: 10345 /* check that flags argument in get_local_storage(map, flags) is 0, 10346 * this is required because get_local_storage() can't return an error. 10347 */ 10348 if (!bpf_register_is_null(®s[BPF_REG_2])) { 10349 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10350 return -EINVAL; 10351 } 10352 break; 10353 case BPF_FUNC_for_each_map_elem: 10354 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10355 set_map_elem_callback_state); 10356 break; 10357 case BPF_FUNC_timer_set_callback: 10358 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10359 set_timer_callback_state); 10360 break; 10361 case BPF_FUNC_find_vma: 10362 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10363 set_find_vma_callback_state); 10364 break; 10365 case BPF_FUNC_snprintf: 10366 err = check_bpf_snprintf_call(env, regs); 10367 break; 10368 case BPF_FUNC_loop: 10369 update_loop_inline_state(env, meta.subprogno); 10370 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10371 * is finished, thus mark it precise. 10372 */ 10373 err = mark_chain_precision(env, BPF_REG_1); 10374 if (err) 10375 return err; 10376 if (cur_func(env)->callback_depth < reg_umax(®s[BPF_REG_1])) { 10377 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10378 set_loop_callback_state); 10379 } else { 10380 cur_func(env)->callback_depth = 0; 10381 if (env->log.level & BPF_LOG_LEVEL2) 10382 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10383 env->cur_state->curframe); 10384 } 10385 break; 10386 case BPF_FUNC_dynptr_from_mem: 10387 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10388 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10389 reg_type_str(env, regs[BPF_REG_1].type)); 10390 return -EACCES; 10391 } 10392 break; 10393 case BPF_FUNC_set_retval: 10394 { 10395 struct bpf_retval_range range = { 10396 .minval = -MAX_ERRNO, 10397 .maxval = 0, 10398 .return_32bit = true 10399 }; 10400 struct bpf_reg_state *r1 = ®s[BPF_REG_1]; 10401 10402 if (r1->type != SCALAR_VALUE) { 10403 verbose(env, "R1 is not a scalar\n"); 10404 return -EINVAL; 10405 } 10406 10407 /* CGROUP_GETSOCKOPT is allowed to return arbitrary value */ 10408 if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT && 10409 env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) 10410 break; 10411 10412 if (prog_type == BPF_PROG_TYPE_LSM && 10413 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10414 if (!env->prog->aux->attach_func_proto->type) { 10415 /* Make sure programs that attach to void 10416 * hooks don't try to modify return value. 10417 */ 10418 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10419 return -EINVAL; 10420 } 10421 bpf_lsm_get_retval_range(env->prog, &range); 10422 } 10423 10424 err = mark_chain_precision(env, BPF_REG_1); 10425 if (err) 10426 return err; 10427 10428 if (!retval_range_within(range, r1)) { 10429 verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1"); 10430 return -EINVAL; 10431 } 10432 10433 break; 10434 } 10435 case BPF_FUNC_dynptr_write: 10436 { 10437 enum bpf_dynptr_type dynptr_type = meta.dynptr.type; 10438 10439 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10440 return -EFAULT; 10441 10442 if (dynptr_type == BPF_DYNPTR_TYPE_SKB || 10443 dynptr_type == BPF_DYNPTR_TYPE_SKB_META) 10444 /* this will trigger clear_all_pkt_pointers(), which will 10445 * invalidate all dynptr slices associated with the skb 10446 */ 10447 changes_data = true; 10448 10449 break; 10450 } 10451 case BPF_FUNC_per_cpu_ptr: 10452 case BPF_FUNC_this_cpu_ptr: 10453 { 10454 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10455 const struct btf_type *type; 10456 10457 if (reg->type & MEM_RCU) { 10458 type = btf_type_by_id(reg->btf, reg->btf_id); 10459 if (!type || !btf_type_is_struct(type)) { 10460 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10461 return -EFAULT; 10462 } 10463 returns_cpu_specific_alloc_ptr = true; 10464 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10465 } 10466 break; 10467 } 10468 case BPF_FUNC_user_ringbuf_drain: 10469 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10470 set_user_ringbuf_callback_state); 10471 break; 10472 } 10473 10474 if (err) 10475 return err; 10476 10477 /* reset caller saved regs */ 10478 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10479 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 10480 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10481 } 10482 invalidate_outgoing_stack_args(env, cur_func(env)); 10483 10484 /* helper call returns 64-bit value. */ 10485 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10486 10487 /* update return register (already marked as written above) */ 10488 ret_type = fn->ret_type; 10489 ret_flag = type_flag(ret_type); 10490 10491 switch (base_type(ret_type)) { 10492 case RET_INTEGER: 10493 /* sets type to SCALAR_VALUE */ 10494 mark_reg_unknown(env, regs, BPF_REG_0); 10495 break; 10496 case RET_VOID: 10497 regs[BPF_REG_0].type = NOT_INIT; 10498 break; 10499 case RET_PTR_TO_MAP_VALUE: 10500 /* There is no offset yet applied, variable or fixed */ 10501 mark_reg_known_zero(env, regs, BPF_REG_0); 10502 /* remember map_ptr, so that check_map_access() 10503 * can check 'value_size' boundary of memory access 10504 * to map element returned from bpf_map_lookup_elem() 10505 */ 10506 if (meta.map.ptr == NULL) { 10507 verifier_bug(env, "unexpected null map_ptr"); 10508 return -EFAULT; 10509 } 10510 10511 if (func_id == BPF_FUNC_map_lookup_elem && 10512 can_elide_value_nullness(meta.map.ptr) && 10513 meta.const_map_key >= 0 && 10514 meta.const_map_key < meta.map.ptr->max_entries) 10515 ret_flag &= ~PTR_MAYBE_NULL; 10516 10517 regs[BPF_REG_0].map_ptr = meta.map.ptr; 10518 regs[BPF_REG_0].map_uid = meta.map.uid; 10519 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10520 if (!type_may_be_null(ret_flag) && 10521 btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 10522 regs[BPF_REG_0].id = ++env->id_gen; 10523 } 10524 break; 10525 case RET_PTR_TO_SOCKET: 10526 mark_reg_known_zero(env, regs, BPF_REG_0); 10527 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10528 break; 10529 case RET_PTR_TO_SOCK_COMMON: 10530 mark_reg_known_zero(env, regs, BPF_REG_0); 10531 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10532 break; 10533 case RET_PTR_TO_TCP_SOCK: 10534 mark_reg_known_zero(env, regs, BPF_REG_0); 10535 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10536 break; 10537 case RET_PTR_TO_MEM: 10538 mark_reg_known_zero(env, regs, BPF_REG_0); 10539 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10540 regs[BPF_REG_0].mem_size = meta.ret_mem.size; 10541 break; 10542 case RET_PTR_TO_MEM_OR_BTF_ID: 10543 { 10544 const struct btf_type *t; 10545 10546 mark_reg_known_zero(env, regs, BPF_REG_0); 10547 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10548 if (!btf_type_is_struct(t)) { 10549 u32 tsize; 10550 const struct btf_type *ret; 10551 const char *tname; 10552 10553 /* resolve the type size of ksym. */ 10554 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10555 if (IS_ERR(ret)) { 10556 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10557 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10558 tname, PTR_ERR(ret)); 10559 return -EINVAL; 10560 } 10561 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10562 regs[BPF_REG_0].mem_size = tsize; 10563 } else { 10564 if (returns_cpu_specific_alloc_ptr) { 10565 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10566 } else { 10567 /* MEM_RDONLY may be carried from ret_flag, but it 10568 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10569 * it will confuse the check of PTR_TO_BTF_ID in 10570 * check_mem_access(). 10571 */ 10572 ret_flag &= ~MEM_RDONLY; 10573 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10574 } 10575 10576 regs[BPF_REG_0].btf = meta.ret_btf; 10577 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10578 } 10579 break; 10580 } 10581 case RET_PTR_TO_BTF_ID: 10582 { 10583 struct btf *ret_btf; 10584 int ret_btf_id; 10585 10586 mark_reg_known_zero(env, regs, BPF_REG_0); 10587 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10588 if (func_id == BPF_FUNC_kptr_xchg) { 10589 ret_btf = meta.kptr_field->kptr.btf; 10590 ret_btf_id = meta.kptr_field->kptr.btf_id; 10591 if (!btf_is_kernel(ret_btf)) { 10592 regs[BPF_REG_0].type |= MEM_ALLOC; 10593 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10594 regs[BPF_REG_0].type |= MEM_PERCPU; 10595 } 10596 } else { 10597 if (fn->ret_btf_id == BPF_PTR_POISON) { 10598 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type", 10599 func_id_name(func_id)); 10600 return -EFAULT; 10601 } 10602 ret_btf = btf_vmlinux; 10603 ret_btf_id = *fn->ret_btf_id; 10604 } 10605 if (ret_btf_id == 0) { 10606 verbose(env, "invalid return type %u of func %s#%d\n", 10607 base_type(ret_type), func_id_name(func_id), 10608 func_id); 10609 return -EINVAL; 10610 } 10611 regs[BPF_REG_0].btf = ret_btf; 10612 regs[BPF_REG_0].btf_id = ret_btf_id; 10613 break; 10614 } 10615 default: 10616 verbose(env, "unknown return type %u of func %s#%d\n", 10617 base_type(ret_type), func_id_name(func_id), func_id); 10618 return -EINVAL; 10619 } 10620 10621 if (type_may_be_null(regs[BPF_REG_0].type)) 10622 regs[BPF_REG_0].id = ++env->id_gen; 10623 10624 if (is_ptr_cast_function(func_id) && 10625 find_reference_state(env->cur_state, meta.ref_obj.id)) { 10626 struct bpf_verifier_state *branch; 10627 struct bpf_reg_state *r0; 10628 10629 err = validate_ref_obj(env, &meta.ref_obj); 10630 if (err) 10631 return err; 10632 10633 /* 10634 * In order for a release of any of the original or cast pointers 10635 * to invalidate all other pointers, reuse the same reference id for 10636 * the cast result. 10637 * This reference id can't be used for nullness propagation, 10638 * as cast might return NULL for a non-NULL input. 10639 * Hence, explore the NULL case as a separate branch. 10640 */ 10641 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10642 if (IS_ERR(branch)) 10643 return PTR_ERR(branch); 10644 10645 r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0]; 10646 __mark_reg_known_zero(r0); 10647 r0->type = SCALAR_VALUE; 10648 10649 regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL; 10650 regs[BPF_REG_0].id = meta.ref_obj.id; 10651 } else if (is_acquire_function(func_id, meta.map.ptr)) { 10652 int id = acquire_reference(env, insn_idx, 0); 10653 10654 if (id < 0) 10655 return id; 10656 10657 regs[BPF_REG_0].id = id; 10658 } 10659 10660 if (func_id == BPF_FUNC_dynptr_data) 10661 regs[BPF_REG_0].parent_id = meta.dynptr.id; 10662 10663 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10664 if (err) 10665 return err; 10666 10667 err = check_map_func_compatibility(env, meta.map.ptr, func_id); 10668 if (err) 10669 return err; 10670 10671 if ((func_id == BPF_FUNC_get_stack || 10672 func_id == BPF_FUNC_get_task_stack) && 10673 !env->prog->has_callchain_buf) { 10674 const char *err_str; 10675 10676 #ifdef CONFIG_PERF_EVENTS 10677 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10678 err_str = "cannot get callchain buffer for func %s#%d\n"; 10679 #else 10680 err = -ENOTSUPP; 10681 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10682 #endif 10683 if (err) { 10684 verbose(env, err_str, func_id_name(func_id), func_id); 10685 return err; 10686 } 10687 10688 env->prog->has_callchain_buf = true; 10689 } 10690 10691 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10692 env->prog->call_get_stack = true; 10693 10694 if (func_id == BPF_FUNC_get_func_ip) { 10695 if (check_get_func_ip(env)) 10696 return -ENOTSUPP; 10697 env->prog->call_get_func_ip = true; 10698 } 10699 10700 if (func_id == BPF_FUNC_tail_call) { 10701 if (env->cur_state->curframe) { 10702 struct bpf_verifier_state *branch; 10703 10704 mark_reg_scratched(env, BPF_REG_0); 10705 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10706 if (IS_ERR(branch)) 10707 return PTR_ERR(branch); 10708 clear_all_pkt_pointers(env); 10709 mark_reg_unknown(env, regs, BPF_REG_0); 10710 err = prepare_func_exit(env, &env->insn_idx); 10711 if (err) 10712 return err; 10713 env->insn_idx--; 10714 } else { 10715 changes_data = false; 10716 } 10717 } 10718 10719 if (changes_data) 10720 clear_all_pkt_pointers(env); 10721 return 0; 10722 } 10723 10724 /* mark_btf_func_reg_size() is used when the reg size is determined by 10725 * the BTF func_proto's return value size and argument. 10726 */ 10727 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs, 10728 u32 regno, size_t reg_size) 10729 { 10730 struct bpf_reg_state *reg = ®s[regno]; 10731 10732 if (regno == BPF_REG_0) { 10733 /* Function return value */ 10734 reg->subreg_def = reg_size == sizeof(u64) ? 10735 DEF_NOT_SUBREG : env->insn_idx + 1; 10736 } else if (reg_size == sizeof(u64)) { 10737 /* Function argument */ 10738 mark_insn_zext(env, reg); 10739 } 10740 } 10741 10742 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10743 size_t reg_size) 10744 { 10745 return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size); 10746 } 10747 10748 static bool is_kfunc_acquire(struct bpf_call_arg_meta *meta) 10749 { 10750 return meta->kfunc_flags & KF_ACQUIRE; 10751 } 10752 10753 static bool is_kfunc_release(struct bpf_call_arg_meta *meta) 10754 { 10755 return meta->kfunc_flags & KF_RELEASE; 10756 } 10757 10758 static bool is_kfunc_destructive(struct bpf_call_arg_meta *meta) 10759 { 10760 return meta->kfunc_flags & KF_DESTRUCTIVE; 10761 } 10762 10763 static bool is_kfunc_rcu(struct bpf_call_arg_meta *meta) 10764 { 10765 return meta->kfunc_flags & KF_RCU; 10766 } 10767 10768 static bool is_kfunc_rcu_protected(struct bpf_call_arg_meta *meta) 10769 { 10770 return meta->kfunc_flags & KF_RCU_PROTECTED; 10771 } 10772 10773 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10774 const struct btf_param *arg, 10775 const struct bpf_reg_state *reg) 10776 { 10777 const struct btf_type *t; 10778 10779 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10780 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10781 return false; 10782 10783 return btf_param_match_suffix(btf, arg, "__sz"); 10784 } 10785 10786 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10787 const struct btf_param *arg, 10788 const struct bpf_reg_state *reg) 10789 { 10790 const struct btf_type *t; 10791 10792 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10793 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10794 return false; 10795 10796 return btf_param_match_suffix(btf, arg, "__szk"); 10797 } 10798 10799 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10800 { 10801 return btf_param_match_suffix(btf, arg, "__k"); 10802 } 10803 10804 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10805 { 10806 return btf_param_match_suffix(btf, arg, "__ign"); 10807 } 10808 10809 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 10810 { 10811 return btf_param_match_suffix(btf, arg, "__map"); 10812 } 10813 10814 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10815 { 10816 return btf_param_match_suffix(btf, arg, "__alloc"); 10817 } 10818 10819 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10820 { 10821 return btf_param_match_suffix(btf, arg, "__uninit"); 10822 } 10823 10824 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10825 { 10826 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 10827 } 10828 10829 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10830 { 10831 return btf_param_match_suffix(btf, arg, "__nullable"); 10832 } 10833 10834 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg) 10835 { 10836 return btf_param_match_suffix(btf, arg, "__nonown_allowed"); 10837 } 10838 10839 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10840 { 10841 return btf_param_match_suffix(btf, arg, "__str"); 10842 } 10843 10844 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg) 10845 { 10846 return btf_param_match_suffix(btf, arg, "__irq_flag"); 10847 } 10848 10849 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10850 const struct btf_param *arg, 10851 const char *name) 10852 { 10853 int len, target_len = strlen(name); 10854 const char *param_name; 10855 10856 param_name = btf_name_by_offset(btf, arg->name_off); 10857 if (str_is_empty(param_name)) 10858 return false; 10859 len = strlen(param_name); 10860 if (len != target_len) 10861 return false; 10862 if (strcmp(param_name, name)) 10863 return false; 10864 10865 return true; 10866 } 10867 10868 enum { 10869 KF_ARG_DYNPTR_ID, 10870 KF_ARG_LIST_HEAD_ID, 10871 KF_ARG_LIST_NODE_ID, 10872 KF_ARG_RB_ROOT_ID, 10873 KF_ARG_RB_NODE_ID, 10874 KF_ARG_WORKQUEUE_ID, 10875 KF_ARG_RES_SPIN_LOCK_ID, 10876 KF_ARG_TASK_WORK_ID, 10877 KF_ARG_PROG_AUX_ID, 10878 KF_ARG_TIMER_ID 10879 }; 10880 10881 BTF_ID_LIST(kf_arg_btf_ids) 10882 BTF_ID(struct, bpf_dynptr) 10883 BTF_ID(struct, bpf_list_head) 10884 BTF_ID(struct, bpf_list_node) 10885 BTF_ID(struct, bpf_rb_root) 10886 BTF_ID(struct, bpf_rb_node) 10887 BTF_ID(struct, bpf_wq) 10888 BTF_ID(struct, bpf_res_spin_lock) 10889 BTF_ID(struct, bpf_task_work) 10890 BTF_ID(struct, bpf_prog_aux) 10891 BTF_ID(struct, bpf_timer) 10892 10893 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10894 const struct btf_param *arg, int type) 10895 { 10896 const struct btf_type *t; 10897 u32 res_id; 10898 10899 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10900 if (!t) 10901 return false; 10902 if (!btf_type_is_ptr(t)) 10903 return false; 10904 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10905 if (!t) 10906 return false; 10907 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10908 } 10909 10910 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10911 { 10912 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10913 } 10914 10915 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10916 { 10917 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10918 } 10919 10920 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10921 { 10922 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10923 } 10924 10925 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10926 { 10927 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10928 } 10929 10930 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10931 { 10932 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10933 } 10934 10935 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg) 10936 { 10937 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID); 10938 } 10939 10940 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 10941 { 10942 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 10943 } 10944 10945 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg) 10946 { 10947 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID); 10948 } 10949 10950 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg) 10951 { 10952 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID); 10953 } 10954 10955 static bool is_rbtree_node_type(const struct btf_type *t) 10956 { 10957 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]); 10958 } 10959 10960 static bool is_list_node_type(const struct btf_type *t) 10961 { 10962 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]); 10963 } 10964 10965 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10966 const struct btf_param *arg) 10967 { 10968 const struct btf_type *t; 10969 10970 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10971 if (!t) 10972 return false; 10973 10974 return true; 10975 } 10976 10977 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg) 10978 { 10979 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID); 10980 } 10981 10982 /* 10983 * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF: 10984 * - the _impl prototype with full arg list (meta->func_proto) 10985 * - the BPF API prototype w/o implicit args (func->type in BTF) 10986 * To determine whether an argument is implicit, we compare its position 10987 * against the number of arguments in the prototype w/o implicit args. 10988 */ 10989 static bool is_kfunc_arg_implicit(const struct bpf_call_arg_meta *meta, u32 arg_idx) 10990 { 10991 const struct btf_type *func, *func_proto; 10992 u32 argn; 10993 10994 if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS)) 10995 return false; 10996 10997 func = btf_type_by_id(meta->btf, meta->func_id); 10998 func_proto = btf_type_by_id(meta->btf, func->type); 10999 argn = btf_type_vlen(func_proto); 11000 11001 return argn <= arg_idx; 11002 } 11003 11004 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 11005 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 11006 const struct btf *btf, 11007 const struct btf_type *t, int rec) 11008 { 11009 const struct btf_type *member_type; 11010 const struct btf_member *member; 11011 u32 i; 11012 11013 if (!btf_type_is_struct(t)) 11014 return false; 11015 11016 for_each_member(i, t, member) { 11017 const struct btf_array *array; 11018 11019 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 11020 if (btf_type_is_struct(member_type)) { 11021 if (rec >= 3) { 11022 verbose(env, "max struct nesting depth exceeded\n"); 11023 return false; 11024 } 11025 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 11026 return false; 11027 continue; 11028 } 11029 if (btf_type_is_array(member_type)) { 11030 array = btf_array(member_type); 11031 if (!array->nelems) 11032 return false; 11033 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 11034 if (!btf_type_is_scalar(member_type)) 11035 return false; 11036 continue; 11037 } 11038 if (!btf_type_is_scalar(member_type)) 11039 return false; 11040 } 11041 return true; 11042 } 11043 11044 enum kfunc_ptr_arg_type { 11045 KF_ARG_PTR_TO_CTX, 11046 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 11047 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 11048 KF_ARG_PTR_TO_DYNPTR, 11049 KF_ARG_PTR_TO_ITER, 11050 KF_ARG_PTR_TO_LIST_HEAD, 11051 KF_ARG_PTR_TO_LIST_NODE, 11052 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 11053 KF_ARG_PTR_TO_MEM, 11054 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 11055 KF_ARG_PTR_TO_CALLBACK, 11056 KF_ARG_PTR_TO_RB_ROOT, 11057 KF_ARG_PTR_TO_RB_NODE, 11058 KF_ARG_PTR_TO_NULL, 11059 KF_ARG_PTR_TO_CONST_STR, 11060 KF_ARG_PTR_TO_MAP, 11061 KF_ARG_PTR_TO_TIMER, 11062 KF_ARG_PTR_TO_WORKQUEUE, 11063 KF_ARG_PTR_TO_IRQ_FLAG, 11064 KF_ARG_PTR_TO_RES_SPIN_LOCK, 11065 KF_ARG_PTR_TO_TASK_WORK, 11066 }; 11067 11068 enum special_kfunc_type { 11069 KF_bpf_obj_new_impl, 11070 KF_bpf_obj_new, 11071 KF_bpf_obj_drop_impl, 11072 KF_bpf_obj_drop, 11073 KF_bpf_refcount_acquire_impl, 11074 KF_bpf_refcount_acquire, 11075 KF_bpf_list_push_front_impl, 11076 KF_bpf_list_push_front, 11077 KF_bpf_list_push_back_impl, 11078 KF_bpf_list_push_back, 11079 KF_bpf_list_add, 11080 KF_bpf_list_pop_front, 11081 KF_bpf_list_pop_back, 11082 KF_bpf_list_del, 11083 KF_bpf_list_front, 11084 KF_bpf_list_back, 11085 KF_bpf_list_is_first, 11086 KF_bpf_list_is_last, 11087 KF_bpf_list_empty, 11088 KF_bpf_cast_to_kern_ctx, 11089 KF_bpf_rdonly_cast, 11090 KF_bpf_rcu_read_lock, 11091 KF_bpf_rcu_read_unlock, 11092 KF_bpf_rbtree_remove, 11093 KF_bpf_rbtree_add_impl, 11094 KF_bpf_rbtree_add, 11095 KF_bpf_rbtree_first, 11096 KF_bpf_rbtree_root, 11097 KF_bpf_rbtree_left, 11098 KF_bpf_rbtree_right, 11099 KF_bpf_dynptr_from_skb, 11100 KF_bpf_dynptr_from_xdp, 11101 KF_bpf_dynptr_from_skb_meta, 11102 KF_bpf_xdp_pull_data, 11103 KF_bpf_dynptr_slice, 11104 KF_bpf_dynptr_slice_rdwr, 11105 KF_bpf_dynptr_clone, 11106 KF_bpf_percpu_obj_new_impl, 11107 KF_bpf_percpu_obj_new, 11108 KF_bpf_percpu_obj_drop_impl, 11109 KF_bpf_percpu_obj_drop, 11110 KF_bpf_throw, 11111 KF_bpf_wq_set_callback, 11112 KF_bpf_preempt_disable, 11113 KF_bpf_preempt_enable, 11114 KF_bpf_iter_css_task_new, 11115 KF_bpf_session_cookie, 11116 KF_bpf_get_kmem_cache, 11117 KF_bpf_local_irq_save, 11118 KF_bpf_local_irq_restore, 11119 KF_bpf_iter_num_new, 11120 KF_bpf_iter_num_next, 11121 KF_bpf_iter_num_destroy, 11122 KF_bpf_set_dentry_xattr, 11123 KF_bpf_remove_dentry_xattr, 11124 KF_bpf_res_spin_lock, 11125 KF_bpf_res_spin_unlock, 11126 KF_bpf_res_spin_lock_irqsave, 11127 KF_bpf_res_spin_unlock_irqrestore, 11128 KF_bpf_dynptr_from_file, 11129 KF_bpf_dynptr_file_discard, 11130 KF___bpf_trap, 11131 KF_bpf_task_work_schedule_signal, 11132 KF_bpf_task_work_schedule_resume, 11133 KF_bpf_arena_alloc_pages, 11134 KF_bpf_arena_free_pages, 11135 KF_bpf_arena_reserve_pages, 11136 KF_bpf_session_is_return, 11137 KF_bpf_stream_vprintk, 11138 KF_bpf_stream_print_stack, 11139 }; 11140 11141 BTF_ID_LIST(special_kfunc_list) 11142 BTF_ID(func, bpf_obj_new_impl) 11143 BTF_ID(func, bpf_obj_new) 11144 BTF_ID(func, bpf_obj_drop_impl) 11145 BTF_ID(func, bpf_obj_drop) 11146 BTF_ID(func, bpf_refcount_acquire_impl) 11147 BTF_ID(func, bpf_refcount_acquire) 11148 BTF_ID(func, bpf_list_push_front_impl) 11149 BTF_ID(func, bpf_list_push_front) 11150 BTF_ID(func, bpf_list_push_back_impl) 11151 BTF_ID(func, bpf_list_push_back) 11152 BTF_ID(func, bpf_list_add) 11153 BTF_ID(func, bpf_list_pop_front) 11154 BTF_ID(func, bpf_list_pop_back) 11155 BTF_ID(func, bpf_list_del) 11156 BTF_ID(func, bpf_list_front) 11157 BTF_ID(func, bpf_list_back) 11158 BTF_ID(func, bpf_list_is_first) 11159 BTF_ID(func, bpf_list_is_last) 11160 BTF_ID(func, bpf_list_empty) 11161 BTF_ID(func, bpf_cast_to_kern_ctx) 11162 BTF_ID(func, bpf_rdonly_cast) 11163 BTF_ID(func, bpf_rcu_read_lock) 11164 BTF_ID(func, bpf_rcu_read_unlock) 11165 BTF_ID(func, bpf_rbtree_remove) 11166 BTF_ID(func, bpf_rbtree_add_impl) 11167 BTF_ID(func, bpf_rbtree_add) 11168 BTF_ID(func, bpf_rbtree_first) 11169 BTF_ID(func, bpf_rbtree_root) 11170 BTF_ID(func, bpf_rbtree_left) 11171 BTF_ID(func, bpf_rbtree_right) 11172 #ifdef CONFIG_NET 11173 BTF_ID(func, bpf_dynptr_from_skb) 11174 BTF_ID(func, bpf_dynptr_from_xdp) 11175 BTF_ID(func, bpf_dynptr_from_skb_meta) 11176 BTF_ID(func, bpf_xdp_pull_data) 11177 #else 11178 BTF_ID_UNUSED 11179 BTF_ID_UNUSED 11180 BTF_ID_UNUSED 11181 BTF_ID_UNUSED 11182 #endif 11183 BTF_ID(func, bpf_dynptr_slice) 11184 BTF_ID(func, bpf_dynptr_slice_rdwr) 11185 BTF_ID(func, bpf_dynptr_clone) 11186 BTF_ID(func, bpf_percpu_obj_new_impl) 11187 BTF_ID(func, bpf_percpu_obj_new) 11188 BTF_ID(func, bpf_percpu_obj_drop_impl) 11189 BTF_ID(func, bpf_percpu_obj_drop) 11190 BTF_ID(func, bpf_throw) 11191 BTF_ID(func, bpf_wq_set_callback) 11192 BTF_ID(func, bpf_preempt_disable) 11193 BTF_ID(func, bpf_preempt_enable) 11194 #ifdef CONFIG_CGROUPS 11195 BTF_ID(func, bpf_iter_css_task_new) 11196 #else 11197 BTF_ID_UNUSED 11198 #endif 11199 #ifdef CONFIG_BPF_EVENTS 11200 BTF_ID(func, bpf_session_cookie) 11201 #else 11202 BTF_ID_UNUSED 11203 #endif 11204 BTF_ID(func, bpf_get_kmem_cache) 11205 BTF_ID(func, bpf_local_irq_save) 11206 BTF_ID(func, bpf_local_irq_restore) 11207 BTF_ID(func, bpf_iter_num_new) 11208 BTF_ID(func, bpf_iter_num_next) 11209 BTF_ID(func, bpf_iter_num_destroy) 11210 #ifdef CONFIG_BPF_LSM 11211 BTF_ID(func, bpf_set_dentry_xattr) 11212 BTF_ID(func, bpf_remove_dentry_xattr) 11213 #else 11214 BTF_ID_UNUSED 11215 BTF_ID_UNUSED 11216 #endif 11217 BTF_ID(func, bpf_res_spin_lock) 11218 BTF_ID(func, bpf_res_spin_unlock) 11219 BTF_ID(func, bpf_res_spin_lock_irqsave) 11220 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 11221 BTF_ID(func, bpf_dynptr_from_file) 11222 BTF_ID(func, bpf_dynptr_file_discard) 11223 BTF_ID(func, __bpf_trap) 11224 BTF_ID(func, bpf_task_work_schedule_signal) 11225 BTF_ID(func, bpf_task_work_schedule_resume) 11226 BTF_ID(func, bpf_arena_alloc_pages) 11227 BTF_ID(func, bpf_arena_free_pages) 11228 BTF_ID(func, bpf_arena_reserve_pages) 11229 #ifdef CONFIG_BPF_EVENTS 11230 BTF_ID(func, bpf_session_is_return) 11231 #else 11232 BTF_ID_UNUSED 11233 #endif 11234 BTF_ID(func, bpf_stream_vprintk) 11235 BTF_ID(func, bpf_stream_print_stack) 11236 11237 static bool is_bpf_obj_new_kfunc(u32 func_id) 11238 { 11239 return func_id == special_kfunc_list[KF_bpf_obj_new] || 11240 func_id == special_kfunc_list[KF_bpf_obj_new_impl]; 11241 } 11242 11243 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id) 11244 { 11245 return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] || 11246 func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]; 11247 } 11248 11249 static bool is_bpf_obj_drop_kfunc(u32 func_id) 11250 { 11251 return func_id == special_kfunc_list[KF_bpf_obj_drop] || 11252 func_id == special_kfunc_list[KF_bpf_obj_drop_impl]; 11253 } 11254 11255 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id) 11256 { 11257 return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] || 11258 func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]; 11259 } 11260 11261 static bool is_bpf_refcount_acquire_kfunc(u32 func_id) 11262 { 11263 return func_id == special_kfunc_list[KF_bpf_refcount_acquire] || 11264 func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11265 } 11266 11267 static bool is_bpf_list_push_kfunc(u32 func_id) 11268 { 11269 return func_id == special_kfunc_list[KF_bpf_list_push_front] || 11270 func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11271 func_id == special_kfunc_list[KF_bpf_list_push_back] || 11272 func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11273 func_id == special_kfunc_list[KF_bpf_list_add]; 11274 } 11275 11276 static bool is_bpf_rbtree_add_kfunc(u32 func_id) 11277 { 11278 return func_id == special_kfunc_list[KF_bpf_rbtree_add] || 11279 func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11280 } 11281 11282 static bool is_task_work_add_kfunc(u32 func_id) 11283 { 11284 return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] || 11285 func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume]; 11286 } 11287 11288 static bool is_kfunc_ret_null(struct bpf_call_arg_meta *meta) 11289 { 11290 if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref) 11291 return false; 11292 11293 return meta->kfunc_flags & KF_RET_NULL; 11294 } 11295 11296 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_call_arg_meta *meta) 11297 { 11298 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11299 } 11300 11301 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_call_arg_meta *meta) 11302 { 11303 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11304 } 11305 11306 static bool is_kfunc_bpf_preempt_disable(struct bpf_call_arg_meta *meta) 11307 { 11308 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11309 } 11310 11311 static bool is_kfunc_bpf_preempt_enable(struct bpf_call_arg_meta *meta) 11312 { 11313 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11314 } 11315 11316 bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta) 11317 { 11318 return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data]; 11319 } 11320 11321 static enum kfunc_ptr_arg_type 11322 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, struct bpf_func_state *caller, 11323 struct bpf_reg_state *regs, struct bpf_call_arg_meta *meta, 11324 const struct btf_type *t, const struct btf_type *ref_t, 11325 const char *ref_tname, const struct btf_param *args, 11326 int arg, int nargs, argno_t argno, struct bpf_reg_state *reg) 11327 { 11328 bool arg_mem_size = false; 11329 11330 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 11331 meta->func_id == special_kfunc_list[KF_bpf_session_is_return] || 11332 meta->func_id == special_kfunc_list[KF_bpf_session_cookie]) 11333 return KF_ARG_PTR_TO_CTX; 11334 11335 if (arg + 1 < nargs && 11336 (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)) || 11337 is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)))) 11338 arg_mem_size = true; 11339 11340 /* In this function, we verify the kfunc's BTF as per the argument type, 11341 * leaving the rest of the verification with respect to the register 11342 * type to our caller. When a set of conditions hold in the BTF type of 11343 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11344 */ 11345 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg)) 11346 return KF_ARG_PTR_TO_CTX; 11347 11348 if (is_kfunc_arg_nullable(meta->btf, &args[arg]) && bpf_register_is_null(reg) && 11349 !arg_mem_size) 11350 return KF_ARG_PTR_TO_NULL; 11351 11352 if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg])) 11353 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11354 11355 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg])) 11356 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11357 11358 if (is_kfunc_arg_dynptr(meta->btf, &args[arg])) 11359 return KF_ARG_PTR_TO_DYNPTR; 11360 11361 if (is_kfunc_arg_iter(meta, arg, &args[arg])) 11362 return KF_ARG_PTR_TO_ITER; 11363 11364 if (is_kfunc_arg_list_head(meta->btf, &args[arg])) 11365 return KF_ARG_PTR_TO_LIST_HEAD; 11366 11367 if (is_kfunc_arg_list_node(meta->btf, &args[arg])) 11368 return KF_ARG_PTR_TO_LIST_NODE; 11369 11370 if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg])) 11371 return KF_ARG_PTR_TO_RB_ROOT; 11372 11373 if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg])) 11374 return KF_ARG_PTR_TO_RB_NODE; 11375 11376 if (is_kfunc_arg_const_str(meta->btf, &args[arg])) 11377 return KF_ARG_PTR_TO_CONST_STR; 11378 11379 if (is_kfunc_arg_map(meta->btf, &args[arg])) 11380 return KF_ARG_PTR_TO_MAP; 11381 11382 if (is_kfunc_arg_wq(meta->btf, &args[arg])) 11383 return KF_ARG_PTR_TO_WORKQUEUE; 11384 11385 if (is_kfunc_arg_timer(meta->btf, &args[arg])) 11386 return KF_ARG_PTR_TO_TIMER; 11387 11388 if (is_kfunc_arg_task_work(meta->btf, &args[arg])) 11389 return KF_ARG_PTR_TO_TASK_WORK; 11390 11391 if (is_kfunc_arg_irq_flag(meta->btf, &args[arg])) 11392 return KF_ARG_PTR_TO_IRQ_FLAG; 11393 11394 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg])) 11395 return KF_ARG_PTR_TO_RES_SPIN_LOCK; 11396 11397 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11398 if (!btf_type_is_struct(ref_t)) { 11399 verbose(env, "kernel function %s %s pointer type %s %s is not supported\n", 11400 meta->func_name, reg_arg_name(env, argno), 11401 btf_type_str(ref_t), ref_tname); 11402 return -EINVAL; 11403 } 11404 return KF_ARG_PTR_TO_BTF_ID; 11405 } 11406 11407 if (is_kfunc_arg_callback(env, meta->btf, &args[arg])) 11408 return KF_ARG_PTR_TO_CALLBACK; 11409 11410 /* This is the catch all argument type of register types supported by 11411 * check_helper_mem_access. However, we only allow when argument type is 11412 * pointer to scalar, or struct composed (recursively) of scalars. When 11413 * arg_mem_size is true, the pointer can be void *. 11414 */ 11415 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11416 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11417 verbose(env, "%s pointer type %s %s must point to %sscalar, or struct with scalar\n", 11418 reg_arg_name(env, argno), 11419 btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11420 return -EINVAL; 11421 } 11422 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11423 } 11424 11425 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11426 struct bpf_reg_state *reg, 11427 const struct btf_type *ref_t, 11428 const char *ref_tname, u32 ref_id, 11429 struct bpf_call_arg_meta *meta, 11430 int arg, argno_t argno) 11431 { 11432 const struct btf_type *reg_ref_t; 11433 bool strict_type_match = false; 11434 const struct btf *reg_btf; 11435 const char *reg_ref_tname; 11436 bool taking_projection; 11437 bool struct_same; 11438 u32 reg_ref_id; 11439 11440 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11441 reg_btf = reg->btf; 11442 reg_ref_id = reg->btf_id; 11443 } else { 11444 reg_btf = btf_vmlinux; 11445 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11446 } 11447 11448 /* Enforce strict type matching for calls to kfuncs that are acquiring 11449 * or releasing a reference, or are no-cast aliases. We do _not_ 11450 * enforce strict matching for kfuncs by default, 11451 * as we want to enable BPF programs to pass types that are bitwise 11452 * equivalent without forcing them to explicitly cast with something 11453 * like bpf_cast_to_kern_ctx(). 11454 * 11455 * For example, say we had a type like the following: 11456 * 11457 * struct bpf_cpumask { 11458 * cpumask_t cpumask; 11459 * refcount_t usage; 11460 * }; 11461 * 11462 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11463 * to a struct cpumask, so it would be safe to pass a struct 11464 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11465 * 11466 * The philosophy here is similar to how we allow scalars of different 11467 * types to be passed to kfuncs as long as the size is the same. The 11468 * only difference here is that we're simply allowing 11469 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11470 * resolve types. 11471 */ 11472 if ((is_kfunc_release(meta) && reg_is_referenced(env, reg)) || 11473 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11474 strict_type_match = true; 11475 11476 WARN_ON_ONCE(is_kfunc_release(meta) && !tnum_is_const(reg->var_off)); 11477 11478 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11479 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11480 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->var_off.value, 11481 meta->btf, ref_id, strict_type_match, 11482 !type_is_alloc(reg->type)); 11483 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11484 * actually use it -- it must cast to the underlying type. So we allow 11485 * caller to pass in the underlying type. 11486 */ 11487 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11488 if (!taking_projection && !struct_same) { 11489 verbose(env, "kernel function %s %s expected pointer to %s %s but %s has a pointer to %s %s\n", 11490 meta->func_name, reg_arg_name(env, argno), 11491 btf_type_str(ref_t), ref_tname, reg_arg_name(env, argno), 11492 btf_type_str(reg_ref_t), reg_ref_tname); 11493 return -EINVAL; 11494 } 11495 return 0; 11496 } 11497 11498 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 11499 struct bpf_call_arg_meta *meta) 11500 { 11501 int err, spi, kfunc_class = IRQ_NATIVE_KFUNC; 11502 bool irq_save; 11503 11504 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] || 11505 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) { 11506 irq_save = true; 11507 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 11508 kfunc_class = IRQ_LOCK_KFUNC; 11509 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] || 11510 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) { 11511 irq_save = false; 11512 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 11513 kfunc_class = IRQ_LOCK_KFUNC; 11514 } else { 11515 verifier_bug(env, "unknown irq flags kfunc"); 11516 return -EFAULT; 11517 } 11518 11519 if (irq_save) { 11520 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 11521 verbose(env, "expected uninitialized irq flag as %s\n", 11522 reg_arg_name(env, argno)); 11523 return -EINVAL; 11524 } 11525 11526 err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW, 11527 BPF_WRITE, -1, false, false); 11528 if (err) 11529 return err; 11530 11531 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 11532 if (err) 11533 return err; 11534 } else { 11535 err = is_irq_flag_reg_valid_init(env, reg); 11536 if (err) { 11537 verbose(env, "expected an initialized irq flag as %s\n", 11538 reg_arg_name(env, argno)); 11539 return err; 11540 } 11541 11542 spi = irq_flag_get_spi(env, reg); 11543 if (spi < 0) 11544 return spi; 11545 11546 mark_stack_slots_scratched(env, spi, 1); 11547 11548 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 11549 if (err) 11550 return err; 11551 } 11552 return 0; 11553 } 11554 11555 11556 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11557 { 11558 struct btf_record *rec = reg_btf_record(reg); 11559 11560 if (!env->cur_state->active_locks) { 11561 verifier_bug(env, "%s w/o active lock", __func__); 11562 return -EFAULT; 11563 } 11564 11565 if (type_flag(reg->type) & NON_OWN_REF) { 11566 verifier_bug(env, "NON_OWN_REF already set"); 11567 return -EFAULT; 11568 } 11569 11570 reg->type |= NON_OWN_REF; 11571 if (rec->refcount_off >= 0) 11572 reg->type |= MEM_RCU; 11573 11574 return 0; 11575 } 11576 11577 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id) 11578 { 11579 struct bpf_func_state *unused; 11580 struct bpf_reg_state *reg; 11581 11582 WARN_ON_ONCE(release_reference_nomark(env->cur_state, id)); 11583 11584 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11585 if (reg->id == id) { 11586 reg->id = 0; 11587 ref_set_non_owning(env, reg); 11588 } 11589 })); 11590 11591 return; 11592 } 11593 11594 /* Implementation details: 11595 * 11596 * Each register points to some region of memory, which we define as an 11597 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11598 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11599 * allocation. The lock and the data it protects are colocated in the same 11600 * memory region. 11601 * 11602 * Hence, everytime a register holds a pointer value pointing to such 11603 * allocation, the verifier preserves a unique reg->id for it. 11604 * 11605 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11606 * bpf_spin_lock is called. 11607 * 11608 * To enable this, lock state in the verifier captures two values: 11609 * active_lock.ptr = Register's type specific pointer 11610 * active_lock.id = A unique ID for each register pointer value 11611 * 11612 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11613 * supported register types. 11614 * 11615 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11616 * allocated objects is the reg->btf pointer. 11617 * 11618 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11619 * can establish the provenance of the map value statically for each distinct 11620 * lookup into such maps. They always contain a single map value hence unique 11621 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11622 * 11623 * So, in case of global variables, they use array maps with max_entries = 1, 11624 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11625 * into the same map value as max_entries is 1, as described above). 11626 * 11627 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11628 * outer map pointer (in verifier context), but each lookup into an inner map 11629 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11630 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11631 * will get different reg->id assigned to each lookup, hence different 11632 * active_lock.id. 11633 * 11634 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11635 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11636 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11637 */ 11638 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11639 { 11640 struct bpf_reference_state *s; 11641 void *ptr; 11642 u32 id; 11643 11644 switch ((int)reg->type) { 11645 case PTR_TO_MAP_VALUE: 11646 ptr = reg->map_ptr; 11647 break; 11648 case PTR_TO_BTF_ID | MEM_ALLOC: 11649 ptr = reg->btf; 11650 break; 11651 default: 11652 verifier_bug(env, "unknown reg type for lock check"); 11653 return -EFAULT; 11654 } 11655 id = reg->id; 11656 11657 if (!env->cur_state->active_locks) 11658 return -EINVAL; 11659 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 11660 if (!s) { 11661 verbose(env, "held lock and object are not in the same allocation\n"); 11662 return -EINVAL; 11663 } 11664 return 0; 11665 } 11666 11667 static bool is_bpf_list_api_kfunc(u32 btf_id) 11668 { 11669 return is_bpf_list_push_kfunc(btf_id) || 11670 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11671 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 11672 btf_id == special_kfunc_list[KF_bpf_list_del] || 11673 btf_id == special_kfunc_list[KF_bpf_list_front] || 11674 btf_id == special_kfunc_list[KF_bpf_list_back] || 11675 btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11676 btf_id == special_kfunc_list[KF_bpf_list_is_last] || 11677 btf_id == special_kfunc_list[KF_bpf_list_empty]; 11678 } 11679 11680 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11681 { 11682 return is_bpf_rbtree_add_kfunc(btf_id) || 11683 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11684 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 11685 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 11686 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11687 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 11688 } 11689 11690 static bool is_bpf_iter_num_api_kfunc(u32 btf_id) 11691 { 11692 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] || 11693 btf_id == special_kfunc_list[KF_bpf_iter_num_next] || 11694 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy]; 11695 } 11696 11697 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11698 { 11699 return is_bpf_list_api_kfunc(btf_id) || 11700 is_bpf_rbtree_api_kfunc(btf_id) || 11701 is_bpf_refcount_acquire_kfunc(btf_id); 11702 } 11703 11704 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id) 11705 { 11706 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 11707 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 11708 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 11709 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]; 11710 } 11711 11712 static bool is_bpf_arena_kfunc(u32 btf_id) 11713 { 11714 return btf_id == special_kfunc_list[KF_bpf_arena_alloc_pages] || 11715 btf_id == special_kfunc_list[KF_bpf_arena_free_pages] || 11716 btf_id == special_kfunc_list[KF_bpf_arena_reserve_pages]; 11717 } 11718 11719 static bool is_bpf_stream_kfunc(u32 btf_id) 11720 { 11721 return btf_id == special_kfunc_list[KF_bpf_stream_vprintk] || 11722 btf_id == special_kfunc_list[KF_bpf_stream_print_stack]; 11723 } 11724 11725 static bool kfunc_spin_allowed(u32 btf_id) 11726 { 11727 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) || 11728 is_bpf_res_spin_lock_kfunc(btf_id) || is_bpf_arena_kfunc(btf_id) || 11729 is_bpf_stream_kfunc(btf_id); 11730 } 11731 11732 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11733 { 11734 return is_bpf_rbtree_add_kfunc(btf_id); 11735 } 11736 11737 static bool is_async_callback_calling_kfunc(u32 btf_id) 11738 { 11739 return is_bpf_wq_set_callback_kfunc(btf_id) || 11740 is_task_work_add_kfunc(btf_id); 11741 } 11742 11743 bool bpf_is_throw_kfunc(struct bpf_insn *insn) 11744 { 11745 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11746 insn->imm == special_kfunc_list[KF_bpf_throw]; 11747 } 11748 11749 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id) 11750 { 11751 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback]; 11752 } 11753 11754 static bool is_callback_calling_kfunc(u32 btf_id) 11755 { 11756 return is_sync_callback_calling_kfunc(btf_id) || 11757 is_async_callback_calling_kfunc(btf_id); 11758 } 11759 11760 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11761 { 11762 return is_bpf_rbtree_api_kfunc(btf_id); 11763 } 11764 11765 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11766 enum btf_field_type head_field_type, 11767 u32 kfunc_btf_id) 11768 { 11769 bool ret; 11770 11771 switch (head_field_type) { 11772 case BPF_LIST_HEAD: 11773 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11774 break; 11775 case BPF_RB_ROOT: 11776 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11777 break; 11778 default: 11779 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11780 btf_field_type_name(head_field_type)); 11781 return false; 11782 } 11783 11784 if (!ret) 11785 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11786 btf_field_type_name(head_field_type)); 11787 return ret; 11788 } 11789 11790 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11791 enum btf_field_type node_field_type, 11792 u32 kfunc_btf_id) 11793 { 11794 bool ret; 11795 11796 switch (node_field_type) { 11797 case BPF_LIST_NODE: 11798 ret = is_bpf_list_push_kfunc(kfunc_btf_id) || 11799 kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] || 11800 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11801 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last]; 11802 break; 11803 case BPF_RB_NODE: 11804 ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) || 11805 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11806 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11807 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 11808 break; 11809 default: 11810 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11811 btf_field_type_name(node_field_type)); 11812 return false; 11813 } 11814 11815 if (!ret) 11816 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11817 btf_field_type_name(node_field_type)); 11818 return ret; 11819 } 11820 11821 static int 11822 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11823 struct bpf_reg_state *reg, argno_t argno, 11824 struct bpf_call_arg_meta *meta, 11825 enum btf_field_type head_field_type, 11826 struct btf_field **head_field) 11827 { 11828 const char *head_type_name; 11829 struct btf_field *field; 11830 struct btf_record *rec; 11831 u32 head_off; 11832 11833 if (meta->btf != btf_vmlinux) { 11834 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11835 return -EFAULT; 11836 } 11837 11838 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11839 return -EFAULT; 11840 11841 head_type_name = btf_field_type_name(head_field_type); 11842 if (!tnum_is_const(reg->var_off)) { 11843 verbose(env, 11844 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11845 reg_arg_name(env, argno), head_type_name); 11846 return -EINVAL; 11847 } 11848 11849 rec = reg_btf_record(reg); 11850 head_off = reg->var_off.value; 11851 field = btf_record_find(rec, head_off, head_field_type); 11852 if (!field) { 11853 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11854 return -EINVAL; 11855 } 11856 11857 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11858 if (check_reg_allocation_locked(env, reg)) { 11859 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11860 rec->spin_lock_off, head_type_name); 11861 return -EINVAL; 11862 } 11863 11864 if (*head_field) { 11865 verifier_bug(env, "repeating %s arg", head_type_name); 11866 return -EFAULT; 11867 } 11868 *head_field = field; 11869 return 0; 11870 } 11871 11872 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11873 struct bpf_reg_state *reg, argno_t argno, 11874 struct bpf_call_arg_meta *meta) 11875 { 11876 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD, 11877 &meta->arg_list_head.field); 11878 } 11879 11880 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11881 struct bpf_reg_state *reg, argno_t argno, 11882 struct bpf_call_arg_meta *meta) 11883 { 11884 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT, 11885 &meta->arg_rbtree_root.field); 11886 } 11887 11888 static int 11889 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11890 struct bpf_reg_state *reg, argno_t argno, 11891 struct bpf_call_arg_meta *meta, 11892 enum btf_field_type head_field_type, 11893 enum btf_field_type node_field_type, 11894 struct btf_field **node_field) 11895 { 11896 const char *node_type_name; 11897 const struct btf_type *et, *t; 11898 struct btf_field *field; 11899 u32 node_off; 11900 11901 if (meta->btf != btf_vmlinux) { 11902 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11903 return -EFAULT; 11904 } 11905 11906 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11907 return -EFAULT; 11908 11909 node_type_name = btf_field_type_name(node_field_type); 11910 if (!tnum_is_const(reg->var_off)) { 11911 verbose(env, 11912 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11913 reg_arg_name(env, argno), node_type_name); 11914 return -EINVAL; 11915 } 11916 11917 node_off = reg->var_off.value; 11918 field = reg_find_field_offset(reg, node_off, node_field_type); 11919 if (!field) { 11920 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11921 return -EINVAL; 11922 } 11923 11924 field = *node_field; 11925 11926 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11927 t = btf_type_by_id(reg->btf, reg->btf_id); 11928 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11929 field->graph_root.value_btf_id, true, 11930 !type_is_alloc(reg->type))) { 11931 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11932 "in struct %s, but arg is at offset=%d in struct %s\n", 11933 btf_field_type_name(head_field_type), 11934 btf_field_type_name(node_field_type), 11935 field->graph_root.node_offset, 11936 btf_name_by_offset(field->graph_root.btf, et->name_off), 11937 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11938 return -EINVAL; 11939 } 11940 meta->arg_btf = reg->btf; 11941 meta->arg_btf_id = reg->btf_id; 11942 11943 if (node_off != field->graph_root.node_offset) { 11944 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11945 node_off, btf_field_type_name(node_field_type), 11946 field->graph_root.node_offset, 11947 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11948 return -EINVAL; 11949 } 11950 11951 return 0; 11952 } 11953 11954 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11955 struct bpf_reg_state *reg, argno_t argno, 11956 struct bpf_call_arg_meta *meta) 11957 { 11958 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 11959 BPF_LIST_HEAD, BPF_LIST_NODE, 11960 &meta->arg_list_head.field); 11961 } 11962 11963 static int process_kf_arg_ptr_to_rbtree_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_RB_ROOT, BPF_RB_NODE, 11969 &meta->arg_rbtree_root.field); 11970 } 11971 11972 /* 11973 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11974 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11975 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11976 * them can only be attached to some specific hook points. 11977 */ 11978 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11979 { 11980 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11981 11982 switch (prog_type) { 11983 case BPF_PROG_TYPE_LSM: 11984 return true; 11985 case BPF_PROG_TYPE_TRACING: 11986 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11987 return true; 11988 fallthrough; 11989 default: 11990 return in_sleepable(env); 11991 } 11992 } 11993 11994 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 11995 int insn_idx) 11996 { 11997 const char *func_name = meta->func_name, *ref_tname; 11998 struct bpf_func_state *caller = cur_func(env); 11999 struct bpf_reg_state *regs = cur_regs(env); 12000 const struct btf *btf = meta->btf; 12001 const struct btf_param *args; 12002 struct btf_record *rec; 12003 u32 i, nargs; 12004 int ret; 12005 12006 args = (const struct btf_param *)(meta->func_proto + 1); 12007 nargs = btf_type_vlen(meta->func_proto); 12008 if (nargs > MAX_BPF_FUNC_ARGS) { 12009 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 12010 MAX_BPF_FUNC_ARGS); 12011 return -EINVAL; 12012 } 12013 if (nargs > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) { 12014 verbose(env, "JIT does not support kfunc %s() with %d args\n", 12015 func_name, nargs); 12016 return -ENOTSUPP; 12017 } 12018 12019 ret = check_outgoing_stack_args(env, caller, nargs); 12020 if (ret) 12021 return ret; 12022 12023 /* Check that BTF function arguments match actual types that the 12024 * verifier sees. 12025 */ 12026 for (i = 0; i < nargs; i++) { 12027 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 12028 const struct btf_type *t, *ref_t, *resolve_ret; 12029 enum bpf_arg_type arg_type = ARG_DONTCARE; 12030 argno_t argno = argno_from_arg(i + 1); 12031 int regno = reg_from_argno(argno); 12032 bool btf_id_fixed_off_ok = true; 12033 u32 ref_id, type_size; 12034 bool is_ret_buf_sz = false; 12035 int kf_arg_type; 12036 12037 if (is_kfunc_arg_prog_aux(btf, &args[i])) { 12038 /* Reject repeated use bpf_prog_aux */ 12039 if (meta->arg_prog) { 12040 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc"); 12041 return -EFAULT; 12042 } 12043 if (regno < 0) { 12044 verbose(env, "%s prog->aux cannot be a stack argument\n", 12045 reg_arg_name(env, argno)); 12046 return -EINVAL; 12047 } 12048 meta->arg_prog = true; 12049 cur_aux(env)->arg_prog = regno; 12050 continue; 12051 } 12052 12053 if (is_kfunc_arg_ignore(btf, &args[i]) || is_kfunc_arg_implicit(meta, i)) 12054 continue; 12055 12056 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 12057 12058 if (btf_type_is_scalar(t)) { 12059 if (reg->type != SCALAR_VALUE) { 12060 verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno)); 12061 return -EINVAL; 12062 } 12063 12064 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 12065 if (meta->arg_constant.found) { 12066 verifier_bug(env, "only one constant argument permitted"); 12067 return -EFAULT; 12068 } 12069 if (!tnum_is_const(reg->var_off)) { 12070 verbose(env, "%s must be a known constant\n", 12071 reg_arg_name(env, argno)); 12072 return -EINVAL; 12073 } 12074 if (regno >= 0) 12075 ret = mark_chain_precision(env, regno); 12076 else 12077 ret = mark_stack_arg_precision(env, i); 12078 if (ret < 0) 12079 return ret; 12080 meta->arg_constant.found = true; 12081 meta->arg_constant.value = reg->var_off.value; 12082 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 12083 meta->r0_rdonly = true; 12084 is_ret_buf_sz = true; 12085 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 12086 is_ret_buf_sz = true; 12087 } 12088 12089 if (is_ret_buf_sz) { 12090 ret = process_const_alloc_mem_size(env, reg, argno, &meta->ret_mem); 12091 if (ret < 0) 12092 return ret; 12093 } 12094 continue; 12095 } 12096 12097 if (!btf_type_is_ptr(t)) { 12098 verbose(env, "Unrecognized %s type %s\n", 12099 reg_arg_name(env, argno), btf_type_str(t)); 12100 return -EINVAL; 12101 } 12102 12103 if ((bpf_register_is_null(reg) || type_may_be_null(reg->type)) && 12104 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 12105 verbose(env, "Possibly NULL pointer passed to trusted %s\n", 12106 reg_arg_name(env, argno)); 12107 return -EACCES; 12108 } 12109 12110 if (regno == meta->release_regno && !is_kfunc_arg_dynptr(meta->btf, &args[i]) && 12111 !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) { 12112 verbose(env, "release kfunc %s expects referenced PTR_TO_BTF_ID passed to %s\n", 12113 func_name, reg_arg_name(env, argno)); 12114 return -EINVAL; 12115 } 12116 12117 if (reg_is_referenced(env, reg)) 12118 update_ref_obj(&meta->ref_obj, reg); 12119 12120 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 12121 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12122 12123 kf_arg_type = get_kfunc_ptr_arg_type(env, caller, regs, meta, t, ref_t, ref_tname, 12124 args, i, nargs, argno, reg); 12125 if (kf_arg_type < 0) 12126 return kf_arg_type; 12127 12128 switch (kf_arg_type) { 12129 case KF_ARG_PTR_TO_NULL: 12130 continue; 12131 case KF_ARG_PTR_TO_MAP: 12132 if (!reg->map_ptr) { 12133 verbose(env, "pointer in %s isn't map pointer\n", 12134 reg_arg_name(env, argno)); 12135 return -EINVAL; 12136 } 12137 if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 || 12138 reg->map_ptr->record->task_work_off >= 0)) { 12139 /* Use map_uid (which is unique id of inner map) to reject: 12140 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 12141 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 12142 * if (inner_map1 && inner_map2) { 12143 * wq = bpf_map_lookup_elem(inner_map1); 12144 * if (wq) 12145 * // mismatch would have been allowed 12146 * bpf_wq_init(wq, inner_map2); 12147 * } 12148 * 12149 * Comparing map_ptr is enough to distinguish normal and outer maps. 12150 */ 12151 if (meta->map.ptr != reg->map_ptr || 12152 meta->map.uid != reg->map_uid) { 12153 if (reg->map_ptr->record->task_work_off >= 0) { 12154 verbose(env, 12155 "bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n", 12156 meta->map.uid, reg->map_uid); 12157 return -EINVAL; 12158 } 12159 verbose(env, 12160 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 12161 meta->map.uid, reg->map_uid); 12162 return -EINVAL; 12163 } 12164 } 12165 meta->map.ptr = reg->map_ptr; 12166 meta->map.uid = reg->map_uid; 12167 fallthrough; 12168 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12169 case KF_ARG_PTR_TO_BTF_ID: 12170 if (!is_trusted_reg(env, reg)) { 12171 if (!is_kfunc_rcu(meta)) { 12172 verbose(env, "%s must be referenced or trusted\n", 12173 reg_arg_name(env, argno)); 12174 return -EINVAL; 12175 } 12176 if (!is_rcu_reg(reg)) { 12177 verbose(env, "%s must be a rcu pointer\n", 12178 reg_arg_name(env, argno)); 12179 return -EINVAL; 12180 } 12181 } 12182 fallthrough; 12183 case KF_ARG_PTR_TO_ITER: 12184 case KF_ARG_PTR_TO_LIST_HEAD: 12185 case KF_ARG_PTR_TO_LIST_NODE: 12186 case KF_ARG_PTR_TO_RB_ROOT: 12187 case KF_ARG_PTR_TO_RB_NODE: 12188 case KF_ARG_PTR_TO_MEM: 12189 case KF_ARG_PTR_TO_MEM_SIZE: 12190 case KF_ARG_PTR_TO_CALLBACK: 12191 case KF_ARG_PTR_TO_CONST_STR: 12192 case KF_ARG_PTR_TO_WORKQUEUE: 12193 case KF_ARG_PTR_TO_TIMER: 12194 case KF_ARG_PTR_TO_TASK_WORK: 12195 case KF_ARG_PTR_TO_IRQ_FLAG: 12196 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12197 break; 12198 case KF_ARG_PTR_TO_DYNPTR: 12199 arg_type = ARG_PTR_TO_DYNPTR; 12200 break; 12201 case KF_ARG_PTR_TO_CTX: 12202 arg_type = ARG_PTR_TO_CTX; 12203 break; 12204 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12205 arg_type = ARG_PTR_TO_BTF_ID; 12206 btf_id_fixed_off_ok = false; 12207 break; 12208 default: 12209 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type); 12210 return -EFAULT; 12211 } 12212 12213 if (regno == meta->release_regno) 12214 arg_type |= OBJ_RELEASE; 12215 ret = __check_func_arg_reg_off(env, reg, argno, arg_type, 12216 btf_id_fixed_off_ok); 12217 if (ret < 0) 12218 return ret; 12219 12220 switch (kf_arg_type) { 12221 case KF_ARG_PTR_TO_CTX: 12222 if (reg->type != PTR_TO_CTX) { 12223 verbose(env, "%s expected pointer to ctx, but got %s\n", 12224 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 12225 return -EINVAL; 12226 } 12227 12228 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12229 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 12230 if (ret < 0) 12231 return -EINVAL; 12232 meta->ret_btf_id = ret; 12233 } 12234 break; 12235 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12236 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 12237 if (!is_bpf_obj_drop_kfunc(meta->func_id)) { 12238 verbose(env, "%s expected for bpf_obj_drop()\n", 12239 reg_arg_name(env, argno)); 12240 return -EINVAL; 12241 } 12242 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 12243 if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) { 12244 verbose(env, "%s expected for bpf_percpu_obj_drop()\n", 12245 reg_arg_name(env, argno)); 12246 return -EINVAL; 12247 } 12248 } else { 12249 verbose(env, "%s expected pointer to allocated object\n", 12250 reg_arg_name(env, argno)); 12251 return -EINVAL; 12252 } 12253 if (!reg_is_referenced(env, reg)) { 12254 verbose(env, "allocated object must be referenced\n"); 12255 return -EINVAL; 12256 } 12257 if (meta->btf == btf_vmlinux) { 12258 meta->arg_btf = reg->btf; 12259 meta->arg_btf_id = reg->btf_id; 12260 } 12261 break; 12262 case KF_ARG_PTR_TO_DYNPTR: 12263 { 12264 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 12265 12266 if (is_kfunc_arg_uninit(btf, &args[i])) 12267 dynptr_arg_type |= MEM_UNINIT; 12268 12269 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 12270 dynptr_arg_type |= DYNPTR_TYPE_SKB; 12271 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 12272 dynptr_arg_type |= DYNPTR_TYPE_XDP; 12273 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) { 12274 dynptr_arg_type |= DYNPTR_TYPE_SKB_META; 12275 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 12276 dynptr_arg_type |= DYNPTR_TYPE_FILE; 12277 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) { 12278 dynptr_arg_type |= DYNPTR_TYPE_FILE | OBJ_RELEASE; 12279 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 12280 (dynptr_arg_type & MEM_UNINIT)) { 12281 enum bpf_dynptr_type parent_type = meta->dynptr.type; 12282 12283 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 12284 verifier_bug(env, "no dynptr type for parent of clone"); 12285 return -EFAULT; 12286 } 12287 12288 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12289 } 12290 12291 ret = process_dynptr_func(env, reg, argno, insn_idx, dynptr_arg_type, 12292 &meta->ref_obj, &meta->dynptr); 12293 if (ret < 0) 12294 return ret; 12295 break; 12296 } 12297 case KF_ARG_PTR_TO_ITER: 12298 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12299 if (!check_css_task_iter_allowlist(env)) { 12300 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12301 return -EINVAL; 12302 } 12303 } 12304 ret = process_iter_arg(env, reg, argno, insn_idx, meta); 12305 if (ret < 0) 12306 return ret; 12307 break; 12308 case KF_ARG_PTR_TO_LIST_HEAD: 12309 if (reg->type != PTR_TO_MAP_VALUE && 12310 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12311 verbose(env, "%s expected pointer to map value or allocated object\n", 12312 reg_arg_name(env, argno)); 12313 return -EINVAL; 12314 } 12315 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 12316 !reg_is_referenced(env, reg)) { 12317 verbose(env, "allocated object must be referenced\n"); 12318 return -EINVAL; 12319 } 12320 ret = process_kf_arg_ptr_to_list_head(env, reg, argno, meta); 12321 if (ret < 0) 12322 return ret; 12323 break; 12324 case KF_ARG_PTR_TO_RB_ROOT: 12325 if (reg->type != PTR_TO_MAP_VALUE && 12326 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12327 verbose(env, "%s expected pointer to map value or allocated object\n", 12328 reg_arg_name(env, argno)); 12329 return -EINVAL; 12330 } 12331 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 12332 !reg_is_referenced(env, reg)) { 12333 verbose(env, "allocated object must be referenced\n"); 12334 return -EINVAL; 12335 } 12336 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta); 12337 if (ret < 0) 12338 return ret; 12339 break; 12340 case KF_ARG_PTR_TO_LIST_NODE: 12341 if (is_kfunc_arg_nonown_allowed(btf, &args[i]) && 12342 type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg)) { 12343 /* Allow bpf_list_front/back return value for 12344 * __nonown_allowed list-node arguments. 12345 */ 12346 goto check_ok; 12347 } 12348 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12349 verbose(env, "%s expected pointer to allocated object\n", 12350 reg_arg_name(env, argno)); 12351 return -EINVAL; 12352 } 12353 if (!reg_is_referenced(env, reg)) { 12354 verbose(env, "allocated object must be referenced\n"); 12355 return -EINVAL; 12356 } 12357 check_ok: 12358 ret = process_kf_arg_ptr_to_list_node(env, reg, argno, meta); 12359 if (ret < 0) 12360 return ret; 12361 break; 12362 case KF_ARG_PTR_TO_RB_NODE: 12363 if (is_bpf_rbtree_add_kfunc(meta->func_id)) { 12364 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12365 verbose(env, "%s expected pointer to allocated object\n", 12366 reg_arg_name(env, argno)); 12367 return -EINVAL; 12368 } 12369 if (!reg_is_referenced(env, reg)) { 12370 verbose(env, "allocated object must be referenced\n"); 12371 return -EINVAL; 12372 } 12373 } else { 12374 if (!type_is_non_owning_ref(reg->type) && 12375 !reg_is_referenced(env, reg)) { 12376 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name); 12377 return -EINVAL; 12378 } 12379 if (in_rbtree_lock_required_cb(env)) { 12380 verbose(env, "%s not allowed in rbtree cb\n", func_name); 12381 return -EINVAL; 12382 } 12383 } 12384 12385 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta); 12386 if (ret < 0) 12387 return ret; 12388 break; 12389 case KF_ARG_PTR_TO_MAP: 12390 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12391 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12392 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12393 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12394 fallthrough; 12395 case KF_ARG_PTR_TO_BTF_ID: 12396 /* Only base_type is checked, further checks are done here */ 12397 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12398 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12399 !reg2btf_ids[base_type(reg->type)]) { 12400 verbose(env, "%s is %s ", reg_arg_name(env, argno), 12401 reg_type_str(env, reg->type)); 12402 verbose(env, "expected %s or socket\n", 12403 reg_type_str(env, base_type(reg->type) | 12404 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12405 return -EINVAL; 12406 } 12407 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i, argno); 12408 if (ret < 0) 12409 return ret; 12410 break; 12411 case KF_ARG_PTR_TO_MEM: 12412 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12413 if (IS_ERR(resolve_ret)) { 12414 verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n", 12415 reg_arg_name(env, argno), btf_type_str(ref_t), 12416 ref_tname, PTR_ERR(resolve_ret)); 12417 return -EINVAL; 12418 } 12419 ret = check_mem_reg(env, reg, argno, type_size); 12420 if (ret < 0) 12421 return ret; 12422 break; 12423 case KF_ARG_PTR_TO_MEM_SIZE: 12424 { 12425 struct bpf_reg_state *buff_reg = reg; 12426 const struct btf_param *buff_arg = &args[i]; 12427 struct bpf_reg_state *size_reg = get_func_arg_reg(caller, regs, i + 1); 12428 const struct btf_param *size_arg = &args[i + 1]; 12429 argno_t next_argno = argno_from_arg(i + 2); 12430 12431 if (!bpf_register_is_null(buff_reg) || !is_kfunc_arg_nullable(meta->btf, buff_arg)) { 12432 ret = check_kfunc_mem_size_reg(env, buff_reg, size_reg, 12433 argno, next_argno); 12434 if (ret < 0) { 12435 verbose(env, "%s and ", reg_arg_name(env, argno)); 12436 verbose(env, "%s memory, len pair leads to invalid memory access\n", 12437 reg_arg_name(env, next_argno)); 12438 return ret; 12439 } 12440 } 12441 12442 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12443 if (meta->arg_constant.found) { 12444 verifier_bug(env, "only one constant argument permitted"); 12445 return -EFAULT; 12446 } 12447 if (!tnum_is_const(size_reg->var_off)) { 12448 verbose(env, "%s must be a known constant\n", 12449 reg_arg_name(env, next_argno)); 12450 return -EINVAL; 12451 } 12452 meta->arg_constant.found = true; 12453 meta->arg_constant.value = size_reg->var_off.value; 12454 } 12455 12456 /* Skip next '__sz' or '__szk' argument */ 12457 i++; 12458 break; 12459 } 12460 case KF_ARG_PTR_TO_CALLBACK: 12461 if (reg->type != PTR_TO_FUNC) { 12462 verbose(env, "%s expected pointer to func\n", reg_arg_name(env, argno)); 12463 return -EINVAL; 12464 } 12465 meta->subprogno = reg->subprogno; 12466 break; 12467 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12468 if (!type_is_ptr_alloc_obj(reg->type)) { 12469 verbose(env, "%s is neither owning or non-owning ref\n", 12470 reg_arg_name(env, argno)); 12471 return -EINVAL; 12472 } 12473 if (!type_is_non_owning_ref(reg->type)) 12474 meta->arg_owning_ref = true; 12475 12476 rec = reg_btf_record(reg); 12477 if (!rec) { 12478 verifier_bug(env, "Couldn't find btf_record"); 12479 return -EFAULT; 12480 } 12481 12482 if (rec->refcount_off < 0) { 12483 verbose(env, "%s doesn't point to a type with bpf_refcount field\n", 12484 reg_arg_name(env, argno)); 12485 return -EINVAL; 12486 } 12487 12488 meta->arg_btf = reg->btf; 12489 meta->arg_btf_id = reg->btf_id; 12490 break; 12491 case KF_ARG_PTR_TO_CONST_STR: 12492 if (reg->type != PTR_TO_MAP_VALUE) { 12493 verbose(env, "%s doesn't point to a const string\n", 12494 reg_arg_name(env, argno)); 12495 return -EINVAL; 12496 } 12497 ret = check_arg_const_str(env, reg, argno); 12498 if (ret) 12499 return ret; 12500 break; 12501 case KF_ARG_PTR_TO_WORKQUEUE: 12502 if (reg->type != PTR_TO_MAP_VALUE) { 12503 verbose(env, "%s doesn't point to a map value\n", 12504 reg_arg_name(env, argno)); 12505 return -EINVAL; 12506 } 12507 ret = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map); 12508 if (ret < 0) 12509 return ret; 12510 break; 12511 case KF_ARG_PTR_TO_TIMER: 12512 if (reg->type != PTR_TO_MAP_VALUE) { 12513 verbose(env, "%s doesn't point to a map value\n", 12514 reg_arg_name(env, argno)); 12515 return -EINVAL; 12516 } 12517 ret = process_timer_kfunc(env, reg, argno, meta); 12518 if (ret < 0) 12519 return ret; 12520 break; 12521 case KF_ARG_PTR_TO_TASK_WORK: 12522 if (reg->type != PTR_TO_MAP_VALUE) { 12523 verbose(env, "%s doesn't point to a map value\n", 12524 reg_arg_name(env, argno)); 12525 return -EINVAL; 12526 } 12527 ret = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map); 12528 if (ret < 0) 12529 return ret; 12530 break; 12531 case KF_ARG_PTR_TO_IRQ_FLAG: 12532 if (reg->type != PTR_TO_STACK) { 12533 verbose(env, "%s doesn't point to an irq flag on stack\n", 12534 reg_arg_name(env, argno)); 12535 return -EINVAL; 12536 } 12537 ret = process_irq_flag(env, reg, argno, meta); 12538 if (ret < 0) 12539 return ret; 12540 break; 12541 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12542 { 12543 int flags = PROCESS_RES_LOCK; 12544 12545 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12546 verbose(env, "%s doesn't point to map value or allocated object\n", 12547 reg_arg_name(env, argno)); 12548 return -EINVAL; 12549 } 12550 12551 if (!is_bpf_res_spin_lock_kfunc(meta->func_id)) 12552 return -EFAULT; 12553 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 12554 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 12555 flags |= PROCESS_SPIN_LOCK; 12556 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 12557 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 12558 flags |= PROCESS_LOCK_IRQ; 12559 ret = process_spin_lock(env, reg, argno, flags); 12560 if (ret < 0) 12561 return ret; 12562 break; 12563 } 12564 } 12565 } 12566 12567 return 0; 12568 } 12569 12570 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, 12571 s32 func_id, 12572 s16 offset, 12573 struct bpf_call_arg_meta *meta) 12574 { 12575 struct bpf_kfunc_meta kfunc; 12576 int err; 12577 12578 memset(meta, 0, sizeof(*meta)); 12579 12580 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 12581 if (err) 12582 return err; 12583 12584 meta->btf = kfunc.btf; 12585 meta->func_id = kfunc.id; 12586 meta->func_proto = kfunc.proto; 12587 meta->func_name = kfunc.name; 12588 12589 if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog)) 12590 return -EACCES; 12591 12592 meta->kfunc_flags = *kfunc.flags; 12593 12594 /* Only support release referenced argument passed by register */ 12595 if (is_kfunc_release(meta)) 12596 meta->release_regno = BPF_REG_1; 12597 12598 return 0; 12599 } 12600 12601 /* 12602 * Determine how many bytes a helper accesses through a stack pointer at 12603 * argument position @arg (0-based, corresponding to R1-R5). 12604 * 12605 * Returns: 12606 * > 0 known read access size in bytes 12607 * 0 doesn't read anything directly 12608 * S64_MIN unknown 12609 * < 0 known write access of (-return) bytes 12610 */ 12611 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12612 int arg, int insn_idx) 12613 { 12614 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12615 const struct bpf_func_proto *fn; 12616 enum bpf_arg_type at; 12617 s64 size; 12618 12619 if (bpf_get_helper_proto(env, insn->imm, &fn) < 0) 12620 return S64_MIN; 12621 12622 at = fn->arg_type[arg]; 12623 12624 switch (base_type(at)) { 12625 case ARG_PTR_TO_MAP_KEY: 12626 case ARG_PTR_TO_MAP_VALUE: { 12627 bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY; 12628 u64 val; 12629 int i, map_reg; 12630 12631 for (i = 0; i < arg; i++) { 12632 if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR) 12633 break; 12634 } 12635 if (i >= arg) 12636 goto scan_all_maps; 12637 12638 map_reg = BPF_REG_1 + i; 12639 12640 if (!(aux->const_reg_map_mask & BIT(map_reg))) 12641 goto scan_all_maps; 12642 12643 i = aux->const_reg_vals[map_reg]; 12644 if (i < env->used_map_cnt) { 12645 size = is_key ? env->used_maps[i]->key_size 12646 : env->used_maps[i]->value_size; 12647 goto out; 12648 } 12649 scan_all_maps: 12650 /* 12651 * Map pointer is not known at this call site (e.g. different 12652 * maps on merged paths). Conservatively return the largest 12653 * key_size or value_size across all maps used by the program. 12654 */ 12655 val = 0; 12656 for (i = 0; i < env->used_map_cnt; i++) { 12657 struct bpf_map *map = env->used_maps[i]; 12658 u32 sz = is_key ? map->key_size : map->value_size; 12659 12660 if (sz > val) 12661 val = sz; 12662 if (map->inner_map_meta) { 12663 sz = is_key ? map->inner_map_meta->key_size 12664 : map->inner_map_meta->value_size; 12665 if (sz > val) 12666 val = sz; 12667 } 12668 } 12669 if (!val) 12670 return S64_MIN; 12671 size = val; 12672 goto out; 12673 } 12674 case ARG_PTR_TO_MEM: 12675 if (at & MEM_FIXED_SIZE) { 12676 size = fn->arg_size[arg]; 12677 goto out; 12678 } 12679 if (arg + 1 < ARRAY_SIZE(fn->arg_type) && 12680 arg_type_is_mem_size(fn->arg_type[arg + 1])) { 12681 int size_reg = BPF_REG_1 + arg + 1; 12682 12683 if (aux->const_reg_mask & BIT(size_reg)) { 12684 size = (s64)aux->const_reg_vals[size_reg]; 12685 goto out; 12686 } 12687 /* 12688 * Size arg is const on each path but differs across merged 12689 * paths. MAX_BPF_STACK is a safe upper bound for reads. 12690 */ 12691 if (at & MEM_UNINIT) 12692 return 0; 12693 return MAX_BPF_STACK; 12694 } 12695 return S64_MIN; 12696 case ARG_PTR_TO_DYNPTR: 12697 size = BPF_DYNPTR_SIZE; 12698 break; 12699 case ARG_PTR_TO_STACK: 12700 /* 12701 * Only used by bpf_calls_callback() helpers. The helper itself 12702 * doesn't access stack. The callback subprog does and it's 12703 * analyzed separately. 12704 */ 12705 return 0; 12706 default: 12707 return S64_MIN; 12708 } 12709 out: 12710 /* 12711 * MEM_UNINIT args are write-only: the helper initializes the 12712 * buffer without reading it. 12713 */ 12714 if (at & MEM_UNINIT) 12715 return -size; 12716 return size; 12717 } 12718 12719 /* 12720 * Determine how many bytes a kfunc accesses through a stack pointer at 12721 * argument position @arg (0-based, corresponding to R1-R5). 12722 * 12723 * Returns: 12724 * > 0 known read access size in bytes 12725 * 0 doesn't access memory through that argument (ex: not a pointer) 12726 * S64_MIN unknown 12727 * < 0 known write access of (-return) bytes 12728 */ 12729 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12730 int arg, int insn_idx) 12731 { 12732 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12733 struct bpf_call_arg_meta meta; 12734 const struct btf_param *args; 12735 const struct btf_type *t, *ref_t; 12736 const struct btf *btf; 12737 u32 nargs, type_size; 12738 s64 size; 12739 12740 if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0) 12741 return S64_MIN; 12742 12743 btf = meta.btf; 12744 args = btf_params(meta.func_proto); 12745 nargs = btf_type_vlen(meta.func_proto); 12746 if (arg >= nargs) 12747 return 0; 12748 12749 t = btf_type_skip_modifiers(btf, args[arg].type, NULL); 12750 if (!btf_type_is_ptr(t)) 12751 return 0; 12752 12753 /* dynptr: fixed 16-byte on-stack representation */ 12754 if (is_kfunc_arg_dynptr(btf, &args[arg])) { 12755 size = BPF_DYNPTR_SIZE; 12756 goto out; 12757 } 12758 12759 /* ptr + __sz/__szk pair: size is in the next register */ 12760 if (arg + 1 < nargs && 12761 (btf_param_match_suffix(btf, &args[arg + 1], "__sz") || 12762 btf_param_match_suffix(btf, &args[arg + 1], "__szk"))) { 12763 int size_reg = BPF_REG_1 + arg + 1; 12764 12765 if (aux->const_reg_mask & BIT(size_reg)) { 12766 size = (s64)aux->const_reg_vals[size_reg]; 12767 goto out; 12768 } 12769 return MAX_BPF_STACK; 12770 } 12771 12772 /* fixed-size pointed-to type: resolve via BTF */ 12773 ref_t = btf_type_skip_modifiers(btf, t->type, NULL); 12774 if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) { 12775 size = type_size; 12776 goto out; 12777 } 12778 12779 return S64_MIN; 12780 out: 12781 /* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */ 12782 if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW) 12783 return -size; 12784 if (is_kfunc_arg_uninit(btf, &args[arg])) 12785 return -size; 12786 return size; 12787 } 12788 12789 /* check special kfuncs and return: 12790 * 1 - not fall-through to 'else' branch, continue verification 12791 * 0 - fall-through to 'else' branch 12792 * < 0 - not fall-through to 'else' branch, return error 12793 */ 12794 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 12795 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 12796 const struct btf_type *ptr_type, struct btf *desc_btf) 12797 { 12798 const struct btf_type *ret_t; 12799 int err = 0; 12800 12801 if (meta->btf != btf_vmlinux) 12802 return 0; 12803 12804 if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12805 struct btf_struct_meta *struct_meta; 12806 struct btf *ret_btf; 12807 u32 ret_btf_id; 12808 12809 if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set) 12810 return -ENOMEM; 12811 12812 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 12813 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12814 return -EINVAL; 12815 } 12816 12817 ret_btf = env->prog->aux->btf; 12818 ret_btf_id = meta->arg_constant.value; 12819 12820 /* This may be NULL due to user not supplying a BTF */ 12821 if (!ret_btf) { 12822 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12823 return -EINVAL; 12824 } 12825 12826 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12827 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12828 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12829 return -EINVAL; 12830 } 12831 12832 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12833 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12834 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12835 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12836 return -EINVAL; 12837 } 12838 12839 if (!bpf_global_percpu_ma_set) { 12840 mutex_lock(&bpf_percpu_ma_lock); 12841 if (!bpf_global_percpu_ma_set) { 12842 /* Charge memory allocated with bpf_global_percpu_ma to 12843 * root memcg. The obj_cgroup for root memcg is NULL. 12844 */ 12845 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12846 if (!err) 12847 bpf_global_percpu_ma_set = true; 12848 } 12849 mutex_unlock(&bpf_percpu_ma_lock); 12850 if (err) 12851 return err; 12852 } 12853 12854 mutex_lock(&bpf_percpu_ma_lock); 12855 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12856 mutex_unlock(&bpf_percpu_ma_lock); 12857 if (err) 12858 return err; 12859 } 12860 12861 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12862 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12863 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12864 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12865 return -EINVAL; 12866 } 12867 12868 if (struct_meta) { 12869 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12870 return -EINVAL; 12871 } 12872 } 12873 12874 mark_reg_known_zero(env, regs, BPF_REG_0); 12875 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12876 regs[BPF_REG_0].btf = ret_btf; 12877 regs[BPF_REG_0].btf_id = ret_btf_id; 12878 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) 12879 regs[BPF_REG_0].type |= MEM_PERCPU; 12880 12881 insn_aux->obj_new_size = ret_t->size; 12882 insn_aux->kptr_struct_meta = struct_meta; 12883 } else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) { 12884 mark_reg_known_zero(env, regs, BPF_REG_0); 12885 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12886 regs[BPF_REG_0].btf = meta->arg_btf; 12887 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 12888 12889 insn_aux->kptr_struct_meta = 12890 btf_find_struct_meta(meta->arg_btf, 12891 meta->arg_btf_id); 12892 } else if (is_list_node_type(ptr_type)) { 12893 struct btf_field *field = meta->arg_list_head.field; 12894 12895 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12896 } else if (is_rbtree_node_type(ptr_type)) { 12897 struct btf_field *field = meta->arg_rbtree_root.field; 12898 12899 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12900 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12901 mark_reg_known_zero(env, regs, BPF_REG_0); 12902 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12903 regs[BPF_REG_0].btf = desc_btf; 12904 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 12905 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12906 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 12907 if (!ret_t) { 12908 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n", 12909 meta->arg_constant.value); 12910 return -EINVAL; 12911 } else if (btf_type_is_struct(ret_t)) { 12912 mark_reg_known_zero(env, regs, BPF_REG_0); 12913 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12914 regs[BPF_REG_0].btf = desc_btf; 12915 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 12916 } else if (btf_type_is_void(ret_t)) { 12917 mark_reg_known_zero(env, regs, BPF_REG_0); 12918 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED; 12919 regs[BPF_REG_0].mem_size = 0; 12920 } else { 12921 verbose(env, 12922 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n"); 12923 return -EINVAL; 12924 } 12925 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12926 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12927 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type); 12928 12929 mark_reg_known_zero(env, regs, BPF_REG_0); 12930 12931 if (!meta->arg_constant.found) { 12932 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size"); 12933 return -EFAULT; 12934 } 12935 12936 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 12937 12938 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12939 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12940 12941 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12942 regs[BPF_REG_0].type |= MEM_RDONLY; 12943 } else { 12944 /* this will set env->seen_direct_write to true */ 12945 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12946 verbose(env, "the prog does not allow writes to packet data\n"); 12947 return -EINVAL; 12948 } 12949 } 12950 12951 if (!meta->dynptr.id) { 12952 verifier_bug(env, "no dynptr id"); 12953 return -EFAULT; 12954 } 12955 regs[BPF_REG_0].parent_id = meta->dynptr.id; 12956 } else { 12957 return 0; 12958 } 12959 12960 return 1; 12961 } 12962 12963 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12964 12965 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12966 int *insn_idx_p) 12967 { 12968 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12969 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12970 struct bpf_reg_state *regs = cur_regs(env); 12971 const char *func_name, *ptr_type_name; 12972 const struct btf_type *t, *ptr_type; 12973 struct bpf_call_arg_meta meta; 12974 struct bpf_insn_aux_data *insn_aux; 12975 int err, insn_idx = *insn_idx_p; 12976 const struct btf_param *args; 12977 u32 i, nargs, ptr_type_id; 12978 struct btf *desc_btf; 12979 int id; 12980 12981 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12982 if (!insn->imm) 12983 return 0; 12984 12985 err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta); 12986 if (err == -EACCES && meta.func_name) 12987 verbose(env, "calling kernel function %s is not allowed\n", meta.func_name); 12988 if (err) 12989 return err; 12990 desc_btf = meta.btf; 12991 func_name = meta.func_name; 12992 insn_aux = &env->insn_aux_data[insn_idx]; 12993 12994 insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta); 12995 12996 if (!insn->off && 12997 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 12998 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 12999 struct bpf_verifier_state *branch; 13000 struct bpf_reg_state *regs; 13001 13002 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 13003 if (IS_ERR(branch)) { 13004 verbose(env, "failed to push state for failed lock acquisition\n"); 13005 return PTR_ERR(branch); 13006 } 13007 13008 regs = branch->frame[branch->curframe]->regs; 13009 13010 /* Clear r0-r5 registers in forked state */ 13011 for (i = 0; i < CALLER_SAVED_REGS; i++) 13012 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 13013 13014 mark_reg_unknown(env, regs, BPF_REG_0); 13015 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 13016 if (err) { 13017 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 13018 return err; 13019 } 13020 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32)); 13021 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 13022 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 13023 return -EFAULT; 13024 } 13025 13026 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 13027 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 13028 return -EACCES; 13029 } 13030 13031 sleepable = bpf_is_kfunc_sleepable(&meta); 13032 if (sleepable && !in_sleepable(env)) { 13033 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 13034 return -EACCES; 13035 } 13036 13037 /* Track non-sleepable context for kfuncs, same as for helpers. */ 13038 if (!in_sleepable_context(env)) 13039 insn_aux->non_sleepable = true; 13040 13041 /* Check the arguments */ 13042 err = check_kfunc_args(env, &meta, insn_idx); 13043 if (err < 0) 13044 return err; 13045 13046 if ((is_bpf_obj_drop_kfunc(meta.func_id) || 13047 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (is_tracing_prog_type(prog_type) || 13048 /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */ 13049 (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER 13050 && !env->prog->sleepable))) { 13051 struct btf_struct_meta *struct_meta; 13052 13053 struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13054 if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) { 13055 verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n", 13056 func_name); 13057 return -EINVAL; 13058 } 13059 } 13060 13061 if (is_bpf_rbtree_add_kfunc(meta.func_id)) { 13062 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13063 set_rbtree_add_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 if (is_bpf_wq_set_callback_kfunc(meta.func_id)) { 13072 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13073 set_timer_callback_state); 13074 if (err) { 13075 verbose(env, "kfunc %s#%d failed callback verification\n", 13076 func_name, meta.func_id); 13077 return err; 13078 } 13079 } 13080 13081 if (is_task_work_add_kfunc(meta.func_id)) { 13082 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13083 set_task_work_schedule_callback_state); 13084 if (err) { 13085 verbose(env, "kfunc %s#%d failed callback verification\n", 13086 func_name, meta.func_id); 13087 return err; 13088 } 13089 } 13090 13091 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 13092 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 13093 13094 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 13095 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 13096 13097 if (rcu_lock) { 13098 env->cur_state->active_rcu_locks++; 13099 } else if (rcu_unlock) { 13100 if (env->cur_state->active_rcu_locks == 0) { 13101 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 13102 return -EINVAL; 13103 } 13104 if (--env->cur_state->active_rcu_locks == 0) 13105 invalidate_rcu_protected_refs(env); 13106 } else if (preempt_disable) { 13107 env->cur_state->active_preempt_locks++; 13108 } else if (preempt_enable) { 13109 if (env->cur_state->active_preempt_locks == 0) { 13110 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 13111 return -EINVAL; 13112 } 13113 env->cur_state->active_preempt_locks--; 13114 } 13115 13116 if (sleepable && !in_sleepable_context(env)) { 13117 verbose(env, "kernel func %s is sleepable within %s\n", 13118 func_name, non_sleepable_context_description(env)); 13119 return -EACCES; 13120 } 13121 13122 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 13123 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 13124 return -EACCES; 13125 } 13126 13127 if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) { 13128 verbose(env, "kernel func %s requires RCU critical section protection\n", func_name); 13129 return -EACCES; 13130 } 13131 13132 /* In case of release function, we get register number of refcounted 13133 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 13134 */ 13135 if (meta.release_regno) { 13136 err = release_reg(env, ®s[meta.release_regno], false, !!meta.dynptr.id); 13137 if (err) 13138 return err; 13139 } 13140 13141 if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) { 13142 id = regs[BPF_REG_2].id; 13143 insn_aux->insert_off = regs[BPF_REG_2].var_off.value; 13144 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13145 ref_convert_owning_non_owning(env, id); 13146 } 13147 13148 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 13149 if (!bpf_jit_supports_exceptions()) { 13150 verbose(env, "JIT does not support calling kfunc %s#%d\n", 13151 func_name, meta.func_id); 13152 return -ENOTSUPP; 13153 } 13154 env->seen_exception = true; 13155 13156 /* In the case of the default callback, the cookie value passed 13157 * to bpf_throw becomes the return value of the program. 13158 */ 13159 if (!env->exception_callback_subprog) { 13160 err = check_return_code(env, BPF_REG_1, "R1"); 13161 if (err < 0) 13162 return err; 13163 } 13164 } 13165 13166 for (i = 0; i < CALLER_SAVED_REGS; i++) { 13167 u32 regno = caller_saved[i]; 13168 13169 bpf_mark_reg_not_init(env, ®s[regno]); 13170 regs[regno].subreg_def = DEF_NOT_SUBREG; 13171 } 13172 invalidate_outgoing_stack_args(env, cur_func(env)); 13173 13174 /* Check return type */ 13175 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13176 13177 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13178 if (meta.btf != btf_vmlinux || 13179 (!is_bpf_obj_new_kfunc(meta.func_id) && 13180 !is_bpf_percpu_obj_new_kfunc(meta.func_id) && 13181 !is_bpf_refcount_acquire_kfunc(meta.func_id))) { 13182 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13183 return -EINVAL; 13184 } 13185 } 13186 13187 if (btf_type_is_scalar(t)) { 13188 mark_reg_unknown(env, regs, BPF_REG_0); 13189 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13190 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13191 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 13192 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 13193 } else if (btf_type_is_ptr(t)) { 13194 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 13195 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 13196 if (err) { 13197 if (err < 0) 13198 return err; 13199 } else if (btf_type_is_void(ptr_type)) { 13200 /* kfunc returning 'void *' is equivalent to returning scalar */ 13201 mark_reg_unknown(env, regs, BPF_REG_0); 13202 } else if (!__btf_type_is_struct(ptr_type)) { 13203 if (!meta.ret_mem.found) { 13204 __u32 sz; 13205 13206 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 13207 meta.ret_mem.found = true; 13208 meta.ret_mem.size = sz; 13209 meta.r0_rdonly = true; 13210 } 13211 13212 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 13213 meta.r0_rdonly = false; 13214 } 13215 if (!meta.ret_mem.found) { 13216 ptr_type_name = btf_name_by_offset(desc_btf, 13217 ptr_type->name_off); 13218 verbose(env, 13219 "kernel function %s returns pointer type %s %s is not supported\n", 13220 func_name, 13221 btf_type_str(ptr_type), 13222 ptr_type_name); 13223 return -EINVAL; 13224 } 13225 13226 mark_reg_known_zero(env, regs, BPF_REG_0); 13227 regs[BPF_REG_0].type = PTR_TO_MEM; 13228 regs[BPF_REG_0].mem_size = meta.ret_mem.size; 13229 13230 if (meta.r0_rdonly) 13231 regs[BPF_REG_0].type |= MEM_RDONLY; 13232 13233 /* Ensures we don't access the memory after a release_reference() */ 13234 if (meta.ref_obj.id) { 13235 err = validate_ref_obj(env, &meta.ref_obj); 13236 if (err) 13237 return err; 13238 regs[BPF_REG_0].parent_id = meta.ref_obj.id; 13239 } 13240 13241 if (is_kfunc_rcu_protected(&meta)) 13242 regs[BPF_REG_0].type |= MEM_RCU; 13243 } else { 13244 enum bpf_reg_type type = PTR_TO_BTF_ID; 13245 13246 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 13247 type |= PTR_UNTRUSTED; 13248 else if (is_kfunc_rcu_protected(&meta) || 13249 (bpf_is_iter_next_kfunc(&meta) && 13250 (get_iter_from_state(env->cur_state, &meta) 13251 ->type & MEM_RCU))) { 13252 /* 13253 * If the iterator's constructor (the _new 13254 * function e.g., bpf_iter_task_new) has been 13255 * annotated with BPF kfunc flag 13256 * KF_RCU_PROTECTED and was called within a RCU 13257 * read-side critical section, also propagate 13258 * the MEM_RCU flag to the pointer returned from 13259 * the iterator's next function (e.g., 13260 * bpf_iter_task_next). 13261 */ 13262 type |= MEM_RCU; 13263 } else { 13264 /* 13265 * Any PTR_TO_BTF_ID that is returned from a BPF 13266 * kfunc should by default be treated as 13267 * implicitly trusted. 13268 */ 13269 type |= PTR_TRUSTED; 13270 } 13271 13272 mark_reg_known_zero(env, regs, BPF_REG_0); 13273 regs[BPF_REG_0].btf = desc_btf; 13274 regs[BPF_REG_0].type = type; 13275 regs[BPF_REG_0].btf_id = ptr_type_id; 13276 } 13277 13278 if (is_kfunc_ret_null(&meta)) { 13279 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 13280 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 13281 regs[BPF_REG_0].id = ++env->id_gen; 13282 } 13283 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 13284 if (is_kfunc_acquire(&meta)) { 13285 id = acquire_reference(env, insn_idx, 0); 13286 if (id < 0) 13287 return id; 13288 regs[BPF_REG_0].id = id; 13289 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 13290 ref_set_non_owning(env, ®s[BPF_REG_0]); 13291 } 13292 13293 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 13294 regs[BPF_REG_0].id = ++env->id_gen; 13295 } else if (btf_type_is_void(t)) { 13296 if (meta.btf == btf_vmlinux) { 13297 if (is_bpf_obj_drop_kfunc(meta.func_id) || 13298 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) { 13299 insn_aux->kptr_struct_meta = 13300 btf_find_struct_meta(meta.arg_btf, 13301 meta.arg_btf_id); 13302 } 13303 } 13304 } 13305 13306 if (bpf_is_kfunc_pkt_changing(&meta)) 13307 clear_all_pkt_pointers(env); 13308 13309 nargs = btf_type_vlen(meta.func_proto); 13310 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 13311 struct bpf_func_state *caller = cur_func(env); 13312 struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno]; 13313 u16 out_stack_arg_cnt = nargs - MAX_BPF_FUNC_REG_ARGS; 13314 u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt; 13315 13316 if (stack_arg_cnt > caller_info->stack_arg_cnt) 13317 caller_info->stack_arg_cnt = stack_arg_cnt; 13318 } 13319 13320 args = (const struct btf_param *)(meta.func_proto + 1); 13321 for (i = 0; i < min_t(int, nargs, MAX_BPF_FUNC_REG_ARGS); i++) { 13322 u32 regno = i + 1; 13323 13324 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 13325 if (btf_type_is_ptr(t)) 13326 mark_btf_func_reg_size(env, regno, sizeof(void *)); 13327 else 13328 /* scalar. ensured by check_kfunc_args() */ 13329 mark_btf_func_reg_size(env, regno, t->size); 13330 } 13331 13332 if (bpf_is_iter_next_kfunc(&meta)) { 13333 err = process_iter_next_call(env, insn_idx, &meta); 13334 if (err) 13335 return err; 13336 } 13337 13338 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 13339 env->prog->call_session_cookie = true; 13340 13341 if (bpf_is_throw_kfunc(insn)) 13342 return process_bpf_exit_full(env, NULL, true); 13343 13344 return 0; 13345 } 13346 13347 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env, 13348 const struct bpf_reg_state *reg, 13349 enum bpf_reg_type type) 13350 { 13351 bool known = tnum_is_const(reg->var_off); 13352 s64 val = reg->var_off.value; 13353 s64 smin = reg_smin(reg); 13354 13355 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13356 verbose(env, "math between %s pointer and %lld is not allowed\n", 13357 reg_type_str(env, type), val); 13358 return false; 13359 } 13360 13361 if (smin == S64_MIN) { 13362 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 13363 reg_type_str(env, type)); 13364 return false; 13365 } 13366 13367 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13368 verbose(env, "value %lld makes %s pointer be out of bounds\n", 13369 smin, reg_type_str(env, type)); 13370 return false; 13371 } 13372 13373 return true; 13374 } 13375 13376 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env, 13377 const struct bpf_reg_state *reg, 13378 enum bpf_reg_type type) 13379 { 13380 bool known = tnum_is_const(reg->var_off); 13381 s64 val = reg->var_off.value; 13382 s64 smin = reg_smin(reg); 13383 13384 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13385 verbose(env, "%s pointer offset %lld is not allowed\n", 13386 reg_type_str(env, type), val); 13387 return false; 13388 } 13389 13390 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13391 verbose(env, "%s pointer offset %lld is not allowed\n", 13392 reg_type_str(env, type), smin); 13393 return false; 13394 } 13395 13396 return true; 13397 } 13398 13399 enum { 13400 REASON_BOUNDS = -1, 13401 REASON_TYPE = -2, 13402 REASON_PATHS = -3, 13403 REASON_LIMIT = -4, 13404 REASON_STACK = -5, 13405 }; 13406 13407 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 13408 u32 *alu_limit, bool mask_to_left) 13409 { 13410 u32 max = 0, ptr_limit = 0; 13411 13412 switch (ptr_reg->type) { 13413 case PTR_TO_STACK: 13414 /* Offset 0 is out-of-bounds, but acceptable start for the 13415 * left direction, see BPF_REG_FP. Also, unknown scalar 13416 * offset where we would need to deal with min/max bounds is 13417 * currently prohibited for unprivileged. 13418 */ 13419 max = MAX_BPF_STACK + mask_to_left; 13420 ptr_limit = -ptr_reg->var_off.value; 13421 break; 13422 case PTR_TO_MAP_VALUE: 13423 max = ptr_reg->map_ptr->value_size; 13424 ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg); 13425 break; 13426 default: 13427 return REASON_TYPE; 13428 } 13429 13430 if (ptr_limit >= max) 13431 return REASON_LIMIT; 13432 *alu_limit = ptr_limit; 13433 return 0; 13434 } 13435 13436 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 13437 const struct bpf_insn *insn) 13438 { 13439 return env->bypass_spec_v1 || 13440 BPF_SRC(insn->code) == BPF_K || 13441 cur_aux(env)->nospec; 13442 } 13443 13444 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 13445 u32 alu_state, u32 alu_limit) 13446 { 13447 /* If we arrived here from different branches with different 13448 * state or limits to sanitize, then this won't work. 13449 */ 13450 if (aux->alu_state && 13451 (aux->alu_state != alu_state || 13452 aux->alu_limit != alu_limit)) 13453 return REASON_PATHS; 13454 13455 /* Corresponding fixup done in do_misc_fixups(). */ 13456 aux->alu_state = alu_state; 13457 aux->alu_limit = alu_limit; 13458 return 0; 13459 } 13460 13461 static int sanitize_val_alu(struct bpf_verifier_env *env, 13462 struct bpf_insn *insn) 13463 { 13464 struct bpf_insn_aux_data *aux = cur_aux(env); 13465 13466 if (can_skip_alu_sanitation(env, insn)) 13467 return 0; 13468 13469 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13470 } 13471 13472 static bool sanitize_needed(u8 opcode) 13473 { 13474 return opcode == BPF_ADD || opcode == BPF_SUB; 13475 } 13476 13477 struct bpf_sanitize_info { 13478 struct bpf_insn_aux_data aux; 13479 bool mask_to_left; 13480 }; 13481 13482 static int sanitize_speculative_path(struct bpf_verifier_env *env, 13483 const struct bpf_insn *insn, 13484 u32 next_idx, u32 curr_idx) 13485 { 13486 struct bpf_verifier_state *branch; 13487 struct bpf_reg_state *regs; 13488 13489 branch = push_stack(env, next_idx, curr_idx, true); 13490 if (!IS_ERR(branch) && insn) { 13491 regs = branch->frame[branch->curframe]->regs; 13492 if (BPF_SRC(insn->code) == BPF_K) { 13493 mark_reg_unknown(env, regs, insn->dst_reg); 13494 } else if (BPF_SRC(insn->code) == BPF_X) { 13495 mark_reg_unknown(env, regs, insn->dst_reg); 13496 mark_reg_unknown(env, regs, insn->src_reg); 13497 } 13498 } 13499 return PTR_ERR_OR_ZERO(branch); 13500 } 13501 13502 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13503 struct bpf_insn *insn, 13504 const struct bpf_reg_state *ptr_reg, 13505 const struct bpf_reg_state *off_reg, 13506 struct bpf_reg_state *dst_reg, 13507 struct bpf_sanitize_info *info, 13508 const bool commit_window) 13509 { 13510 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13511 struct bpf_verifier_state *vstate = env->cur_state; 13512 bool off_is_imm = tnum_is_const(off_reg->var_off); 13513 bool off_is_neg = reg_smin(off_reg) < 0; 13514 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13515 u8 opcode = BPF_OP(insn->code); 13516 u32 alu_state, alu_limit; 13517 struct bpf_reg_state tmp; 13518 int err; 13519 13520 if (can_skip_alu_sanitation(env, insn)) 13521 return 0; 13522 13523 /* We already marked aux for masking from non-speculative 13524 * paths, thus we got here in the first place. We only care 13525 * to explore bad access from here. 13526 */ 13527 if (vstate->speculative) 13528 goto do_sim; 13529 13530 if (!commit_window) { 13531 if (!tnum_is_const(off_reg->var_off) && 13532 (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0)) 13533 return REASON_BOUNDS; 13534 13535 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13536 (opcode == BPF_SUB && !off_is_neg); 13537 } 13538 13539 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13540 if (err < 0) 13541 return err; 13542 13543 if (commit_window) { 13544 /* In commit phase we narrow the masking window based on 13545 * the observed pointer move after the simulated operation. 13546 */ 13547 alu_state = info->aux.alu_state; 13548 alu_limit = abs(info->aux.alu_limit - alu_limit); 13549 } else { 13550 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13551 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13552 alu_state |= ptr_is_dst_reg ? 13553 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13554 13555 /* Limit pruning on unknown scalars to enable deep search for 13556 * potential masking differences from other program paths. 13557 */ 13558 if (!off_is_imm) 13559 env->explore_alu_limits = true; 13560 } 13561 13562 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13563 if (err < 0) 13564 return err; 13565 do_sim: 13566 /* If we're in commit phase, we're done here given we already 13567 * pushed the truncated dst_reg into the speculative verification 13568 * stack. 13569 * 13570 * Also, when register is a known constant, we rewrite register-based 13571 * operation to immediate-based, and thus do not need masking (and as 13572 * a consequence, do not need to simulate the zero-truncation either). 13573 */ 13574 if (commit_window || off_is_imm) 13575 return 0; 13576 13577 /* Simulate and find potential out-of-bounds access under 13578 * speculative execution from truncation as a result of 13579 * masking when off was not within expected range. If off 13580 * sits in dst, then we temporarily need to move ptr there 13581 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13582 * for cases where we use K-based arithmetic in one direction 13583 * and truncated reg-based in the other in order to explore 13584 * bad access. 13585 */ 13586 if (!ptr_is_dst_reg) { 13587 tmp = *dst_reg; 13588 *dst_reg = *ptr_reg; 13589 } 13590 err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx); 13591 if (err < 0) 13592 return REASON_STACK; 13593 if (!ptr_is_dst_reg) 13594 *dst_reg = tmp; 13595 return 0; 13596 } 13597 13598 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13599 { 13600 struct bpf_verifier_state *vstate = env->cur_state; 13601 13602 /* If we simulate paths under speculation, we don't update the 13603 * insn as 'seen' such that when we verify unreachable paths in 13604 * the non-speculative domain, sanitize_dead_code() can still 13605 * rewrite/sanitize them. 13606 */ 13607 if (!vstate->speculative) 13608 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13609 } 13610 13611 static int sanitize_err(struct bpf_verifier_env *env, 13612 const struct bpf_insn *insn, int reason, 13613 const struct bpf_reg_state *off_reg, 13614 const struct bpf_reg_state *dst_reg) 13615 { 13616 static const char *err = "pointer arithmetic with it prohibited for !root"; 13617 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13618 u32 dst = insn->dst_reg, src = insn->src_reg; 13619 13620 switch (reason) { 13621 case REASON_BOUNDS: 13622 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13623 off_reg == dst_reg ? dst : src, err); 13624 break; 13625 case REASON_TYPE: 13626 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13627 off_reg == dst_reg ? src : dst, err); 13628 break; 13629 case REASON_PATHS: 13630 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13631 dst, op, err); 13632 break; 13633 case REASON_LIMIT: 13634 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13635 dst, op, err); 13636 break; 13637 case REASON_STACK: 13638 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13639 dst, err); 13640 return -ENOMEM; 13641 default: 13642 verifier_bug(env, "unknown reason (%d)", reason); 13643 break; 13644 } 13645 13646 return -EACCES; 13647 } 13648 13649 /* check that stack access falls within stack limits and that 'reg' doesn't 13650 * have a variable offset. 13651 * 13652 * Variable offset is prohibited for unprivileged mode for simplicity since it 13653 * requires corresponding support in Spectre masking for stack ALU. See also 13654 * retrieve_ptr_limit(). 13655 */ 13656 static int check_stack_access_for_ptr_arithmetic( 13657 struct bpf_verifier_env *env, 13658 int regno, 13659 const struct bpf_reg_state *reg, 13660 int off) 13661 { 13662 if (!tnum_is_const(reg->var_off)) { 13663 char tn_buf[48]; 13664 13665 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13666 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13667 regno, tn_buf, off); 13668 return -EACCES; 13669 } 13670 13671 if (off >= 0 || off < -MAX_BPF_STACK) { 13672 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13673 "prohibited for !root; off=%d\n", regno, off); 13674 return -EACCES; 13675 } 13676 13677 return 0; 13678 } 13679 13680 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13681 const struct bpf_insn *insn, 13682 struct bpf_reg_state *dst_reg) 13683 { 13684 u32 dst = insn->dst_reg; 13685 13686 /* For unprivileged we require that resulting offset must be in bounds 13687 * in order to be able to sanitize access later on. 13688 */ 13689 if (env->bypass_spec_v1) 13690 return 0; 13691 13692 switch (dst_reg->type) { 13693 case PTR_TO_STACK: 13694 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13695 dst_reg->var_off.value)) 13696 return -EACCES; 13697 break; 13698 case PTR_TO_MAP_VALUE: 13699 if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) { 13700 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13701 "prohibited for !root\n", dst); 13702 return -EACCES; 13703 } 13704 break; 13705 default: 13706 return -EOPNOTSUPP; 13707 } 13708 13709 return 0; 13710 } 13711 13712 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13713 * Caller should also handle BPF_MOV case separately. 13714 * If we return -EACCES, caller may want to try again treating pointer as a 13715 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13716 */ 13717 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13718 struct bpf_insn *insn, 13719 const struct bpf_reg_state *ptr_reg, 13720 const struct bpf_reg_state *off_reg) 13721 { 13722 struct bpf_verifier_state *vstate = env->cur_state; 13723 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13724 struct bpf_reg_state *regs = state->regs, *dst_reg; 13725 bool known = tnum_is_const(off_reg->var_off); 13726 s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg); 13727 u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg); 13728 struct bpf_sanitize_info info = {}; 13729 u8 opcode = BPF_OP(insn->code); 13730 u32 dst = insn->dst_reg; 13731 int ret, bounds_ret; 13732 13733 dst_reg = ®s[dst]; 13734 13735 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13736 smin_val > smax_val || umin_val > umax_val) { 13737 /* Taint dst register if offset had invalid bounds derived from 13738 * e.g. dead branches. 13739 */ 13740 __mark_reg_unknown(env, dst_reg); 13741 return 0; 13742 } 13743 13744 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13745 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13746 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13747 __mark_reg_unknown(env, dst_reg); 13748 return 0; 13749 } 13750 13751 verbose(env, 13752 "R%d 32-bit pointer arithmetic prohibited\n", 13753 dst); 13754 return -EACCES; 13755 } 13756 13757 if (ptr_reg->type & PTR_MAYBE_NULL) { 13758 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13759 dst, reg_type_str(env, ptr_reg->type)); 13760 return -EACCES; 13761 } 13762 13763 /* 13764 * Accesses to untrusted PTR_TO_MEM are done through probe 13765 * instructions, hence no need to track offsets. 13766 */ 13767 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 13768 return 0; 13769 13770 switch (base_type(ptr_reg->type)) { 13771 case PTR_TO_CTX: 13772 case PTR_TO_MAP_VALUE: 13773 case PTR_TO_MAP_KEY: 13774 case PTR_TO_STACK: 13775 case PTR_TO_PACKET_META: 13776 case PTR_TO_PACKET: 13777 case PTR_TO_TP_BUFFER: 13778 case PTR_TO_BTF_ID: 13779 case PTR_TO_MEM: 13780 case PTR_TO_BUF: 13781 case PTR_TO_FUNC: 13782 case CONST_PTR_TO_DYNPTR: 13783 break; 13784 case PTR_TO_FLOW_KEYS: 13785 if (known) 13786 break; 13787 fallthrough; 13788 case CONST_PTR_TO_MAP: 13789 /* smin_val represents the known value */ 13790 if (known && smin_val == 0 && opcode == BPF_ADD) 13791 break; 13792 fallthrough; 13793 default: 13794 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13795 dst, reg_type_str(env, ptr_reg->type)); 13796 return -EACCES; 13797 } 13798 13799 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13800 * The id may be overwritten later if we create a new variable offset. 13801 */ 13802 dst_reg->type = ptr_reg->type; 13803 dst_reg->id = ptr_reg->id; 13804 13805 if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type) || 13806 !check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) 13807 return -EINVAL; 13808 13809 /* pointer types do not carry 32-bit bounds at the moment. */ 13810 __mark_reg32_unbounded(dst_reg); 13811 13812 if (sanitize_needed(opcode)) { 13813 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13814 &info, false); 13815 if (ret < 0) 13816 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13817 } 13818 13819 switch (opcode) { 13820 case BPF_ADD: 13821 /* 13822 * dst_reg gets the pointer type and since some positive 13823 * integer value was added to the pointer, give it a new 'id' 13824 * if it's a PTR_TO_PACKET. 13825 * this creates a new 'base' pointer, off_reg (variable) gets 13826 * added into the variable offset, and we copy the fixed offset 13827 * from ptr_reg. 13828 */ 13829 dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64); 13830 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13831 dst_reg->raw = ptr_reg->raw; 13832 if (reg_is_pkt_pointer(ptr_reg)) { 13833 if (!known) 13834 dst_reg->id = ++env->id_gen; 13835 /* 13836 * Clear range for unknown addends since we can't know 13837 * where the pkt pointer ended up. Also clear AT_PKT_END / 13838 * BEYOND_PKT_END from prior comparison as any pointer 13839 * arithmetic invalidates them. 13840 */ 13841 if (!known || dst_reg->range < 0) 13842 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13843 } 13844 break; 13845 case BPF_SUB: 13846 if (dst_reg == off_reg) { 13847 /* scalar -= pointer. Creates an unknown scalar */ 13848 verbose(env, "R%d tried to subtract pointer from scalar\n", 13849 dst); 13850 return -EACCES; 13851 } 13852 /* We don't allow subtraction from FP, because (according to 13853 * test_verifier.c test "invalid fp arithmetic", JITs might not 13854 * be able to deal with it. 13855 */ 13856 if (ptr_reg->type == PTR_TO_STACK) { 13857 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13858 dst); 13859 return -EACCES; 13860 } 13861 dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64)); 13862 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13863 dst_reg->raw = ptr_reg->raw; 13864 if (reg_is_pkt_pointer(ptr_reg)) { 13865 if (!known) 13866 dst_reg->id = ++env->id_gen; 13867 /* 13868 * Clear range if the subtrahend may be negative since 13869 * pkt pointer could move past its bounds. A positive 13870 * subtrahend moves it backwards keeping positive range 13871 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from 13872 * prior comparison as arithmetic invalidates them. 13873 */ 13874 if ((!known && smin_val < 0) || dst_reg->range < 0) 13875 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13876 } 13877 break; 13878 case BPF_AND: 13879 case BPF_OR: 13880 case BPF_XOR: 13881 /* bitwise ops on pointers are troublesome, prohibit. */ 13882 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13883 dst, bpf_alu_string[opcode >> 4]); 13884 return -EACCES; 13885 default: 13886 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13887 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13888 dst, bpf_alu_string[opcode >> 4]); 13889 return -EACCES; 13890 } 13891 13892 if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) 13893 return -EINVAL; 13894 reg_bounds_sync(dst_reg); 13895 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 13896 if (bounds_ret == -EACCES) 13897 return bounds_ret; 13898 if (sanitize_needed(opcode)) { 13899 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13900 &info, true); 13901 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 13902 && !env->cur_state->speculative 13903 && bounds_ret 13904 && !ret, 13905 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 13906 return -EFAULT; 13907 } 13908 if (ret < 0) 13909 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13910 } 13911 13912 return 0; 13913 } 13914 13915 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13916 struct bpf_reg_state *src_reg) 13917 { 13918 dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32); 13919 } 13920 13921 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13922 struct bpf_reg_state *src_reg) 13923 { 13924 dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64); 13925 } 13926 13927 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13928 struct bpf_reg_state *src_reg) 13929 { 13930 dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32)); 13931 } 13932 13933 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13934 struct bpf_reg_state *src_reg) 13935 { 13936 dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64)); 13937 } 13938 13939 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13940 struct bpf_reg_state *src_reg) 13941 { 13942 s32 smin = reg_s32_min(dst_reg); 13943 s32 smax = reg_s32_max(dst_reg); 13944 u32 umin = reg_u32_min(dst_reg); 13945 u32 umax = reg_u32_max(dst_reg); 13946 s32 tmp_prod[4]; 13947 13948 if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) || 13949 check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) { 13950 /* Overflow possible, we know nothing */ 13951 umin = 0; 13952 umax = U32_MAX; 13953 } 13954 if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) || 13955 check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) || 13956 check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) || 13957 check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) { 13958 /* Overflow possible, we know nothing */ 13959 smin = S32_MIN; 13960 smax = S32_MAX; 13961 } else { 13962 smin = min_array(tmp_prod, 4); 13963 smax = max_array(tmp_prod, 4); 13964 } 13965 13966 dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax), 13967 cnum32_from_srange(smin, smax)); 13968 } 13969 13970 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13971 struct bpf_reg_state *src_reg) 13972 { 13973 s64 smin = reg_smin(dst_reg); 13974 s64 smax = reg_smax(dst_reg); 13975 u64 umin = reg_umin(dst_reg); 13976 u64 umax = reg_umax(dst_reg); 13977 s64 tmp_prod[4]; 13978 13979 if (check_mul_overflow(umax, reg_umax(src_reg), &umax) || 13980 check_mul_overflow(umin, reg_umin(src_reg), &umin)) { 13981 /* Overflow possible, we know nothing */ 13982 umin = 0; 13983 umax = U64_MAX; 13984 } 13985 if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) || 13986 check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) || 13987 check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) || 13988 check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) { 13989 /* Overflow possible, we know nothing */ 13990 smin = S64_MIN; 13991 smax = S64_MAX; 13992 } else { 13993 smin = min_array(tmp_prod, 4); 13994 smax = max_array(tmp_prod, 4); 13995 } 13996 13997 dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax), 13998 cnum64_from_srange(smin, smax)); 13999 } 14000 14001 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg, 14002 struct bpf_reg_state *src_reg) 14003 { 14004 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 14005 14006 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val, 14007 reg_u32_max(dst_reg) / src_val); 14008 14009 /* Reset other ranges/tnum to unbounded/unknown. */ 14010 reset_reg64_and_tnum(dst_reg); 14011 } 14012 14013 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg, 14014 struct bpf_reg_state *src_reg) 14015 { 14016 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 14017 14018 reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val), 14019 div64_u64(reg_umax(dst_reg), src_val)); 14020 14021 /* Reset other ranges/tnum to unbounded/unknown. */ 14022 reset_reg32_and_tnum(dst_reg); 14023 } 14024 14025 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg, 14026 struct bpf_reg_state *src_reg) 14027 { 14028 s32 smin = reg_s32_min(dst_reg); 14029 s32 smax = reg_s32_max(dst_reg); 14030 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 14031 s32 res1, res2; 14032 14033 /* BPF div specification: S32_MIN / -1 = S32_MIN */ 14034 if (smin == S32_MIN && src_val == -1) { 14035 /* 14036 * If the dividend range contains more than just S32_MIN, 14037 * we cannot precisely track the result, so it becomes unbounded. 14038 * e.g., [S32_MIN, S32_MIN+10]/(-1), 14039 * = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)] 14040 * = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX] 14041 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN. 14042 */ 14043 if (smax != S32_MIN) { 14044 smin = S32_MIN; 14045 smax = S32_MAX; 14046 } 14047 goto reset; 14048 } 14049 14050 res1 = smin / src_val; 14051 res2 = smax / src_val; 14052 smin = min(res1, res2); 14053 smax = max(res1, res2); 14054 14055 reset: 14056 reg_set_srange32(dst_reg, smin, smax); 14057 /* Reset other ranges/tnum to unbounded/unknown. */ 14058 reset_reg64_and_tnum(dst_reg); 14059 } 14060 14061 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg, 14062 struct bpf_reg_state *src_reg) 14063 { 14064 s64 smin = reg_smin(dst_reg); 14065 s64 smax = reg_smax(dst_reg); 14066 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14067 s64 res1, res2; 14068 14069 /* BPF div specification: S64_MIN / -1 = S64_MIN */ 14070 if (smin == S64_MIN && src_val == -1) { 14071 /* 14072 * If the dividend range contains more than just S64_MIN, 14073 * we cannot precisely track the result, so it becomes unbounded. 14074 * e.g., [S64_MIN, S64_MIN+10]/(-1), 14075 * = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)] 14076 * = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX] 14077 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN. 14078 */ 14079 if (smax != S64_MIN) { 14080 smin = S64_MIN; 14081 smax = S64_MAX; 14082 } 14083 goto reset; 14084 } 14085 14086 res1 = div64_s64(smin, src_val); 14087 res2 = div64_s64(smax, src_val); 14088 smin = min(res1, res2); 14089 smax = max(res1, res2); 14090 14091 reset: 14092 reg_set_srange64(dst_reg, smin, smax); 14093 /* Reset other ranges/tnum to unbounded/unknown. */ 14094 reset_reg32_and_tnum(dst_reg); 14095 } 14096 14097 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg, 14098 struct bpf_reg_state *src_reg) 14099 { 14100 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 14101 u32 res_max = src_val - 1; 14102 14103 /* 14104 * If dst_umax <= res_max, the result remains unchanged. 14105 * e.g., [2, 5] % 10 = [2, 5]. 14106 */ 14107 if (reg_u32_max(dst_reg) <= res_max) 14108 return; 14109 14110 reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max)); 14111 14112 /* Reset other ranges/tnum to unbounded/unknown. */ 14113 reset_reg64_and_tnum(dst_reg); 14114 } 14115 14116 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg, 14117 struct bpf_reg_state *src_reg) 14118 { 14119 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 14120 u64 res_max = src_val - 1; 14121 14122 /* 14123 * If dst_umax <= res_max, the result remains unchanged. 14124 * e.g., [2, 5] % 10 = [2, 5]. 14125 */ 14126 if (reg_umax(dst_reg) <= res_max) 14127 return; 14128 14129 reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max)); 14130 14131 /* Reset other ranges/tnum to unbounded/unknown. */ 14132 reset_reg32_and_tnum(dst_reg); 14133 } 14134 14135 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg, 14136 struct bpf_reg_state *src_reg) 14137 { 14138 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 14139 14140 /* 14141 * Safe absolute value calculation: 14142 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648. 14143 * Here use unsigned integer to avoid overflow. 14144 */ 14145 u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val; 14146 14147 /* 14148 * Calculate the maximum possible absolute value of the result. 14149 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives 14150 * 2147483647 (S32_MAX), which fits perfectly in s32. 14151 */ 14152 s32 res_max_abs = src_abs - 1; 14153 14154 /* 14155 * If the dividend is already within the result range, 14156 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14157 */ 14158 if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs) 14159 return; 14160 14161 /* General case: result has the same sign as the dividend. */ 14162 if (reg_s32_min(dst_reg) >= 0) { 14163 reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs)); 14164 } else if (reg_s32_max(dst_reg) <= 0) { 14165 reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0); 14166 } else { 14167 reg_set_srange32(dst_reg, -res_max_abs, res_max_abs); 14168 } 14169 14170 /* Reset other ranges/tnum to unbounded/unknown. */ 14171 reset_reg64_and_tnum(dst_reg); 14172 } 14173 14174 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg, 14175 struct bpf_reg_state *src_reg) 14176 { 14177 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14178 14179 /* 14180 * Safe absolute value calculation: 14181 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63. 14182 * Here use unsigned integer to avoid overflow. 14183 */ 14184 u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val; 14185 14186 /* 14187 * Calculate the maximum possible absolute value of the result. 14188 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives 14189 * 2^63 - 1 (S64_MAX), which fits perfectly in s64. 14190 */ 14191 s64 res_max_abs = src_abs - 1; 14192 14193 /* 14194 * If the dividend is already within the result range, 14195 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14196 */ 14197 if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs) 14198 return; 14199 14200 /* General case: result has the same sign as the dividend. */ 14201 if (reg_smin(dst_reg) >= 0) { 14202 reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs)); 14203 } else if (reg_smax(dst_reg) <= 0) { 14204 reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0); 14205 } else { 14206 reg_set_srange64(dst_reg, -res_max_abs, res_max_abs); 14207 } 14208 14209 /* Reset other ranges/tnum to unbounded/unknown. */ 14210 reset_reg32_and_tnum(dst_reg); 14211 } 14212 14213 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14214 struct bpf_reg_state *src_reg) 14215 { 14216 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14217 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14218 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14219 u32 umax_val = reg_u32_max(src_reg); 14220 14221 if (src_known && dst_known) { 14222 __mark_reg32_known(dst_reg, var32_off.value); 14223 return; 14224 } 14225 14226 /* We get our minimum from the var_off, since that's inherently 14227 * bitwise. Our maximum is the minimum of the operands' maxima. 14228 */ 14229 reg_set_urange32(dst_reg, 14230 var32_off.value, 14231 min(reg_u32_max(dst_reg), umax_val)); 14232 } 14233 14234 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14235 struct bpf_reg_state *src_reg) 14236 { 14237 bool src_known = tnum_is_const(src_reg->var_off); 14238 bool dst_known = tnum_is_const(dst_reg->var_off); 14239 u64 umax_val = reg_umax(src_reg); 14240 14241 if (src_known && dst_known) { 14242 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14243 return; 14244 } 14245 14246 /* We get our minimum from the var_off, since that's inherently 14247 * bitwise. Our maximum is the minimum of the operands' maxima. 14248 */ 14249 reg_set_urange64(dst_reg, 14250 dst_reg->var_off.value, 14251 min(reg_umax(dst_reg), umax_val)); 14252 14253 /* We may learn something more from the var_off */ 14254 __update_reg_bounds(dst_reg); 14255 } 14256 14257 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14258 struct bpf_reg_state *src_reg) 14259 { 14260 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14261 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14262 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14263 u32 umin_val = reg_u32_min(src_reg); 14264 14265 if (src_known && dst_known) { 14266 __mark_reg32_known(dst_reg, var32_off.value); 14267 return; 14268 } 14269 14270 /* We get our maximum from the var_off, and our minimum is the 14271 * maximum of the operands' minima 14272 */ 14273 reg_set_urange32(dst_reg, 14274 max(reg_u32_min(dst_reg), umin_val), 14275 var32_off.value | var32_off.mask); 14276 } 14277 14278 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14279 struct bpf_reg_state *src_reg) 14280 { 14281 bool src_known = tnum_is_const(src_reg->var_off); 14282 bool dst_known = tnum_is_const(dst_reg->var_off); 14283 u64 umin_val = reg_umin(src_reg); 14284 14285 if (src_known && dst_known) { 14286 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14287 return; 14288 } 14289 14290 /* We get our maximum from the var_off, and our minimum is the 14291 * maximum of the operands' minima 14292 */ 14293 reg_set_urange64(dst_reg, 14294 max(reg_umin(dst_reg), umin_val), 14295 dst_reg->var_off.value | dst_reg->var_off.mask); 14296 14297 /* We may learn something more from the var_off */ 14298 __update_reg_bounds(dst_reg); 14299 } 14300 14301 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 14302 struct bpf_reg_state *src_reg) 14303 { 14304 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14305 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14306 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14307 14308 if (src_known && dst_known) { 14309 __mark_reg32_known(dst_reg, var32_off.value); 14310 return; 14311 } 14312 14313 /* We get both minimum and maximum from the var32_off. */ 14314 reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask); 14315 } 14316 14317 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 14318 struct bpf_reg_state *src_reg) 14319 { 14320 bool src_known = tnum_is_const(src_reg->var_off); 14321 bool dst_known = tnum_is_const(dst_reg->var_off); 14322 14323 if (src_known && dst_known) { 14324 /* dst_reg->var_off.value has been updated earlier */ 14325 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14326 return; 14327 } 14328 14329 /* We get both minimum and maximum from the var_off. */ 14330 reg_set_urange64(dst_reg, 14331 dst_reg->var_off.value, 14332 dst_reg->var_off.value | dst_reg->var_off.mask); 14333 } 14334 14335 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14336 u64 umin_val, u64 umax_val) 14337 { 14338 /* If we might shift our top bit out, then we know nothing */ 14339 if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val)) 14340 reg_set_urange32(dst_reg, 0, U32_MAX); 14341 else 14342 /* We lose all sign bit information (except what we can pick 14343 * up from var_off) 14344 */ 14345 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val, 14346 reg_u32_max(dst_reg) << umax_val); 14347 } 14348 14349 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14350 struct bpf_reg_state *src_reg) 14351 { 14352 u32 umax_val = reg_u32_max(src_reg); 14353 u32 umin_val = reg_u32_min(src_reg); 14354 /* u32 alu operation will zext upper bits */ 14355 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14356 14357 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14358 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 14359 /* Not required but being careful mark reg64 bounds as unknown so 14360 * that we are forced to pick them up from tnum and zext later and 14361 * if some path skips this step we are still safe. 14362 */ 14363 __mark_reg64_unbounded(dst_reg); 14364 __update_reg32_bounds(dst_reg); 14365 } 14366 14367 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 14368 u64 umin_val, u64 umax_val) 14369 { 14370 struct cnum64 u, s; 14371 14372 /* Special case <<32 because it is a common compiler pattern to sign 14373 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct 14374 * because s32 bounds don't flip sign when shifting to the left by 14375 * 32bits. 14376 */ 14377 if (umin_val == 32 && umax_val == 32) 14378 s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32, 14379 (s64)reg_s32_max(dst_reg) << 32); 14380 else 14381 s = CNUM64_UNBOUNDED; 14382 14383 /* If we might shift our top bit out, then we know nothing */ 14384 if (reg_umax(dst_reg) > 1ULL << (63 - umax_val)) 14385 u = CNUM64_UNBOUNDED; 14386 else 14387 u = cnum64_from_urange(reg_umin(dst_reg) << umin_val, 14388 reg_umax(dst_reg) << umax_val); 14389 14390 dst_reg->r64 = cnum64_intersect(u, s); 14391 } 14392 14393 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 14394 struct bpf_reg_state *src_reg) 14395 { 14396 u64 umax_val = reg_umax(src_reg); 14397 u64 umin_val = reg_umin(src_reg); 14398 14399 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 14400 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 14401 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14402 14403 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 14404 /* We may learn something more from the var_off */ 14405 __update_reg_bounds(dst_reg); 14406 } 14407 14408 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 14409 struct bpf_reg_state *src_reg) 14410 { 14411 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14412 u32 umax_val = reg_u32_max(src_reg); 14413 u32 umin_val = reg_u32_min(src_reg); 14414 14415 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14416 * be negative, then either: 14417 * 1) src_reg might be zero, so the sign bit of the result is 14418 * unknown, so we lose our signed bounds 14419 * 2) it's known negative, thus the unsigned bounds capture the 14420 * signed bounds 14421 * 3) the signed bounds cross zero, so they tell us nothing 14422 * about the result 14423 * If the value in dst_reg is known nonnegative, then again the 14424 * unsigned bounds capture the signed bounds. 14425 * Thus, in all cases it suffices to blow away our signed bounds 14426 * and rely on inferring new ones from the unsigned bounds and 14427 * var_off of the result. 14428 */ 14429 14430 dst_reg->var_off = tnum_rshift(subreg, umin_val); 14431 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val, 14432 reg_u32_max(dst_reg) >> umin_val); 14433 14434 __mark_reg64_unbounded(dst_reg); 14435 __update_reg32_bounds(dst_reg); 14436 } 14437 14438 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 14439 struct bpf_reg_state *src_reg) 14440 { 14441 u64 umax_val = reg_umax(src_reg); 14442 u64 umin_val = reg_umin(src_reg); 14443 14444 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14445 * be negative, then either: 14446 * 1) src_reg might be zero, so the sign bit of the result is 14447 * unknown, so we lose our signed bounds 14448 * 2) it's known negative, thus the unsigned bounds capture the 14449 * signed bounds 14450 * 3) the signed bounds cross zero, so they tell us nothing 14451 * about the result 14452 * If the value in dst_reg is known nonnegative, then again the 14453 * unsigned bounds capture the signed bounds. 14454 * Thus, in all cases it suffices to blow away our signed bounds 14455 * and rely on inferring new ones from the unsigned bounds and 14456 * var_off of the result. 14457 */ 14458 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 14459 reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val, 14460 reg_umax(dst_reg) >> umin_val); 14461 14462 /* Its not easy to operate on alu32 bounds here because it depends 14463 * on bits being shifted in. Take easy way out and mark unbounded 14464 * so we can recalculate later from tnum. 14465 */ 14466 __mark_reg32_unbounded(dst_reg); 14467 __update_reg_bounds(dst_reg); 14468 } 14469 14470 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 14471 struct bpf_reg_state *src_reg) 14472 { 14473 u64 umin_val = reg_u32_min(src_reg); 14474 14475 /* Upon reaching here, src_known is true and 14476 * umax_val is equal to umin_val. 14477 * Blow away the dst_reg umin_value/umax_value and rely on 14478 * dst_reg var_off to refine the result. 14479 */ 14480 reg_set_srange32(dst_reg, 14481 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val), 14482 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val)); 14483 14484 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 14485 14486 __mark_reg64_unbounded(dst_reg); 14487 __update_reg32_bounds(dst_reg); 14488 } 14489 14490 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 14491 struct bpf_reg_state *src_reg) 14492 { 14493 u64 umin_val = reg_umin(src_reg); 14494 14495 /* Upon reaching here, src_known is true and umax_val is equal 14496 * to umin_val. 14497 */ 14498 reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val, 14499 reg_smax(dst_reg) >> umin_val); 14500 14501 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14502 14503 /* Its not easy to operate on alu32 bounds here because it depends 14504 * on bits being shifted in from upper 32-bits. Take easy way out 14505 * and mark unbounded so we can recalculate later from tnum. 14506 */ 14507 __mark_reg32_unbounded(dst_reg); 14508 __update_reg_bounds(dst_reg); 14509 } 14510 14511 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn) 14512 { 14513 /* 14514 * Byte swap operation - update var_off using tnum_bswap. 14515 * Three cases: 14516 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE) 14517 * unconditional swap 14518 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE) 14519 * swap on big-endian, truncation or no-op on little-endian 14520 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE) 14521 * swap on little-endian, truncation or no-op on big-endian 14522 */ 14523 14524 bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64; 14525 bool to_le = BPF_SRC(insn->code) == BPF_TO_LE; 14526 bool is_big_endian; 14527 #ifdef CONFIG_CPU_BIG_ENDIAN 14528 is_big_endian = true; 14529 #else 14530 is_big_endian = false; 14531 #endif 14532 /* Apply bswap if alu64 or switch between big-endian and little-endian machines */ 14533 bool need_bswap = alu64 || (to_le == is_big_endian); 14534 14535 /* 14536 * If the register is mutated, manually reset its scalar ID to break 14537 * any existing ties and avoid incorrect bounds propagation. 14538 */ 14539 if (need_bswap || insn->imm == 16 || insn->imm == 32) 14540 clear_scalar_id(dst_reg); 14541 14542 if (need_bswap) { 14543 if (insn->imm == 16) 14544 dst_reg->var_off = tnum_bswap16(dst_reg->var_off); 14545 else if (insn->imm == 32) 14546 dst_reg->var_off = tnum_bswap32(dst_reg->var_off); 14547 else if (insn->imm == 64) 14548 dst_reg->var_off = tnum_bswap64(dst_reg->var_off); 14549 /* 14550 * Byteswap scrambles the range, so we must reset bounds. 14551 * Bounds will be re-derived from the new tnum later. 14552 */ 14553 __mark_reg_unbounded(dst_reg); 14554 } 14555 /* For bswap16/32, truncate dst register to match the swapped size */ 14556 if (insn->imm == 16 || insn->imm == 32) 14557 coerce_reg_to_size(dst_reg, insn->imm / 8); 14558 } 14559 14560 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14561 const struct bpf_reg_state *src_reg) 14562 { 14563 bool src_is_const = false; 14564 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14565 14566 if (insn_bitness == 32) { 14567 if (tnum_subreg_is_const(src_reg->var_off) 14568 && reg_s32_min(src_reg) == reg_s32_max(src_reg) 14569 && reg_u32_min(src_reg) == reg_u32_max(src_reg)) 14570 src_is_const = true; 14571 } else { 14572 if (tnum_is_const(src_reg->var_off) 14573 && reg_smin(src_reg) == reg_smax(src_reg) 14574 && reg_umin(src_reg) == reg_umax(src_reg)) 14575 src_is_const = true; 14576 } 14577 14578 switch (BPF_OP(insn->code)) { 14579 case BPF_ADD: 14580 case BPF_SUB: 14581 case BPF_NEG: 14582 case BPF_AND: 14583 case BPF_XOR: 14584 case BPF_OR: 14585 case BPF_MUL: 14586 case BPF_END: 14587 return true; 14588 14589 /* 14590 * Division and modulo operators range is only safe to compute when the 14591 * divisor is a constant. 14592 */ 14593 case BPF_DIV: 14594 case BPF_MOD: 14595 return src_is_const; 14596 14597 /* Shift operators range is only computable if shift dimension operand 14598 * is a constant. Shifts greater than 31 or 63 are undefined. This 14599 * includes shifts by a negative number. 14600 */ 14601 case BPF_LSH: 14602 case BPF_RSH: 14603 case BPF_ARSH: 14604 return (src_is_const && reg_umax(src_reg) < insn_bitness); 14605 default: 14606 return false; 14607 } 14608 } 14609 14610 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn, 14611 struct bpf_reg_state *dst_reg) 14612 { 14613 struct bpf_verifier_state *branch; 14614 struct bpf_reg_state *regs; 14615 bool alu32; 14616 14617 if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0) 14618 alu32 = false; 14619 else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0) 14620 alu32 = true; 14621 else 14622 return 0; 14623 14624 branch = push_stack(env, env->insn_idx, env->insn_idx, false); 14625 if (IS_ERR(branch)) 14626 return PTR_ERR(branch); 14627 14628 regs = branch->frame[branch->curframe]->regs; 14629 if (alu32) { 14630 __mark_reg32_known(®s[insn->dst_reg], 0); 14631 __mark_reg32_known(dst_reg, -1ull); 14632 } else { 14633 __mark_reg_known(®s[insn->dst_reg], 0); 14634 __mark_reg_known(dst_reg, -1ull); 14635 } 14636 return 0; 14637 } 14638 14639 /* WARNING: This function does calculations on 64-bit values, but the actual 14640 * execution may occur on 32-bit values. Therefore, things like bitshifts 14641 * need extra checks in the 32-bit case. 14642 */ 14643 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14644 struct bpf_insn *insn, 14645 struct bpf_reg_state *dst_reg, 14646 struct bpf_reg_state src_reg) 14647 { 14648 u8 opcode = BPF_OP(insn->code); 14649 s16 off = insn->off; 14650 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14651 int ret; 14652 14653 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14654 __mark_reg_unknown(env, dst_reg); 14655 return 0; 14656 } 14657 14658 if (sanitize_needed(opcode)) { 14659 ret = sanitize_val_alu(env, insn); 14660 if (ret < 0) 14661 return sanitize_err(env, insn, ret, NULL, NULL); 14662 } 14663 14664 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14665 * There are two classes of instructions: The first class we track both 14666 * alu32 and alu64 sign/unsigned bounds independently this provides the 14667 * greatest amount of precision when alu operations are mixed with jmp32 14668 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14669 * and BPF_OR. This is possible because these ops have fairly easy to 14670 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14671 * See alu32 verifier tests for examples. The second class of 14672 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14673 * with regards to tracking sign/unsigned bounds because the bits may 14674 * cross subreg boundaries in the alu64 case. When this happens we mark 14675 * the reg unbounded in the subreg bound space and use the resulting 14676 * tnum to calculate an approximation of the sign/unsigned bounds. 14677 */ 14678 switch (opcode) { 14679 case BPF_ADD: 14680 scalar32_min_max_add(dst_reg, &src_reg); 14681 scalar_min_max_add(dst_reg, &src_reg); 14682 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14683 break; 14684 case BPF_SUB: 14685 scalar32_min_max_sub(dst_reg, &src_reg); 14686 scalar_min_max_sub(dst_reg, &src_reg); 14687 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14688 break; 14689 case BPF_NEG: 14690 env->fake_reg[0] = *dst_reg; 14691 __mark_reg_known(dst_reg, 0); 14692 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 14693 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 14694 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 14695 break; 14696 case BPF_MUL: 14697 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14698 scalar32_min_max_mul(dst_reg, &src_reg); 14699 scalar_min_max_mul(dst_reg, &src_reg); 14700 break; 14701 case BPF_DIV: 14702 /* BPF div specification: x / 0 = 0 */ 14703 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) { 14704 ___mark_reg_known(dst_reg, 0); 14705 break; 14706 } 14707 if (alu32) 14708 if (off == 1) 14709 scalar32_min_max_sdiv(dst_reg, &src_reg); 14710 else 14711 scalar32_min_max_udiv(dst_reg, &src_reg); 14712 else 14713 if (off == 1) 14714 scalar_min_max_sdiv(dst_reg, &src_reg); 14715 else 14716 scalar_min_max_udiv(dst_reg, &src_reg); 14717 break; 14718 case BPF_MOD: 14719 /* BPF mod specification: x % 0 = x */ 14720 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) 14721 break; 14722 if (alu32) 14723 if (off == 1) 14724 scalar32_min_max_smod(dst_reg, &src_reg); 14725 else 14726 scalar32_min_max_umod(dst_reg, &src_reg); 14727 else 14728 if (off == 1) 14729 scalar_min_max_smod(dst_reg, &src_reg); 14730 else 14731 scalar_min_max_umod(dst_reg, &src_reg); 14732 break; 14733 case BPF_AND: 14734 if (tnum_is_const(src_reg.var_off)) { 14735 ret = maybe_fork_scalars(env, insn, dst_reg); 14736 if (ret) 14737 return ret; 14738 } 14739 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14740 scalar32_min_max_and(dst_reg, &src_reg); 14741 scalar_min_max_and(dst_reg, &src_reg); 14742 break; 14743 case BPF_OR: 14744 if (tnum_is_const(src_reg.var_off)) { 14745 ret = maybe_fork_scalars(env, insn, dst_reg); 14746 if (ret) 14747 return ret; 14748 } 14749 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14750 scalar32_min_max_or(dst_reg, &src_reg); 14751 scalar_min_max_or(dst_reg, &src_reg); 14752 break; 14753 case BPF_XOR: 14754 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14755 scalar32_min_max_xor(dst_reg, &src_reg); 14756 scalar_min_max_xor(dst_reg, &src_reg); 14757 break; 14758 case BPF_LSH: 14759 if (alu32) 14760 scalar32_min_max_lsh(dst_reg, &src_reg); 14761 else 14762 scalar_min_max_lsh(dst_reg, &src_reg); 14763 break; 14764 case BPF_RSH: 14765 if (alu32) 14766 scalar32_min_max_rsh(dst_reg, &src_reg); 14767 else 14768 scalar_min_max_rsh(dst_reg, &src_reg); 14769 break; 14770 case BPF_ARSH: 14771 if (alu32) 14772 scalar32_min_max_arsh(dst_reg, &src_reg); 14773 else 14774 scalar_min_max_arsh(dst_reg, &src_reg); 14775 break; 14776 case BPF_END: 14777 scalar_byte_swap(dst_reg, insn); 14778 break; 14779 default: 14780 break; 14781 } 14782 14783 /* 14784 * ALU32 ops are zero extended into 64bit register. 14785 * 14786 * BPF_END is already handled inside the helper (truncation), 14787 * so skip zext here to avoid unexpected zero extension. 14788 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40 14789 * This is a 64bit byte swap operation with alu32==true, 14790 * but we should not zero extend the result. 14791 */ 14792 if (alu32 && opcode != BPF_END) 14793 zext_32_to_64(dst_reg); 14794 reg_bounds_sync(dst_reg); 14795 return 0; 14796 } 14797 14798 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14799 * and var_off. 14800 */ 14801 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14802 struct bpf_insn *insn) 14803 { 14804 struct bpf_verifier_state *vstate = env->cur_state; 14805 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14806 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14807 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14808 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14809 u8 opcode = BPF_OP(insn->code); 14810 int err; 14811 14812 dst_reg = ®s[insn->dst_reg]; 14813 if (BPF_SRC(insn->code) == BPF_X) 14814 src_reg = ®s[insn->src_reg]; 14815 else 14816 src_reg = NULL; 14817 14818 /* Case where at least one operand is an arena. */ 14819 if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) { 14820 struct bpf_insn_aux_data *aux = cur_aux(env); 14821 14822 if (dst_reg->type != PTR_TO_ARENA) 14823 *dst_reg = *src_reg; 14824 14825 dst_reg->subreg_def = env->insn_idx + 1; 14826 14827 if (BPF_CLASS(insn->code) == BPF_ALU64) 14828 /* 14829 * 32-bit operations zero upper bits automatically. 14830 * 64-bit operations need to be converted to 32. 14831 */ 14832 aux->needs_zext = true; 14833 14834 /* Any arithmetic operations are allowed on arena pointers */ 14835 return 0; 14836 } 14837 14838 if (dst_reg->type != SCALAR_VALUE) 14839 ptr_reg = dst_reg; 14840 14841 if (BPF_SRC(insn->code) == BPF_X) { 14842 if (src_reg->type != SCALAR_VALUE) { 14843 if (dst_reg->type != SCALAR_VALUE) { 14844 /* Combining two pointers by any ALU op yields 14845 * an arbitrary scalar. Disallow all math except 14846 * pointer subtraction 14847 */ 14848 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14849 mark_reg_unknown(env, regs, insn->dst_reg); 14850 return 0; 14851 } 14852 verbose(env, "R%d pointer %s pointer prohibited\n", 14853 insn->dst_reg, 14854 bpf_alu_string[opcode >> 4]); 14855 return -EACCES; 14856 } else { 14857 /* scalar += pointer 14858 * This is legal, but we have to reverse our 14859 * src/dest handling in computing the range 14860 */ 14861 err = mark_chain_precision(env, insn->dst_reg); 14862 if (err) 14863 return err; 14864 return adjust_ptr_min_max_vals(env, insn, 14865 src_reg, dst_reg); 14866 } 14867 } else if (ptr_reg) { 14868 /* pointer += scalar */ 14869 err = mark_chain_precision(env, insn->src_reg); 14870 if (err) 14871 return err; 14872 return adjust_ptr_min_max_vals(env, insn, 14873 dst_reg, src_reg); 14874 } else if (dst_reg->precise) { 14875 /* if dst_reg is precise, src_reg should be precise as well */ 14876 err = mark_chain_precision(env, insn->src_reg); 14877 if (err) 14878 return err; 14879 } 14880 } else { 14881 /* Pretend the src is a reg with a known value, since we only 14882 * need to be able to read from this state. 14883 */ 14884 off_reg.type = SCALAR_VALUE; 14885 __mark_reg_known(&off_reg, insn->imm); 14886 src_reg = &off_reg; 14887 if (ptr_reg) /* pointer += K */ 14888 return adjust_ptr_min_max_vals(env, insn, 14889 ptr_reg, src_reg); 14890 } 14891 14892 /* Got here implies adding two SCALAR_VALUEs */ 14893 if (WARN_ON_ONCE(ptr_reg)) { 14894 print_verifier_state(env, vstate, vstate->curframe, true); 14895 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14896 return -EFAULT; 14897 } 14898 if (WARN_ON(!src_reg)) { 14899 print_verifier_state(env, vstate, vstate->curframe, true); 14900 verbose(env, "verifier internal error: no src_reg\n"); 14901 return -EFAULT; 14902 } 14903 /* 14904 * For alu32 linked register tracking, we need to check dst_reg's 14905 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(), 14906 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX. 14907 */ 14908 u64 dst_umax = reg_umax(dst_reg); 14909 14910 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14911 if (err) 14912 return err; 14913 /* 14914 * Compilers can generate the code 14915 * r1 = r2 14916 * r1 += 0x1 14917 * if r2 < 1000 goto ... 14918 * use r1 in memory access 14919 * So remember constant delta between r2 and r1 and update r1 after 14920 * 'if' condition. 14921 */ 14922 if (env->bpf_capable && 14923 (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) && 14924 dst_reg->id && is_reg_const(src_reg, alu32) && 14925 !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) { 14926 u64 val = reg_const_value(src_reg, alu32); 14927 s32 off; 14928 14929 if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX)) 14930 goto clear_id; 14931 14932 if (alu32 && (dst_umax > U32_MAX)) 14933 goto clear_id; 14934 14935 off = (s32)val; 14936 14937 if (BPF_OP(insn->code) == BPF_SUB) { 14938 /* Negating S32_MIN would overflow */ 14939 if (off == S32_MIN) 14940 goto clear_id; 14941 off = -off; 14942 } 14943 14944 if (dst_reg->id & BPF_ADD_CONST) { 14945 /* 14946 * If the register already went through rX += val 14947 * we cannot accumulate another val into rx->off. 14948 */ 14949 clear_id: 14950 clear_scalar_id(dst_reg); 14951 } else { 14952 if (alu32) 14953 dst_reg->id |= BPF_ADD_CONST32; 14954 else 14955 dst_reg->id |= BPF_ADD_CONST64; 14956 dst_reg->delta = off; 14957 } 14958 } else { 14959 /* 14960 * Make sure ID is cleared otherwise dst_reg min/max could be 14961 * incorrectly propagated into other registers by sync_linked_regs() 14962 */ 14963 clear_scalar_id(dst_reg); 14964 } 14965 return 0; 14966 } 14967 14968 /* check validity of 32-bit and 64-bit arithmetic operations */ 14969 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14970 { 14971 struct bpf_reg_state *regs = cur_regs(env); 14972 u8 opcode = BPF_OP(insn->code); 14973 int err; 14974 14975 if (opcode == BPF_END || opcode == BPF_NEG) { 14976 /* check src operand */ 14977 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14978 if (err) 14979 return err; 14980 14981 if (is_pointer_value(env, insn->dst_reg)) { 14982 verbose(env, "R%d pointer arithmetic prohibited\n", 14983 insn->dst_reg); 14984 return -EACCES; 14985 } 14986 14987 /* check dest operand */ 14988 if (regs[insn->dst_reg].type == SCALAR_VALUE) { 14989 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14990 err = err ?: adjust_scalar_min_max_vals(env, insn, 14991 ®s[insn->dst_reg], 14992 regs[insn->dst_reg]); 14993 } else { 14994 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14995 } 14996 if (err) 14997 return err; 14998 14999 } else if (opcode == BPF_MOV) { 15000 15001 if (BPF_SRC(insn->code) == BPF_X) { 15002 if (insn->off == BPF_ADDR_SPACE_CAST) { 15003 if (!env->prog->aux->arena) { 15004 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 15005 return -EINVAL; 15006 } 15007 } 15008 15009 /* check src operand */ 15010 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15011 if (err) 15012 return err; 15013 } 15014 15015 /* check dest operand, mark as required later */ 15016 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15017 if (err) 15018 return err; 15019 15020 if (BPF_SRC(insn->code) == BPF_X) { 15021 struct bpf_reg_state *src_reg = regs + insn->src_reg; 15022 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 15023 15024 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15025 if (insn->imm) { 15026 /* off == BPF_ADDR_SPACE_CAST */ 15027 mark_reg_unknown(env, regs, insn->dst_reg); 15028 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 15029 dst_reg->type = PTR_TO_ARENA; 15030 /* PTR_TO_ARENA is 32-bit */ 15031 dst_reg->subreg_def = env->insn_idx + 1; 15032 } 15033 } else if (insn->off == 0) { 15034 /* case: R1 = R2 15035 * copy register state to dest reg 15036 */ 15037 assign_scalar_id_before_mov(env, src_reg); 15038 *dst_reg = *src_reg; 15039 dst_reg->subreg_def = DEF_NOT_SUBREG; 15040 } else { 15041 /* case: R1 = (s8, s16 s32)R2 */ 15042 if (is_pointer_value(env, insn->src_reg)) { 15043 verbose(env, 15044 "R%d sign-extension part of pointer\n", 15045 insn->src_reg); 15046 return -EACCES; 15047 } else if (src_reg->type == SCALAR_VALUE) { 15048 bool no_sext; 15049 15050 no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 15051 if (no_sext) 15052 assign_scalar_id_before_mov(env, src_reg); 15053 *dst_reg = *src_reg; 15054 if (!no_sext) 15055 clear_scalar_id(dst_reg); 15056 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 15057 dst_reg->subreg_def = DEF_NOT_SUBREG; 15058 } else { 15059 mark_reg_unknown(env, regs, insn->dst_reg); 15060 } 15061 } 15062 } else { 15063 /* R1 = (u32) R2 */ 15064 if (is_pointer_value(env, insn->src_reg)) { 15065 verbose(env, 15066 "R%d partial copy of pointer\n", 15067 insn->src_reg); 15068 return -EACCES; 15069 } else if (src_reg->type == SCALAR_VALUE) { 15070 if (insn->off == 0) { 15071 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 15072 15073 if (is_src_reg_u32) 15074 assign_scalar_id_before_mov(env, src_reg); 15075 *dst_reg = *src_reg; 15076 /* Make sure ID is cleared if src_reg is not in u32 15077 * range otherwise dst_reg min/max could be incorrectly 15078 * propagated into src_reg by sync_linked_regs() 15079 */ 15080 if (!is_src_reg_u32) 15081 clear_scalar_id(dst_reg); 15082 dst_reg->subreg_def = env->insn_idx + 1; 15083 } else { 15084 /* case: W1 = (s8, s16)W2 */ 15085 bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 15086 15087 if (no_sext) 15088 assign_scalar_id_before_mov(env, src_reg); 15089 *dst_reg = *src_reg; 15090 if (!no_sext) 15091 clear_scalar_id(dst_reg); 15092 dst_reg->subreg_def = env->insn_idx + 1; 15093 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 15094 } 15095 } else { 15096 mark_reg_unknown(env, regs, 15097 insn->dst_reg); 15098 } 15099 zext_32_to_64(dst_reg); 15100 reg_bounds_sync(dst_reg); 15101 } 15102 } else { 15103 /* case: R = imm 15104 * remember the value we stored into this reg 15105 */ 15106 /* clear any state __mark_reg_known doesn't set */ 15107 mark_reg_unknown(env, regs, insn->dst_reg); 15108 regs[insn->dst_reg].type = SCALAR_VALUE; 15109 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15110 __mark_reg_known(regs + insn->dst_reg, 15111 insn->imm); 15112 } else { 15113 __mark_reg_known(regs + insn->dst_reg, 15114 (u32)insn->imm); 15115 } 15116 } 15117 15118 } else { /* all other ALU ops: and, sub, xor, add, ... */ 15119 15120 if (BPF_SRC(insn->code) == BPF_X) { 15121 /* check src1 operand */ 15122 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15123 if (err) 15124 return err; 15125 } 15126 15127 /* check src2 operand */ 15128 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15129 if (err) 15130 return err; 15131 15132 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 15133 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 15134 verbose(env, "div by zero\n"); 15135 return -EINVAL; 15136 } 15137 15138 if ((opcode == BPF_LSH || opcode == BPF_RSH || 15139 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 15140 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 15141 15142 if (insn->imm < 0 || insn->imm >= size) { 15143 verbose(env, "invalid shift %d\n", insn->imm); 15144 return -EINVAL; 15145 } 15146 } 15147 15148 /* check dest operand */ 15149 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15150 err = err ?: adjust_reg_min_max_vals(env, insn); 15151 if (err) 15152 return err; 15153 } 15154 15155 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 15156 } 15157 15158 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 15159 struct bpf_reg_state *dst_reg, 15160 enum bpf_reg_type type, 15161 bool range_right_open) 15162 { 15163 struct bpf_func_state *state; 15164 struct bpf_reg_state *reg; 15165 int new_range; 15166 15167 if (reg_umax(dst_reg) == 0 && range_right_open) 15168 /* This doesn't give us any range */ 15169 return; 15170 15171 if (reg_umax(dst_reg) > MAX_PACKET_OFF) 15172 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15173 * than pkt_end, but that's because it's also less than pkt. 15174 */ 15175 return; 15176 15177 new_range = reg_umax(dst_reg); 15178 if (range_right_open) 15179 new_range++; 15180 15181 /* Examples for register markings: 15182 * 15183 * pkt_data in dst register: 15184 * 15185 * r2 = r3; 15186 * r2 += 8; 15187 * if (r2 > pkt_end) goto <handle exception> 15188 * <access okay> 15189 * 15190 * r2 = r3; 15191 * r2 += 8; 15192 * if (r2 < pkt_end) goto <access okay> 15193 * <handle exception> 15194 * 15195 * Where: 15196 * r2 == dst_reg, pkt_end == src_reg 15197 * r2=pkt(id=n,off=8,r=0) 15198 * r3=pkt(id=n,off=0,r=0) 15199 * 15200 * pkt_data in src register: 15201 * 15202 * r2 = r3; 15203 * r2 += 8; 15204 * if (pkt_end >= r2) goto <access okay> 15205 * <handle exception> 15206 * 15207 * r2 = r3; 15208 * r2 += 8; 15209 * if (pkt_end <= r2) goto <handle exception> 15210 * <access okay> 15211 * 15212 * Where: 15213 * pkt_end == dst_reg, r2 == src_reg 15214 * r2=pkt(id=n,off=8,r=0) 15215 * r3=pkt(id=n,off=0,r=0) 15216 * 15217 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15218 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15219 * and [r3, r3 + 8-1) respectively is safe to access depending on 15220 * the check. 15221 */ 15222 15223 /* If our ids match, then we must have the same max_value. And we 15224 * don't care about the other reg's fixed offset, since if it's too big 15225 * the range won't allow anything. 15226 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16. 15227 */ 15228 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15229 if (reg->type == type && reg->id == dst_reg->id) 15230 /* keep the maximum range already checked */ 15231 reg->range = max(reg->range, new_range); 15232 })); 15233 } 15234 15235 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15236 u8 opcode, bool is_jmp32); 15237 static u8 rev_opcode(u8 opcode); 15238 15239 /* 15240 * Learn more information about live branches by simulating refinement on both branches. 15241 * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means 15242 * that branch is dead. 15243 */ 15244 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32) 15245 { 15246 /* Fallthrough (FALSE) branch */ 15247 regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32); 15248 reg_bounds_sync(&env->false_reg1); 15249 reg_bounds_sync(&env->false_reg2); 15250 /* 15251 * If there is a range bounds violation in *any* of the abstract values in either 15252 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only 15253 * TRUE branch will be taken. 15254 */ 15255 if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2)) 15256 return 1; 15257 15258 /* Jump (TRUE) branch */ 15259 regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32); 15260 reg_bounds_sync(&env->true_reg1); 15261 reg_bounds_sync(&env->true_reg2); 15262 /* 15263 * If there is a range bounds violation in *any* of the abstract values in either 15264 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead. 15265 * Only FALSE branch will be taken. 15266 */ 15267 if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2)) 15268 return 0; 15269 15270 /* Both branches are possible, we can't determine which one will be taken. */ 15271 return -1; 15272 } 15273 15274 /* 15275 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15276 */ 15277 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15278 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15279 { 15280 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15281 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15282 u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1); 15283 u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1); 15284 s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1); 15285 s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1); 15286 u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2); 15287 u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2); 15288 s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2); 15289 s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2); 15290 15291 if (reg1 == reg2) { 15292 switch (opcode) { 15293 case BPF_JGE: 15294 case BPF_JLE: 15295 case BPF_JSGE: 15296 case BPF_JSLE: 15297 case BPF_JEQ: 15298 return 1; 15299 case BPF_JGT: 15300 case BPF_JLT: 15301 case BPF_JSGT: 15302 case BPF_JSLT: 15303 case BPF_JNE: 15304 return 0; 15305 case BPF_JSET: 15306 if (tnum_is_const(t1)) 15307 return t1.value != 0; 15308 else 15309 return (smin1 <= 0 && smax1 >= 0) ? -1 : 1; 15310 default: 15311 return -1; 15312 } 15313 } 15314 15315 switch (opcode) { 15316 case BPF_JEQ: 15317 /* constants, umin/umax and smin/smax checks would be 15318 * redundant in this case because they all should match 15319 */ 15320 if (tnum_is_const(t1) && tnum_is_const(t2)) 15321 return t1.value == t2.value; 15322 if (!tnum_overlap(t1, t2)) 15323 return 0; 15324 /* non-overlapping ranges */ 15325 if (umin1 > umax2 || umax1 < umin2) 15326 return 0; 15327 if (smin1 > smax2 || smax1 < smin2) 15328 return 0; 15329 if (!is_jmp32) { 15330 /* if 64-bit ranges are inconclusive, see if we can 15331 * utilize 32-bit subrange knowledge to eliminate 15332 * branches that can't be taken a priori 15333 */ 15334 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15335 reg_u32_max(reg1) < reg_u32_min(reg2)) 15336 return 0; 15337 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15338 reg_s32_max(reg1) < reg_s32_min(reg2)) 15339 return 0; 15340 } 15341 break; 15342 case BPF_JNE: 15343 /* constants, umin/umax and smin/smax checks would be 15344 * redundant in this case because they all should match 15345 */ 15346 if (tnum_is_const(t1) && tnum_is_const(t2)) 15347 return t1.value != t2.value; 15348 if (!tnum_overlap(t1, t2)) 15349 return 1; 15350 /* non-overlapping ranges */ 15351 if (umin1 > umax2 || umax1 < umin2) 15352 return 1; 15353 if (smin1 > smax2 || smax1 < smin2) 15354 return 1; 15355 if (!is_jmp32) { 15356 /* if 64-bit ranges are inconclusive, see if we can 15357 * utilize 32-bit subrange knowledge to eliminate 15358 * branches that can't be taken a priori 15359 */ 15360 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15361 reg_u32_max(reg1) < reg_u32_min(reg2)) 15362 return 1; 15363 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15364 reg_s32_max(reg1) < reg_s32_min(reg2)) 15365 return 1; 15366 } 15367 break; 15368 case BPF_JSET: 15369 if (!is_reg_const(reg2, is_jmp32)) { 15370 swap(reg1, reg2); 15371 swap(t1, t2); 15372 } 15373 if (!is_reg_const(reg2, is_jmp32)) 15374 return -1; 15375 if ((~t1.mask & t1.value) & t2.value) 15376 return 1; 15377 if (!((t1.mask | t1.value) & t2.value)) 15378 return 0; 15379 break; 15380 case BPF_JGT: 15381 if (umin1 > umax2) 15382 return 1; 15383 else if (umax1 <= umin2) 15384 return 0; 15385 break; 15386 case BPF_JSGT: 15387 if (smin1 > smax2) 15388 return 1; 15389 else if (smax1 <= smin2) 15390 return 0; 15391 break; 15392 case BPF_JLT: 15393 if (umax1 < umin2) 15394 return 1; 15395 else if (umin1 >= umax2) 15396 return 0; 15397 break; 15398 case BPF_JSLT: 15399 if (smax1 < smin2) 15400 return 1; 15401 else if (smin1 >= smax2) 15402 return 0; 15403 break; 15404 case BPF_JGE: 15405 if (umin1 >= umax2) 15406 return 1; 15407 else if (umax1 < umin2) 15408 return 0; 15409 break; 15410 case BPF_JSGE: 15411 if (smin1 >= smax2) 15412 return 1; 15413 else if (smax1 < smin2) 15414 return 0; 15415 break; 15416 case BPF_JLE: 15417 if (umax1 <= umin2) 15418 return 1; 15419 else if (umin1 > umax2) 15420 return 0; 15421 break; 15422 case BPF_JSLE: 15423 if (smax1 <= smin2) 15424 return 1; 15425 else if (smin1 > smax2) 15426 return 0; 15427 break; 15428 } 15429 15430 return simulate_both_branches_taken(env, opcode, is_jmp32); 15431 } 15432 15433 static int flip_opcode(u32 opcode) 15434 { 15435 /* How can we transform "a <op> b" into "b <op> a"? */ 15436 static const u8 opcode_flip[16] = { 15437 /* these stay the same */ 15438 [BPF_JEQ >> 4] = BPF_JEQ, 15439 [BPF_JNE >> 4] = BPF_JNE, 15440 [BPF_JSET >> 4] = BPF_JSET, 15441 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 15442 [BPF_JGE >> 4] = BPF_JLE, 15443 [BPF_JGT >> 4] = BPF_JLT, 15444 [BPF_JLE >> 4] = BPF_JGE, 15445 [BPF_JLT >> 4] = BPF_JGT, 15446 [BPF_JSGE >> 4] = BPF_JSLE, 15447 [BPF_JSGT >> 4] = BPF_JSLT, 15448 [BPF_JSLE >> 4] = BPF_JSGE, 15449 [BPF_JSLT >> 4] = BPF_JSGT 15450 }; 15451 return opcode_flip[opcode >> 4]; 15452 } 15453 15454 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 15455 struct bpf_reg_state *src_reg, 15456 u8 opcode) 15457 { 15458 struct bpf_reg_state *pkt; 15459 15460 if (src_reg->type == PTR_TO_PACKET_END) { 15461 pkt = dst_reg; 15462 } else if (dst_reg->type == PTR_TO_PACKET_END) { 15463 pkt = src_reg; 15464 opcode = flip_opcode(opcode); 15465 } else { 15466 return -1; 15467 } 15468 15469 if (pkt->range >= 0) 15470 return -1; 15471 15472 switch (opcode) { 15473 case BPF_JLE: 15474 /* pkt <= pkt_end */ 15475 fallthrough; 15476 case BPF_JGT: 15477 /* pkt > pkt_end */ 15478 if (pkt->range == BEYOND_PKT_END) 15479 /* pkt has at last one extra byte beyond pkt_end */ 15480 return opcode == BPF_JGT; 15481 break; 15482 case BPF_JLT: 15483 /* pkt < pkt_end */ 15484 fallthrough; 15485 case BPF_JGE: 15486 /* pkt >= pkt_end */ 15487 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 15488 return opcode == BPF_JGE; 15489 break; 15490 } 15491 return -1; 15492 } 15493 15494 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 15495 * and return: 15496 * 1 - branch will be taken and "goto target" will be executed 15497 * 0 - branch will not be taken and fall-through to next insn 15498 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 15499 * range [0,10] 15500 */ 15501 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15502 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15503 { 15504 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 15505 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 15506 15507 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 15508 u64 val; 15509 15510 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 15511 if (!is_reg_const(reg2, is_jmp32)) { 15512 opcode = flip_opcode(opcode); 15513 swap(reg1, reg2); 15514 } 15515 /* and ensure that reg2 is a constant */ 15516 if (!is_reg_const(reg2, is_jmp32)) 15517 return -1; 15518 15519 if (!reg_not_null(env, reg1)) 15520 return -1; 15521 15522 /* If pointer is valid tests against zero will fail so we can 15523 * use this to direct branch taken. 15524 */ 15525 val = reg_const_value(reg2, is_jmp32); 15526 if (val != 0) 15527 return -1; 15528 15529 switch (opcode) { 15530 case BPF_JEQ: 15531 return 0; 15532 case BPF_JNE: 15533 return 1; 15534 default: 15535 return -1; 15536 } 15537 } 15538 15539 /* now deal with two scalars, but not necessarily constants */ 15540 return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32); 15541 } 15542 15543 /* Opcode that corresponds to a *false* branch condition. 15544 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 15545 */ 15546 static u8 rev_opcode(u8 opcode) 15547 { 15548 switch (opcode) { 15549 case BPF_JEQ: return BPF_JNE; 15550 case BPF_JNE: return BPF_JEQ; 15551 /* JSET doesn't have it's reverse opcode in BPF, so add 15552 * BPF_X flag to denote the reverse of that operation 15553 */ 15554 case BPF_JSET: return BPF_JSET | BPF_X; 15555 case BPF_JSET | BPF_X: return BPF_JSET; 15556 case BPF_JGE: return BPF_JLT; 15557 case BPF_JGT: return BPF_JLE; 15558 case BPF_JLE: return BPF_JGT; 15559 case BPF_JLT: return BPF_JGE; 15560 case BPF_JSGE: return BPF_JSLT; 15561 case BPF_JSGT: return BPF_JSLE; 15562 case BPF_JSLE: return BPF_JSGT; 15563 case BPF_JSLT: return BPF_JSGE; 15564 default: return 0; 15565 } 15566 } 15567 15568 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 15569 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15570 u8 opcode, bool is_jmp32) 15571 { 15572 struct tnum t; 15573 u64 val; 15574 15575 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 15576 switch (opcode) { 15577 case BPF_JGE: 15578 case BPF_JGT: 15579 case BPF_JSGE: 15580 case BPF_JSGT: 15581 opcode = flip_opcode(opcode); 15582 swap(reg1, reg2); 15583 break; 15584 default: 15585 break; 15586 } 15587 15588 switch (opcode) { 15589 case BPF_JEQ: 15590 if (is_jmp32) { 15591 reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32); 15592 reg2->r32 = reg1->r32; 15593 15594 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 15595 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15596 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 15597 } else { 15598 reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64); 15599 reg2->r64 = reg1->r64; 15600 15601 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 15602 reg2->var_off = reg1->var_off; 15603 } 15604 break; 15605 case BPF_JNE: 15606 if (!is_reg_const(reg2, is_jmp32)) 15607 swap(reg1, reg2); 15608 if (!is_reg_const(reg2, is_jmp32)) 15609 break; 15610 15611 /* try to recompute the bound of reg1 if reg2 is a const and 15612 * is exactly the edge of reg1. 15613 */ 15614 val = reg_const_value(reg2, is_jmp32); 15615 if (is_jmp32) { 15616 /* Complement of the range [val, val] as cnum32. */ 15617 cnum32_intersect_with(®1->r32, (struct cnum32){ val + 1, U32_MAX - 1 }); 15618 } else { 15619 /* Complement of the range [val, val] as cnum64. */ 15620 cnum64_intersect_with(®1->r64, (struct cnum64){ val + 1, U64_MAX - 1 }); 15621 } 15622 break; 15623 case BPF_JSET: 15624 if (!is_reg_const(reg2, is_jmp32)) 15625 swap(reg1, reg2); 15626 if (!is_reg_const(reg2, is_jmp32)) 15627 break; 15628 val = reg_const_value(reg2, is_jmp32); 15629 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 15630 * requires single bit to learn something useful. E.g., if we 15631 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 15632 * are actually set? We can learn something definite only if 15633 * it's a single-bit value to begin with. 15634 * 15635 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 15636 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 15637 * bit 1 is set, which we can readily use in adjustments. 15638 */ 15639 if (!is_power_of_2(val)) 15640 break; 15641 if (is_jmp32) { 15642 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 15643 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15644 } else { 15645 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 15646 } 15647 break; 15648 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 15649 if (!is_reg_const(reg2, is_jmp32)) 15650 swap(reg1, reg2); 15651 if (!is_reg_const(reg2, is_jmp32)) 15652 break; 15653 val = reg_const_value(reg2, is_jmp32); 15654 /* Forget the ranges before narrowing tnums, to avoid invariant 15655 * violations if we're on a dead branch. 15656 */ 15657 __mark_reg_unbounded(reg1); 15658 if (is_jmp32) { 15659 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 15660 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15661 } else { 15662 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15663 } 15664 break; 15665 case BPF_JLE: 15666 if (is_jmp32) { 15667 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2)); 15668 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1), U32_MAX); 15669 } else { 15670 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2)); 15671 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1), U64_MAX); 15672 } 15673 break; 15674 case BPF_JLT: 15675 if (is_jmp32) { 15676 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2) - 1); 15677 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1) + 1, U32_MAX); 15678 } else { 15679 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2) - 1); 15680 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1) + 1, U64_MAX); 15681 } 15682 break; 15683 case BPF_JSLE: 15684 if (is_jmp32) { 15685 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2)); 15686 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1), S32_MAX); 15687 } else { 15688 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2)); 15689 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1), S64_MAX); 15690 } 15691 break; 15692 case BPF_JSLT: 15693 if (is_jmp32) { 15694 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2) - 1); 15695 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1) + 1, S32_MAX); 15696 } else { 15697 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2) - 1); 15698 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1) + 1, S64_MAX); 15699 } 15700 break; 15701 default: 15702 return; 15703 } 15704 } 15705 15706 /* Check for invariant violations on the registers for both branches of a condition */ 15707 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env) 15708 { 15709 int err; 15710 15711 err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1"); 15712 err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2"); 15713 err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1"); 15714 err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2"); 15715 return err; 15716 } 15717 15718 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 15719 struct bpf_reg_state *reg, u32 id, 15720 bool is_null) 15721 { 15722 if (type_may_be_null(reg->type) && reg->id == id && 15723 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 15724 /* Old offset should have been known-zero, because we don't 15725 * allow pointer arithmetic on pointers that might be NULL. 15726 * If we see this happening, don't convert the register. 15727 * 15728 * But in some cases, some helpers that return local kptrs 15729 * advance offset for the returned pointer. In those cases, 15730 * it is fine to expect to see reg->var_off. 15731 */ 15732 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 15733 WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0))) 15734 return; 15735 if (is_null) { 15736 /* We don't need id from this point 15737 * onwards anymore, thus we should better reset it, 15738 * so that state pruning has chances to take effect. 15739 */ 15740 __mark_reg_known_zero(reg); 15741 reg->type = SCALAR_VALUE; 15742 15743 return; 15744 } 15745 15746 mark_ptr_not_null_reg(reg); 15747 15748 /* 15749 * reg->id is preserved for object relationship tracking 15750 * and spin_lock lock state tracking 15751 */ 15752 } 15753 } 15754 15755 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15756 * be folded together at some point. 15757 */ 15758 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15759 bool is_null) 15760 { 15761 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15762 struct bpf_reg_state *regs = state->regs, *reg; 15763 u32 id = regs[regno].id; 15764 15765 if (is_null && find_reference_state(vstate, id)) 15766 /* regs[regno] is in the " == NULL" branch. 15767 * No one could have freed the reference state before 15768 * doing the NULL check. 15769 */ 15770 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 15771 15772 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15773 mark_ptr_or_null_reg(state, reg, id, is_null); 15774 })); 15775 } 15776 15777 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15778 struct bpf_reg_state *dst_reg, 15779 struct bpf_reg_state *src_reg, 15780 struct bpf_verifier_state *this_branch, 15781 struct bpf_verifier_state *other_branch) 15782 { 15783 if (BPF_SRC(insn->code) != BPF_X) 15784 return false; 15785 15786 /* Pointers are always 64-bit. */ 15787 if (BPF_CLASS(insn->code) == BPF_JMP32) 15788 return false; 15789 15790 switch (BPF_OP(insn->code)) { 15791 case BPF_JGT: 15792 if ((dst_reg->type == PTR_TO_PACKET && 15793 src_reg->type == PTR_TO_PACKET_END) || 15794 (dst_reg->type == PTR_TO_PACKET_META && 15795 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15796 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15797 find_good_pkt_pointers(this_branch, dst_reg, 15798 dst_reg->type, false); 15799 mark_pkt_end(other_branch, insn->dst_reg, true); 15800 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15801 src_reg->type == PTR_TO_PACKET) || 15802 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15803 src_reg->type == PTR_TO_PACKET_META)) { 15804 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15805 find_good_pkt_pointers(other_branch, src_reg, 15806 src_reg->type, true); 15807 mark_pkt_end(this_branch, insn->src_reg, false); 15808 } else { 15809 return false; 15810 } 15811 break; 15812 case BPF_JLT: 15813 if ((dst_reg->type == PTR_TO_PACKET && 15814 src_reg->type == PTR_TO_PACKET_END) || 15815 (dst_reg->type == PTR_TO_PACKET_META && 15816 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15817 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15818 find_good_pkt_pointers(other_branch, dst_reg, 15819 dst_reg->type, true); 15820 mark_pkt_end(this_branch, insn->dst_reg, false); 15821 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15822 src_reg->type == PTR_TO_PACKET) || 15823 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15824 src_reg->type == PTR_TO_PACKET_META)) { 15825 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15826 find_good_pkt_pointers(this_branch, src_reg, 15827 src_reg->type, false); 15828 mark_pkt_end(other_branch, insn->src_reg, true); 15829 } else { 15830 return false; 15831 } 15832 break; 15833 case BPF_JGE: 15834 if ((dst_reg->type == PTR_TO_PACKET && 15835 src_reg->type == PTR_TO_PACKET_END) || 15836 (dst_reg->type == PTR_TO_PACKET_META && 15837 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15838 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15839 find_good_pkt_pointers(this_branch, dst_reg, 15840 dst_reg->type, true); 15841 mark_pkt_end(other_branch, insn->dst_reg, false); 15842 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15843 src_reg->type == PTR_TO_PACKET) || 15844 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15845 src_reg->type == PTR_TO_PACKET_META)) { 15846 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15847 find_good_pkt_pointers(other_branch, src_reg, 15848 src_reg->type, false); 15849 mark_pkt_end(this_branch, insn->src_reg, true); 15850 } else { 15851 return false; 15852 } 15853 break; 15854 case BPF_JLE: 15855 if ((dst_reg->type == PTR_TO_PACKET && 15856 src_reg->type == PTR_TO_PACKET_END) || 15857 (dst_reg->type == PTR_TO_PACKET_META && 15858 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15859 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15860 find_good_pkt_pointers(other_branch, dst_reg, 15861 dst_reg->type, false); 15862 mark_pkt_end(this_branch, insn->dst_reg, true); 15863 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15864 src_reg->type == PTR_TO_PACKET) || 15865 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15866 src_reg->type == PTR_TO_PACKET_META)) { 15867 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15868 find_good_pkt_pointers(this_branch, src_reg, 15869 src_reg->type, true); 15870 mark_pkt_end(other_branch, insn->src_reg, false); 15871 } else { 15872 return false; 15873 } 15874 break; 15875 default: 15876 return false; 15877 } 15878 15879 return true; 15880 } 15881 15882 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 15883 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 15884 { 15885 struct linked_reg *e; 15886 15887 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 15888 return; 15889 15890 e = linked_regs_push(reg_set); 15891 if (e) { 15892 e->frameno = frameno; 15893 e->is_reg = is_reg; 15894 e->regno = spi_or_reg; 15895 } else { 15896 clear_scalar_id(reg); 15897 } 15898 } 15899 15900 /* For all R being scalar registers or spilled scalar registers 15901 * in verifier state, save R in linked_regs if R->id == id. 15902 * If there are too many Rs sharing same id, reset id for leftover Rs. 15903 */ 15904 static void collect_linked_regs(struct bpf_verifier_env *env, 15905 struct bpf_verifier_state *vstate, 15906 u32 id, 15907 struct linked_regs *linked_regs) 15908 { 15909 struct bpf_insn_aux_data *aux = env->insn_aux_data; 15910 struct bpf_func_state *func; 15911 struct bpf_reg_state *reg; 15912 u16 live_regs; 15913 int i, j; 15914 15915 id = id & ~BPF_ADD_CONST; 15916 for (i = vstate->curframe; i >= 0; i--) { 15917 live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before; 15918 func = vstate->frame[i]; 15919 for (j = 0; j < BPF_REG_FP; j++) { 15920 if (!(live_regs & BIT(j))) 15921 continue; 15922 reg = &func->regs[j]; 15923 __collect_linked_regs(linked_regs, reg, id, i, j, true); 15924 } 15925 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 15926 if (!bpf_is_spilled_reg(&func->stack[j])) 15927 continue; 15928 reg = &func->stack[j].spilled_ptr; 15929 __collect_linked_regs(linked_regs, reg, id, i, j, false); 15930 } 15931 } 15932 } 15933 15934 /* For all R in linked_regs, copy known_reg range into R 15935 * if R->id == known_reg->id. 15936 */ 15937 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate, 15938 struct bpf_reg_state *known_reg, struct linked_regs *linked_regs) 15939 { 15940 struct bpf_reg_state fake_reg; 15941 struct bpf_reg_state *reg; 15942 struct linked_reg *e; 15943 int i; 15944 15945 for (i = 0; i < linked_regs->cnt; ++i) { 15946 e = &linked_regs->entries[i]; 15947 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 15948 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 15949 if (reg->type != SCALAR_VALUE || reg == known_reg) 15950 continue; 15951 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15952 continue; 15953 /* 15954 * Skip mixed 32/64-bit links: the delta relationship doesn't 15955 * hold across different ALU widths. 15956 */ 15957 if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST) 15958 continue; 15959 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15960 reg->delta == known_reg->delta) { 15961 s32 saved_subreg_def = reg->subreg_def; 15962 15963 *reg = *known_reg; 15964 reg->subreg_def = saved_subreg_def; 15965 } else { 15966 s32 saved_subreg_def = reg->subreg_def; 15967 s32 saved_off = reg->delta; 15968 u32 saved_id = reg->id; 15969 15970 fake_reg.type = SCALAR_VALUE; 15971 __mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta); 15972 15973 /* reg = known_reg; reg += delta */ 15974 *reg = *known_reg; 15975 /* 15976 * Must preserve off, id and subreg_def flag, 15977 * otherwise another sync_linked_regs() will be incorrect. 15978 */ 15979 reg->delta = saved_off; 15980 reg->id = saved_id; 15981 reg->subreg_def = saved_subreg_def; 15982 15983 scalar32_min_max_add(reg, &fake_reg); 15984 scalar_min_max_add(reg, &fake_reg); 15985 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15986 if ((reg->id | known_reg->id) & BPF_ADD_CONST32) 15987 zext_32_to_64(reg); 15988 reg_bounds_sync(reg); 15989 } 15990 if (e->is_reg) 15991 mark_reg_scratched(env, e->regno); 15992 else 15993 mark_stack_slot_scratched(env, e->spi); 15994 } 15995 } 15996 15997 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15998 struct bpf_insn *insn, int *insn_idx) 15999 { 16000 struct bpf_verifier_state *this_branch = env->cur_state; 16001 struct bpf_verifier_state *other_branch; 16002 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 16003 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 16004 struct bpf_reg_state *eq_branch_regs; 16005 struct linked_regs linked_regs = {}; 16006 u8 opcode = BPF_OP(insn->code); 16007 int insn_flags = 0; 16008 bool is_jmp32; 16009 int pred = -1; 16010 int err; 16011 16012 /* Only conditional jumps are expected to reach here. */ 16013 if (opcode == BPF_JA || opcode > BPF_JCOND) { 16014 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 16015 return -EINVAL; 16016 } 16017 16018 if (opcode == BPF_JCOND) { 16019 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 16020 int idx = *insn_idx; 16021 16022 prev_st = find_prev_entry(env, cur_st->parent, idx); 16023 16024 /* branch out 'fallthrough' insn as a new state to explore */ 16025 queued_st = push_stack(env, idx + 1, idx, false); 16026 if (IS_ERR(queued_st)) 16027 return PTR_ERR(queued_st); 16028 16029 queued_st->may_goto_depth++; 16030 if (prev_st) 16031 widen_imprecise_scalars(env, prev_st, queued_st); 16032 *insn_idx += insn->off; 16033 return 0; 16034 } 16035 16036 /* check src2 operand */ 16037 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16038 if (err) 16039 return err; 16040 16041 dst_reg = ®s[insn->dst_reg]; 16042 if (BPF_SRC(insn->code) == BPF_X) { 16043 /* check src1 operand */ 16044 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16045 if (err) 16046 return err; 16047 16048 src_reg = ®s[insn->src_reg]; 16049 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 16050 is_pointer_value(env, insn->src_reg)) { 16051 verbose(env, "R%d pointer comparison prohibited\n", 16052 insn->src_reg); 16053 return -EACCES; 16054 } 16055 16056 if (src_reg->type == PTR_TO_STACK) 16057 insn_flags |= INSN_F_SRC_REG_STACK; 16058 if (dst_reg->type == PTR_TO_STACK) 16059 insn_flags |= INSN_F_DST_REG_STACK; 16060 } else { 16061 src_reg = &env->fake_reg[0]; 16062 memset(src_reg, 0, sizeof(*src_reg)); 16063 src_reg->type = SCALAR_VALUE; 16064 __mark_reg_known(src_reg, insn->imm); 16065 16066 if (dst_reg->type == PTR_TO_STACK) 16067 insn_flags |= INSN_F_DST_REG_STACK; 16068 } 16069 16070 if (insn_flags) { 16071 err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, 0); 16072 if (err) 16073 return err; 16074 } 16075 16076 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 16077 env->false_reg1 = *dst_reg; 16078 env->false_reg2 = *src_reg; 16079 env->true_reg1 = *dst_reg; 16080 env->true_reg2 = *src_reg; 16081 pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32); 16082 if (pred >= 0) { 16083 /* If we get here with a dst_reg pointer type it is because 16084 * above is_branch_taken() special cased the 0 comparison. 16085 */ 16086 if (!__is_pointer_value(false, dst_reg)) 16087 err = mark_chain_precision(env, insn->dst_reg); 16088 if (BPF_SRC(insn->code) == BPF_X && !err && 16089 !__is_pointer_value(false, src_reg)) 16090 err = mark_chain_precision(env, insn->src_reg); 16091 if (err) 16092 return err; 16093 } 16094 16095 if (pred == 1) { 16096 /* Only follow the goto, ignore fall-through. If needed, push 16097 * the fall-through branch for simulation under speculative 16098 * execution. 16099 */ 16100 if (!env->bypass_spec_v1) { 16101 err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx); 16102 if (err < 0) 16103 return err; 16104 } 16105 if (env->log.level & BPF_LOG_LEVEL) 16106 print_insn_state(env, this_branch, this_branch->curframe); 16107 *insn_idx += insn->off; 16108 return 0; 16109 } else if (pred == 0) { 16110 /* Only follow the fall-through branch, since that's where the 16111 * program will go. If needed, push the goto branch for 16112 * simulation under speculative execution. 16113 */ 16114 if (!env->bypass_spec_v1) { 16115 err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1, 16116 *insn_idx); 16117 if (err < 0) 16118 return err; 16119 } 16120 if (env->log.level & BPF_LOG_LEVEL) 16121 print_insn_state(env, this_branch, this_branch->curframe); 16122 return 0; 16123 } 16124 16125 /* Push scalar registers sharing same ID to jump history, 16126 * do this before creating 'other_branch', so that both 16127 * 'this_branch' and 'other_branch' share this history 16128 * if parent state is created. 16129 */ 16130 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 16131 collect_linked_regs(env, this_branch, src_reg->id, &linked_regs); 16132 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 16133 collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs); 16134 if (linked_regs.cnt > 1) { 16135 err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, linked_regs_pack(&linked_regs)); 16136 if (err) 16137 return err; 16138 } 16139 16140 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); 16141 if (IS_ERR(other_branch)) 16142 return PTR_ERR(other_branch); 16143 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 16144 16145 err = regs_bounds_sanity_check_branches(env); 16146 if (err) 16147 return err; 16148 16149 *dst_reg = env->false_reg1; 16150 *src_reg = env->false_reg2; 16151 other_branch_regs[insn->dst_reg] = env->true_reg1; 16152 if (BPF_SRC(insn->code) == BPF_X) 16153 other_branch_regs[insn->src_reg] = env->true_reg2; 16154 16155 if (BPF_SRC(insn->code) == BPF_X && 16156 src_reg->type == SCALAR_VALUE && src_reg->id && 16157 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 16158 sync_linked_regs(env, this_branch, src_reg, &linked_regs); 16159 sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg], 16160 &linked_regs); 16161 } 16162 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 16163 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 16164 sync_linked_regs(env, this_branch, dst_reg, &linked_regs); 16165 sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg], 16166 &linked_regs); 16167 } 16168 16169 /* if one pointer register is compared to another pointer 16170 * register check if PTR_MAYBE_NULL could be lifted. 16171 * E.g. register A - maybe null 16172 * register B - not null 16173 * for JNE A, B, ... - A is not null in the false branch; 16174 * for JEQ A, B, ... - A is not null in the true branch. 16175 * 16176 * Since PTR_TO_BTF_ID points to a kernel struct that does 16177 * not need to be null checked by the BPF program, i.e., 16178 * could be null even without PTR_MAYBE_NULL marking, so 16179 * only propagate nullness when neither reg is that type. 16180 */ 16181 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16182 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16183 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16184 base_type(src_reg->type) != PTR_TO_BTF_ID && 16185 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16186 eq_branch_regs = NULL; 16187 switch (opcode) { 16188 case BPF_JEQ: 16189 eq_branch_regs = other_branch_regs; 16190 break; 16191 case BPF_JNE: 16192 eq_branch_regs = regs; 16193 break; 16194 default: 16195 /* do nothing */ 16196 break; 16197 } 16198 if (eq_branch_regs) { 16199 if (type_may_be_null(src_reg->type)) 16200 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16201 else 16202 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16203 } 16204 } 16205 16206 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16207 * Also does the same detection for a register whose the value is 16208 * known to be 0. 16209 * NOTE: these optimizations below are related with pointer comparison 16210 * which will never be JMP32. 16211 */ 16212 if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16213 type_may_be_null(dst_reg->type) && 16214 ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) || 16215 (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) { 16216 /* Mark all identical registers in each branch as either 16217 * safe or unknown depending R == 0 or R != 0 conditional. 16218 */ 16219 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16220 opcode == BPF_JNE); 16221 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16222 opcode == BPF_JEQ); 16223 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16224 this_branch, other_branch) && 16225 is_pointer_value(env, insn->dst_reg)) { 16226 verbose(env, "R%d pointer comparison prohibited\n", 16227 insn->dst_reg); 16228 return -EACCES; 16229 } 16230 if (env->log.level & BPF_LOG_LEVEL) 16231 print_insn_state(env, this_branch, this_branch->curframe); 16232 return 0; 16233 } 16234 16235 /* verify BPF_LD_IMM64 instruction */ 16236 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16237 { 16238 struct bpf_insn_aux_data *aux = cur_aux(env); 16239 struct bpf_reg_state *regs = cur_regs(env); 16240 struct bpf_reg_state *dst_reg; 16241 struct bpf_map *map; 16242 int err; 16243 16244 if (BPF_SIZE(insn->code) != BPF_DW) { 16245 verbose(env, "invalid BPF_LD_IMM insn\n"); 16246 return -EINVAL; 16247 } 16248 16249 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16250 if (err) 16251 return err; 16252 16253 dst_reg = ®s[insn->dst_reg]; 16254 if (insn->src_reg == 0) { 16255 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16256 16257 dst_reg->type = SCALAR_VALUE; 16258 __mark_reg_known(®s[insn->dst_reg], imm); 16259 return 0; 16260 } 16261 16262 /* All special src_reg cases are listed below. From this point onwards 16263 * we either succeed and assign a corresponding dst_reg->type after 16264 * zeroing the offset, or fail and reject the program. 16265 */ 16266 mark_reg_known_zero(env, regs, insn->dst_reg); 16267 16268 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16269 dst_reg->type = aux->btf_var.reg_type; 16270 switch (base_type(dst_reg->type)) { 16271 case PTR_TO_MEM: 16272 dst_reg->mem_size = aux->btf_var.mem_size; 16273 break; 16274 case PTR_TO_BTF_ID: 16275 dst_reg->btf = aux->btf_var.btf; 16276 dst_reg->btf_id = aux->btf_var.btf_id; 16277 break; 16278 default: 16279 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 16280 return -EFAULT; 16281 } 16282 return 0; 16283 } 16284 16285 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16286 struct bpf_prog_aux *aux = env->prog->aux; 16287 u32 subprogno = bpf_find_subprog(env, 16288 env->insn_idx + insn->imm + 1); 16289 16290 if (!aux->func_info) { 16291 verbose(env, "missing btf func_info\n"); 16292 return -EINVAL; 16293 } 16294 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16295 verbose(env, "callback function not static\n"); 16296 return -EINVAL; 16297 } 16298 16299 dst_reg->type = PTR_TO_FUNC; 16300 dst_reg->subprogno = subprogno; 16301 return 0; 16302 } 16303 16304 map = env->used_maps[aux->map_index]; 16305 16306 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16307 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16308 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16309 __mark_reg_unknown(env, dst_reg); 16310 dst_reg->map_ptr = map; 16311 return 0; 16312 } 16313 __mark_reg_known(dst_reg, aux->map_off); 16314 dst_reg->type = PTR_TO_MAP_VALUE; 16315 dst_reg->map_ptr = map; 16316 WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY && 16317 map->max_entries != 1); 16318 /* We want reg->id to be same (0) as map_value is not distinct */ 16319 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16320 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16321 dst_reg->type = CONST_PTR_TO_MAP; 16322 dst_reg->map_ptr = map; 16323 } else { 16324 verifier_bug(env, "unexpected src reg value for ldimm64"); 16325 return -EFAULT; 16326 } 16327 16328 return 0; 16329 } 16330 16331 static bool may_access_skb(enum bpf_prog_type type) 16332 { 16333 switch (type) { 16334 case BPF_PROG_TYPE_SOCKET_FILTER: 16335 case BPF_PROG_TYPE_SCHED_CLS: 16336 case BPF_PROG_TYPE_SCHED_ACT: 16337 return true; 16338 default: 16339 return false; 16340 } 16341 } 16342 16343 /* verify safety of LD_ABS|LD_IND instructions: 16344 * - they can only appear in the programs where ctx == skb 16345 * - since they are wrappers of function calls, they scratch R1-R5 registers, 16346 * preserve R6-R9, and store return value into R0 16347 * 16348 * Implicit input: 16349 * ctx == skb == R6 == CTX 16350 * 16351 * Explicit input: 16352 * SRC == any register 16353 * IMM == 32-bit immediate 16354 * 16355 * Output: 16356 * R0 - 8/16/32-bit skb data converted to cpu endianness 16357 */ 16358 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 16359 { 16360 struct bpf_reg_state *regs = cur_regs(env); 16361 static const int ctx_reg = BPF_REG_6; 16362 u8 mode = BPF_MODE(insn->code); 16363 int i, err; 16364 16365 if (!may_access_skb(resolve_prog_type(env->prog))) { 16366 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 16367 return -EINVAL; 16368 } 16369 16370 if (!env->ops->gen_ld_abs) { 16371 verifier_bug(env, "gen_ld_abs is null"); 16372 return -EFAULT; 16373 } 16374 16375 /* check whether implicit source operand (register R6) is readable */ 16376 err = check_reg_arg(env, ctx_reg, SRC_OP); 16377 if (err) 16378 return err; 16379 16380 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 16381 * gen_ld_abs() may terminate the program at runtime, leading to 16382 * reference leak. 16383 */ 16384 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 16385 if (err) 16386 return err; 16387 16388 if (regs[ctx_reg].type != PTR_TO_CTX) { 16389 verbose(env, 16390 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 16391 return -EINVAL; 16392 } 16393 16394 if (mode == BPF_IND) { 16395 /* check explicit source operand */ 16396 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16397 if (err) 16398 return err; 16399 } 16400 16401 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 16402 if (err < 0) 16403 return err; 16404 16405 /* reset caller saved regs to unreadable */ 16406 for (i = 0; i < CALLER_SAVED_REGS; i++) { 16407 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 16408 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 16409 } 16410 16411 /* mark destination R0 register as readable, since it contains 16412 * the value fetched from the packet. 16413 * Already marked as written above. 16414 */ 16415 mark_reg_unknown(env, regs, BPF_REG_0); 16416 /* ld_abs load up to 32-bit skb data. */ 16417 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 16418 /* 16419 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0 16420 * which must be explored by the verifier when in a subprog. 16421 */ 16422 if (env->cur_state->curframe) { 16423 struct bpf_verifier_state *branch; 16424 16425 mark_reg_scratched(env, BPF_REG_0); 16426 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 16427 if (IS_ERR(branch)) 16428 return PTR_ERR(branch); 16429 mark_reg_known_zero(env, regs, BPF_REG_0); 16430 err = prepare_func_exit(env, &env->insn_idx); 16431 if (err) 16432 return err; 16433 env->insn_idx--; 16434 } 16435 return 0; 16436 } 16437 16438 16439 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range) 16440 { 16441 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16442 16443 /* Default return value range. */ 16444 *range = retval_range(0, 1); 16445 16446 switch (prog_type) { 16447 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 16448 switch (env->prog->expected_attach_type) { 16449 case BPF_CGROUP_UDP4_RECVMSG: 16450 case BPF_CGROUP_UDP6_RECVMSG: 16451 case BPF_CGROUP_UNIX_RECVMSG: 16452 case BPF_CGROUP_INET4_GETPEERNAME: 16453 case BPF_CGROUP_INET6_GETPEERNAME: 16454 case BPF_CGROUP_UNIX_GETPEERNAME: 16455 case BPF_CGROUP_INET4_GETSOCKNAME: 16456 case BPF_CGROUP_INET6_GETSOCKNAME: 16457 case BPF_CGROUP_UNIX_GETSOCKNAME: 16458 *range = retval_range(1, 1); 16459 break; 16460 case BPF_CGROUP_INET4_BIND: 16461 case BPF_CGROUP_INET6_BIND: 16462 *range = retval_range(0, 3); 16463 break; 16464 default: 16465 break; 16466 } 16467 break; 16468 case BPF_PROG_TYPE_CGROUP_SKB: 16469 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) 16470 *range = retval_range(0, 3); 16471 break; 16472 case BPF_PROG_TYPE_CGROUP_SOCK: 16473 case BPF_PROG_TYPE_SOCK_OPS: 16474 case BPF_PROG_TYPE_CGROUP_DEVICE: 16475 case BPF_PROG_TYPE_CGROUP_SYSCTL: 16476 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 16477 break; 16478 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16479 if (!env->prog->aux->attach_btf_id) 16480 return false; 16481 *range = retval_range(0, 0); 16482 break; 16483 case BPF_PROG_TYPE_TRACING: 16484 switch (env->prog->expected_attach_type) { 16485 case BPF_TRACE_FENTRY: 16486 case BPF_TRACE_FEXIT: 16487 case BPF_TRACE_FSESSION: 16488 case BPF_TRACE_FENTRY_MULTI: 16489 case BPF_TRACE_FEXIT_MULTI: 16490 case BPF_TRACE_FSESSION_MULTI: 16491 *range = retval_range(0, 0); 16492 break; 16493 case BPF_TRACE_RAW_TP: 16494 case BPF_MODIFY_RETURN: 16495 return false; 16496 case BPF_TRACE_ITER: 16497 default: 16498 break; 16499 } 16500 break; 16501 case BPF_PROG_TYPE_KPROBE: 16502 switch (env->prog->expected_attach_type) { 16503 case BPF_TRACE_KPROBE_SESSION: 16504 case BPF_TRACE_UPROBE_SESSION: 16505 break; 16506 default: 16507 return false; 16508 } 16509 break; 16510 case BPF_PROG_TYPE_SK_LOOKUP: 16511 *range = retval_range(SK_DROP, SK_PASS); 16512 break; 16513 16514 case BPF_PROG_TYPE_LSM: 16515 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 16516 /* no range found, any return value is allowed */ 16517 if (!get_func_retval_range(env->prog, range)) 16518 return false; 16519 /* no restricted range, any return value is allowed */ 16520 if (range->minval == S32_MIN && range->maxval == S32_MAX) 16521 return false; 16522 range->return_32bit = true; 16523 } else if (!env->prog->aux->attach_func_proto->type) { 16524 /* Make sure programs that attach to void 16525 * hooks don't try to modify return value. 16526 */ 16527 *range = retval_range(1, 1); 16528 } 16529 break; 16530 16531 case BPF_PROG_TYPE_NETFILTER: 16532 *range = retval_range(NF_DROP, NF_ACCEPT); 16533 break; 16534 case BPF_PROG_TYPE_STRUCT_OPS: 16535 *range = retval_range(0, 0); 16536 break; 16537 case BPF_PROG_TYPE_EXT: 16538 /* freplace program can return anything as its return value 16539 * depends on the to-be-replaced kernel func or bpf program. 16540 */ 16541 default: 16542 return false; 16543 } 16544 16545 /* Continue calculating. */ 16546 16547 return true; 16548 } 16549 16550 static bool program_returns_void(struct bpf_verifier_env *env) 16551 { 16552 const struct bpf_prog *prog = env->prog; 16553 enum bpf_prog_type prog_type = prog->type; 16554 16555 switch (prog_type) { 16556 case BPF_PROG_TYPE_LSM: 16557 /* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */ 16558 if (prog->expected_attach_type != BPF_LSM_CGROUP && 16559 !prog->aux->attach_func_proto->type) 16560 return true; 16561 break; 16562 case BPF_PROG_TYPE_STRUCT_OPS: 16563 if (!prog->aux->attach_func_proto->type) 16564 return true; 16565 break; 16566 case BPF_PROG_TYPE_EXT: 16567 /* 16568 * If the actual program is an extension, let it 16569 * return void - attaching will succeed only if the 16570 * program being replaced also returns void, and since 16571 * it has passed verification its actual type doesn't matter. 16572 */ 16573 if (subprog_returns_void(env, 0)) 16574 return true; 16575 break; 16576 default: 16577 break; 16578 } 16579 return false; 16580 } 16581 16582 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 16583 { 16584 const char *exit_ctx = "At program exit"; 16585 struct tnum enforce_attach_type_range = tnum_unknown; 16586 const struct bpf_prog *prog = env->prog; 16587 struct bpf_reg_state *reg = reg_state(env, regno); 16588 struct bpf_retval_range range = retval_range(0, 1); 16589 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16590 struct bpf_func_state *frame = env->cur_state->frame[0]; 16591 const struct btf_type *reg_type, *ret_type = NULL; 16592 int err; 16593 16594 /* LSM and struct_ops func-ptr's return type could be "void" */ 16595 if (!frame->in_async_callback_fn && program_returns_void(env)) 16596 return 0; 16597 16598 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) { 16599 /* Allow a struct_ops program to return a referenced kptr if it 16600 * matches the operator's return type and is in its unmodified 16601 * form. A scalar zero (i.e., a null pointer) is also allowed. 16602 */ 16603 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 16604 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 16605 prog->aux->attach_func_proto->type, 16606 NULL); 16607 if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg)) 16608 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 16609 } 16610 16611 /* eBPF calling convention is such that R0 is used 16612 * to return the value from eBPF program. 16613 * Make sure that it's readable at this time 16614 * of bpf_exit, which means that program wrote 16615 * something into it earlier 16616 */ 16617 err = check_reg_arg(env, regno, SRC_OP); 16618 if (err) 16619 return err; 16620 16621 if (is_pointer_value(env, regno)) { 16622 verbose(env, "R%d leaks addr as return value\n", regno); 16623 return -EACCES; 16624 } 16625 16626 if (frame->in_async_callback_fn) { 16627 exit_ctx = "At async callback return"; 16628 range = frame->callback_ret_range; 16629 goto enforce_retval; 16630 } 16631 16632 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type) 16633 return 0; 16634 16635 if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)) 16636 enforce_attach_type_range = tnum_range(2, 3); 16637 16638 if (!return_retval_range(env, &range)) 16639 return 0; 16640 16641 enforce_retval: 16642 if (reg->type != SCALAR_VALUE) { 16643 verbose(env, "%s the register R%d is not a known value (%s)\n", 16644 exit_ctx, regno, reg_type_str(env, reg->type)); 16645 return -EINVAL; 16646 } 16647 16648 err = mark_chain_precision(env, regno); 16649 if (err) 16650 return err; 16651 16652 if (!retval_range_within(range, reg)) { 16653 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 16654 if (prog->expected_attach_type == BPF_LSM_CGROUP && 16655 prog_type == BPF_PROG_TYPE_LSM && 16656 !prog->aux->attach_func_proto->type) 16657 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 16658 return -EINVAL; 16659 } 16660 16661 if (!tnum_is_unknown(enforce_attach_type_range) && 16662 tnum_in(enforce_attach_type_range, reg->var_off)) 16663 env->prog->enforce_expected_attach_type = 1; 16664 return 0; 16665 } 16666 16667 static int check_global_subprog_return_code(struct bpf_verifier_env *env) 16668 { 16669 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 16670 struct bpf_func_state *cur_frame = cur_func(env); 16671 int err; 16672 16673 if (subprog_returns_void(env, cur_frame->subprogno)) 16674 return 0; 16675 16676 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 16677 if (err) 16678 return err; 16679 16680 /* Pointers to arena are safe to pass between subprograms. */ 16681 if (is_arena_reg(env, BPF_REG_0)) 16682 return 0; 16683 16684 if (is_pointer_value(env, BPF_REG_0)) { 16685 verbose(env, "R%d leaks addr as return value\n", BPF_REG_0); 16686 return -EACCES; 16687 } 16688 16689 if (reg->type != SCALAR_VALUE) { 16690 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 16691 reg_type_str(env, reg->type)); 16692 return -EINVAL; 16693 } 16694 16695 return 0; 16696 } 16697 16698 /* Bitmask with 1s for all caller saved registers */ 16699 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16700 16701 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16702 * replacement patch is presumed to follow bpf_fastcall contract 16703 * (see mark_fastcall_pattern_for_call() below). 16704 */ 16705 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 16706 { 16707 switch (imm) { 16708 #ifdef CONFIG_X86_64 16709 case BPF_FUNC_get_smp_processor_id: 16710 #ifdef CONFIG_SMP 16711 case BPF_FUNC_get_current_task_btf: 16712 case BPF_FUNC_get_current_task: 16713 #endif 16714 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 16715 #endif 16716 default: 16717 return false; 16718 } 16719 } 16720 16721 /* If @call is a kfunc or helper call, fills @cs and returns true, 16722 * otherwise returns false. 16723 */ 16724 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 16725 struct bpf_call_summary *cs) 16726 { 16727 struct bpf_call_arg_meta meta; 16728 const struct bpf_func_proto *fn; 16729 int i; 16730 16731 if (bpf_helper_call(call)) { 16732 16733 if (bpf_get_helper_proto(env, call->imm, &fn) < 0) 16734 /* error would be reported later */ 16735 return false; 16736 cs->fastcall = fn->allow_fastcall && 16737 (bpf_verifier_inlines_helper_call(env, call->imm) || 16738 bpf_jit_inlines_helper_call(call->imm)); 16739 cs->is_void = fn->ret_type == RET_VOID; 16740 cs->num_params = 0; 16741 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 16742 if (fn->arg_type[i] == ARG_DONTCARE) 16743 break; 16744 cs->num_params++; 16745 } 16746 return true; 16747 } 16748 16749 if (bpf_pseudo_kfunc_call(call)) { 16750 int err; 16751 16752 err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta); 16753 if (err < 0) 16754 /* error would be reported later */ 16755 return false; 16756 cs->num_params = btf_type_vlen(meta.func_proto); 16757 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 16758 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 16759 return true; 16760 } 16761 16762 return false; 16763 } 16764 16765 /* LLVM define a bpf_fastcall function attribute. 16766 * This attribute means that function scratches only some of 16767 * the caller saved registers defined by ABI. 16768 * For BPF the set of such registers could be defined as follows: 16769 * - R0 is scratched only if function is non-void; 16770 * - R1-R5 are scratched only if corresponding parameter type is defined 16771 * in the function prototype. 16772 * 16773 * The contract between kernel and clang allows to simultaneously use 16774 * such functions and maintain backwards compatibility with old 16775 * kernels that don't understand bpf_fastcall calls: 16776 * 16777 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 16778 * registers are not scratched by the call; 16779 * 16780 * - as a post-processing step, clang visits each bpf_fastcall call and adds 16781 * spill/fill for every live r0-r5; 16782 * 16783 * - stack offsets used for the spill/fill are allocated as lowest 16784 * stack offsets in whole function and are not used for any other 16785 * purposes; 16786 * 16787 * - when kernel loads a program, it looks for such patterns 16788 * (bpf_fastcall function surrounded by spills/fills) and checks if 16789 * spill/fill stack offsets are used exclusively in fastcall patterns; 16790 * 16791 * - if so, and if verifier or current JIT inlines the call to the 16792 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 16793 * spill/fill pairs; 16794 * 16795 * - when old kernel loads a program, presence of spill/fill pairs 16796 * keeps BPF program valid, albeit slightly less efficient. 16797 * 16798 * For example: 16799 * 16800 * r1 = 1; 16801 * r2 = 2; 16802 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16803 * *(u64 *)(r10 - 16) = r2; r2 = 2; 16804 * call %[to_be_inlined] --> call %[to_be_inlined] 16805 * r2 = *(u64 *)(r10 - 16); r0 = r1; 16806 * r1 = *(u64 *)(r10 - 8); r0 += r2; 16807 * r0 = r1; exit; 16808 * r0 += r2; 16809 * exit; 16810 * 16811 * The purpose of mark_fastcall_pattern_for_call is to: 16812 * - look for such patterns; 16813 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 16814 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 16815 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 16816 * at which bpf_fastcall spill/fill stack slots start; 16817 * - update env->subprog_info[*]->keep_fastcall_stack. 16818 * 16819 * The .fastcall_pattern and .fastcall_stack_off are used by 16820 * check_fastcall_stack_contract() to check if every stack access to 16821 * fastcall spill/fill stack slot originates from spill/fill 16822 * instructions, members of fastcall patterns. 16823 * 16824 * If such condition holds true for a subprogram, fastcall patterns could 16825 * be rewritten by remove_fastcall_spills_fills(). 16826 * Otherwise bpf_fastcall patterns are not changed in the subprogram 16827 * (code, presumably, generated by an older clang version). 16828 * 16829 * For example, it is *not* safe to remove spill/fill below: 16830 * 16831 * r1 = 1; 16832 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16833 * call %[to_be_inlined] --> call %[to_be_inlined] 16834 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 16835 * r0 = *(u64 *)(r10 - 8); r0 += r1; 16836 * r0 += r1; exit; 16837 * exit; 16838 */ 16839 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 16840 struct bpf_subprog_info *subprog, 16841 int insn_idx, s16 lowest_off) 16842 { 16843 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 16844 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 16845 u32 clobbered_regs_mask; 16846 struct bpf_call_summary cs; 16847 u32 expected_regs_mask; 16848 s16 off; 16849 int i; 16850 16851 if (!bpf_get_call_summary(env, call, &cs)) 16852 return; 16853 16854 /* A bitmask specifying which caller saved registers are clobbered 16855 * by a call to a helper/kfunc *as if* this helper/kfunc follows 16856 * bpf_fastcall contract: 16857 * - includes R0 if function is non-void; 16858 * - includes R1-R5 if corresponding parameter has is described 16859 * in the function prototype. 16860 */ 16861 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 16862 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 16863 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 16864 16865 /* match pairs of form: 16866 * 16867 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 16868 * ... 16869 * call %[to_be_inlined] 16870 * ... 16871 * rX = *(u64 *)(r10 - Y) 16872 */ 16873 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 16874 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 16875 break; 16876 stx = &insns[insn_idx - i]; 16877 ldx = &insns[insn_idx + i]; 16878 /* must be a stack spill/fill pair */ 16879 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 16880 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 16881 stx->dst_reg != BPF_REG_10 || 16882 ldx->src_reg != BPF_REG_10) 16883 break; 16884 /* must be a spill/fill for the same reg */ 16885 if (stx->src_reg != ldx->dst_reg) 16886 break; 16887 /* must be one of the previously unseen registers */ 16888 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 16889 break; 16890 /* must be a spill/fill for the same expected offset, 16891 * no need to check offset alignment, BPF_DW stack access 16892 * is always 8-byte aligned. 16893 */ 16894 if (stx->off != off || ldx->off != off) 16895 break; 16896 expected_regs_mask &= ~BIT(stx->src_reg); 16897 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 16898 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 16899 } 16900 if (i == 1) 16901 return; 16902 16903 /* Conditionally set 'fastcall_spills_num' to allow forward 16904 * compatibility when more helper functions are marked as 16905 * bpf_fastcall at compile time than current kernel supports, e.g: 16906 * 16907 * 1: *(u64 *)(r10 - 8) = r1 16908 * 2: call A ;; assume A is bpf_fastcall for current kernel 16909 * 3: r1 = *(u64 *)(r10 - 8) 16910 * 4: *(u64 *)(r10 - 8) = r1 16911 * 5: call B ;; assume B is not bpf_fastcall for current kernel 16912 * 6: r1 = *(u64 *)(r10 - 8) 16913 * 16914 * There is no need to block bpf_fastcall rewrite for such program. 16915 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 16916 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 16917 * does not remove spill/fill pair {4,6}. 16918 */ 16919 if (cs.fastcall) 16920 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 16921 else 16922 subprog->keep_fastcall_stack = 1; 16923 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 16924 } 16925 16926 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 16927 { 16928 struct bpf_subprog_info *subprog = env->subprog_info; 16929 struct bpf_insn *insn; 16930 s16 lowest_off; 16931 int s, i; 16932 16933 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 16934 /* find lowest stack spill offset used in this subprog */ 16935 lowest_off = 0; 16936 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16937 insn = env->prog->insnsi + i; 16938 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 16939 insn->dst_reg != BPF_REG_10) 16940 continue; 16941 lowest_off = min(lowest_off, insn->off); 16942 } 16943 /* use this offset to find fastcall patterns */ 16944 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16945 insn = env->prog->insnsi + i; 16946 if (insn->code != (BPF_JMP | BPF_CALL)) 16947 continue; 16948 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 16949 } 16950 } 16951 return 0; 16952 } 16953 16954 static void adjust_btf_func(struct bpf_verifier_env *env) 16955 { 16956 struct bpf_prog_aux *aux = env->prog->aux; 16957 int i; 16958 16959 if (!aux->func_info) 16960 return; 16961 16962 /* func_info is not available for hidden subprogs */ 16963 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16964 aux->func_info[i].insn_off = env->subprog_info[i].start; 16965 } 16966 16967 /* Find id in idset and increment its count, or add new entry */ 16968 static void idset_cnt_inc(struct bpf_idset *idset, u32 id) 16969 { 16970 u32 i; 16971 16972 for (i = 0; i < idset->num_ids; i++) { 16973 if (idset->entries[i].id == id) { 16974 idset->entries[i].cnt++; 16975 return; 16976 } 16977 } 16978 /* New id */ 16979 if (idset->num_ids < BPF_ID_MAP_SIZE) { 16980 idset->entries[idset->num_ids].id = id; 16981 idset->entries[idset->num_ids].cnt = 1; 16982 idset->num_ids++; 16983 } 16984 } 16985 16986 /* Find id in idset and return its count, or 0 if not found */ 16987 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id) 16988 { 16989 u32 i; 16990 16991 for (i = 0; i < idset->num_ids; i++) { 16992 if (idset->entries[i].id == id) 16993 return idset->entries[i].cnt; 16994 } 16995 return 0; 16996 } 16997 16998 /* 16999 * Clear singular scalar ids in a state. 17000 * A register with a non-zero id is called singular if no other register shares 17001 * the same base id. Such registers can be treated as independent (id=0). 17002 */ 17003 void bpf_clear_singular_ids(struct bpf_verifier_env *env, 17004 struct bpf_verifier_state *st) 17005 { 17006 struct bpf_idset *idset = &env->idset_scratch; 17007 struct bpf_func_state *func; 17008 struct bpf_reg_state *reg; 17009 17010 idset->num_ids = 0; 17011 17012 bpf_for_each_reg_in_vstate(st, func, reg, ({ 17013 if (reg->type != SCALAR_VALUE) 17014 continue; 17015 if (!reg->id) 17016 continue; 17017 idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST); 17018 })); 17019 17020 bpf_for_each_reg_in_vstate(st, func, reg, ({ 17021 if (reg->type != SCALAR_VALUE) 17022 continue; 17023 if (!reg->id) 17024 continue; 17025 if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1) 17026 clear_scalar_id(reg); 17027 })); 17028 } 17029 17030 /* Return true if it's OK to have the same insn return a different type. */ 17031 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17032 { 17033 switch (base_type(type)) { 17034 case PTR_TO_CTX: 17035 case PTR_TO_SOCKET: 17036 case PTR_TO_SOCK_COMMON: 17037 case PTR_TO_TCP_SOCK: 17038 case PTR_TO_XDP_SOCK: 17039 case PTR_TO_BTF_ID: 17040 case PTR_TO_ARENA: 17041 return false; 17042 default: 17043 return true; 17044 } 17045 } 17046 17047 /* If an instruction was previously used with particular pointer types, then we 17048 * need to be careful to avoid cases such as the below, where it may be ok 17049 * for one branch accessing the pointer, but not ok for the other branch: 17050 * 17051 * R1 = sock_ptr 17052 * goto X; 17053 * ... 17054 * R1 = some_other_valid_ptr; 17055 * goto X; 17056 * ... 17057 * R2 = *(u32 *)(R1 + 0); 17058 */ 17059 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17060 { 17061 return src != prev && (!reg_type_mismatch_ok(src) || 17062 !reg_type_mismatch_ok(prev)); 17063 } 17064 17065 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type) 17066 { 17067 switch (base_type(type)) { 17068 case PTR_TO_MEM: 17069 case PTR_TO_BTF_ID: 17070 return true; 17071 default: 17072 return false; 17073 } 17074 } 17075 17076 static bool is_ptr_to_mem(enum bpf_reg_type type) 17077 { 17078 return base_type(type) == PTR_TO_MEM; 17079 } 17080 17081 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17082 bool allow_trust_mismatch) 17083 { 17084 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17085 enum bpf_reg_type merged_type; 17086 17087 if (*prev_type == NOT_INIT) { 17088 /* Saw a valid insn 17089 * dst_reg = *(u32 *)(src_reg + off) 17090 * save type to validate intersecting paths 17091 */ 17092 *prev_type = type; 17093 } else if (reg_type_mismatch(type, *prev_type)) { 17094 /* Abuser program is trying to use the same insn 17095 * dst_reg = *(u32*) (src_reg + off) 17096 * with different pointer types: 17097 * src_reg == ctx in one branch and 17098 * src_reg == stack|map in some other branch. 17099 * Reject it. 17100 */ 17101 if (allow_trust_mismatch && 17102 is_ptr_to_mem_or_btf_id(type) && 17103 is_ptr_to_mem_or_btf_id(*prev_type)) { 17104 /* 17105 * Have to support a use case when one path through 17106 * the program yields TRUSTED pointer while another 17107 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17108 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17109 * Same behavior of MEM_RDONLY flag. 17110 */ 17111 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type)) 17112 merged_type = PTR_TO_MEM; 17113 else 17114 merged_type = PTR_TO_BTF_ID; 17115 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED)) 17116 merged_type |= PTR_UNTRUSTED; 17117 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY)) 17118 merged_type |= MEM_RDONLY; 17119 *prev_type = merged_type; 17120 } else { 17121 verbose(env, "same insn cannot be used with different pointers\n"); 17122 return -EINVAL; 17123 } 17124 } 17125 17126 return 0; 17127 } 17128 17129 enum { 17130 PROCESS_BPF_EXIT = 1, 17131 INSN_IDX_UPDATED = 2, 17132 }; 17133 17134 static int process_bpf_exit_full(struct bpf_verifier_env *env, 17135 bool *do_print_state, 17136 bool exception_exit) 17137 { 17138 struct bpf_func_state *cur_frame = cur_func(env); 17139 17140 /* We must do check_reference_leak here before 17141 * prepare_func_exit to handle the case when 17142 * state->curframe > 0, it may be a callback function, 17143 * for which reference_state must match caller reference 17144 * state when it exits. 17145 */ 17146 int err = check_resource_leak(env, exception_exit, 17147 exception_exit || !env->cur_state->curframe, 17148 exception_exit ? "bpf_throw" : 17149 "BPF_EXIT instruction in main prog"); 17150 if (err) 17151 return err; 17152 17153 /* The side effect of the prepare_func_exit which is 17154 * being skipped is that it frees bpf_func_state. 17155 * Typically, process_bpf_exit will only be hit with 17156 * outermost exit. copy_verifier_state in pop_stack will 17157 * handle freeing of any extra bpf_func_state left over 17158 * from not processing all nested function exits. We 17159 * also skip return code checks as they are not needed 17160 * for exceptional exits. 17161 */ 17162 if (exception_exit) 17163 return PROCESS_BPF_EXIT; 17164 17165 if (env->cur_state->curframe) { 17166 /* exit from nested function */ 17167 err = prepare_func_exit(env, &env->insn_idx); 17168 if (err) 17169 return err; 17170 *do_print_state = true; 17171 return INSN_IDX_UPDATED; 17172 } 17173 17174 /* 17175 * Return from a regular global subprogram differs from return 17176 * from the main program or async/exception callback. 17177 * Main program exit implies return code restrictions 17178 * that depend on program type. 17179 * Exit from exception callback is equivalent to main program exit. 17180 * Exit from async callback implies return code restrictions 17181 * that depend on async scheduling mechanism. 17182 */ 17183 if (cur_frame->subprogno && 17184 !cur_frame->in_async_callback_fn && 17185 !cur_frame->in_exception_callback_fn) 17186 err = check_global_subprog_return_code(env); 17187 else 17188 err = check_return_code(env, BPF_REG_0, "R0"); 17189 if (err) 17190 return err; 17191 return PROCESS_BPF_EXIT; 17192 } 17193 17194 static int indirect_jump_min_max_index(struct bpf_verifier_env *env, 17195 int regno, 17196 struct bpf_map *map, 17197 u32 *pmin_index, u32 *pmax_index) 17198 { 17199 struct bpf_reg_state *reg = reg_state(env, regno); 17200 u64 min_index = reg_umin(reg); 17201 u64 max_index = reg_umax(reg); 17202 const u32 size = 8; 17203 17204 if (min_index > (u64) U32_MAX * size) { 17205 verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg)); 17206 return -ERANGE; 17207 } 17208 if (max_index > (u64) U32_MAX * size) { 17209 verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg)); 17210 return -ERANGE; 17211 } 17212 17213 min_index /= size; 17214 max_index /= size; 17215 17216 if (max_index >= map->max_entries) { 17217 verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n", 17218 regno, min_index, max_index, map->max_entries); 17219 return -EINVAL; 17220 } 17221 17222 *pmin_index = min_index; 17223 *pmax_index = max_index; 17224 return 0; 17225 } 17226 17227 /* gotox *dst_reg */ 17228 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn) 17229 { 17230 struct bpf_verifier_state *other_branch; 17231 struct bpf_reg_state *dst_reg; 17232 struct bpf_map *map; 17233 u32 min_index, max_index; 17234 int err = 0; 17235 int n; 17236 int i; 17237 17238 dst_reg = reg_state(env, insn->dst_reg); 17239 if (dst_reg->type != PTR_TO_INSN) { 17240 verbose(env, "R%d has type %s, expected PTR_TO_INSN\n", 17241 insn->dst_reg, reg_type_str(env, dst_reg->type)); 17242 return -EINVAL; 17243 } 17244 17245 map = dst_reg->map_ptr; 17246 if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg)) 17247 return -EFAULT; 17248 17249 if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env, 17250 "R%d has incorrect map type %d", insn->dst_reg, map->map_type)) 17251 return -EFAULT; 17252 17253 err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index); 17254 if (err) 17255 return err; 17256 17257 /* Ensure that the buffer is large enough */ 17258 if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) { 17259 env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf, 17260 max_index - min_index + 1); 17261 if (!env->gotox_tmp_buf) 17262 return -ENOMEM; 17263 } 17264 17265 n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items); 17266 if (n < 0) 17267 return n; 17268 if (n == 0) { 17269 verbose(env, "register R%d doesn't point to any offset in map id=%d\n", 17270 insn->dst_reg, map->id); 17271 return -EINVAL; 17272 } 17273 17274 for (i = 0; i < n - 1; i++) { 17275 mark_indirect_target(env, env->gotox_tmp_buf->items[i]); 17276 other_branch = push_stack(env, env->gotox_tmp_buf->items[i], 17277 env->insn_idx, env->cur_state->speculative); 17278 if (IS_ERR(other_branch)) 17279 return PTR_ERR(other_branch); 17280 } 17281 env->insn_idx = env->gotox_tmp_buf->items[n-1]; 17282 mark_indirect_target(env, env->insn_idx); 17283 return INSN_IDX_UPDATED; 17284 } 17285 17286 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 17287 { 17288 int err; 17289 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 17290 u8 class = BPF_CLASS(insn->code); 17291 17292 switch (class) { 17293 case BPF_ALU: 17294 case BPF_ALU64: 17295 return check_alu_op(env, insn); 17296 17297 case BPF_LDX: 17298 return check_load_mem(env, insn, false, 17299 BPF_MODE(insn->code) == BPF_MEMSX, 17300 true, "ldx"); 17301 17302 case BPF_STX: 17303 if (BPF_MODE(insn->code) == BPF_ATOMIC) 17304 return check_atomic(env, insn); 17305 return check_store_reg(env, insn, false); 17306 17307 case BPF_ST: { 17308 /* Handle stack arg write (store immediate) */ 17309 if (is_stack_arg_st(insn)) { 17310 struct bpf_verifier_state *vstate = env->cur_state; 17311 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 17312 17313 return check_stack_arg_write(env, state, insn->off, NULL); 17314 } 17315 17316 enum bpf_reg_type dst_reg_type; 17317 17318 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17319 if (err) 17320 return err; 17321 17322 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 17323 17324 err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg, argno_from_reg(insn->dst_reg), 17325 insn->off, BPF_SIZE(insn->code), 17326 BPF_WRITE, -1, false, false); 17327 if (err) 17328 return err; 17329 17330 return save_aux_ptr_type(env, dst_reg_type, false); 17331 } 17332 case BPF_JMP: 17333 case BPF_JMP32: { 17334 u8 opcode = BPF_OP(insn->code); 17335 17336 env->jmps_processed++; 17337 if (opcode == BPF_CALL) { 17338 if (env->cur_state->active_locks) { 17339 if ((insn->src_reg == BPF_REG_0 && 17340 insn->imm != BPF_FUNC_spin_unlock && 17341 insn->imm != BPF_FUNC_kptr_xchg) || 17342 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17343 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) { 17344 verbose(env, 17345 "function calls are not allowed while holding a lock\n"); 17346 return -EINVAL; 17347 } 17348 } 17349 mark_reg_scratched(env, BPF_REG_0); 17350 if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno])) 17351 cur_func(env)->no_stack_arg_load = true; 17352 if (insn->src_reg == BPF_PSEUDO_CALL) 17353 return check_func_call(env, insn, &env->insn_idx); 17354 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17355 return check_kfunc_call(env, insn, &env->insn_idx); 17356 return check_helper_call(env, insn, &env->insn_idx); 17357 } else if (opcode == BPF_JA) { 17358 if (BPF_SRC(insn->code) == BPF_X) 17359 return check_indirect_jump(env, insn); 17360 17361 if (class == BPF_JMP) 17362 env->insn_idx += insn->off + 1; 17363 else 17364 env->insn_idx += insn->imm + 1; 17365 return INSN_IDX_UPDATED; 17366 } else if (opcode == BPF_EXIT) { 17367 return process_bpf_exit_full(env, do_print_state, false); 17368 } 17369 return check_cond_jmp_op(env, insn, &env->insn_idx); 17370 } 17371 case BPF_LD: { 17372 u8 mode = BPF_MODE(insn->code); 17373 17374 if (mode == BPF_ABS || mode == BPF_IND) 17375 return check_ld_abs(env, insn); 17376 17377 if (mode == BPF_IMM) { 17378 err = check_ld_imm(env, insn); 17379 if (err) 17380 return err; 17381 17382 env->insn_idx++; 17383 sanitize_mark_insn_seen(env); 17384 } 17385 return 0; 17386 } 17387 } 17388 /* all class values are handled above. silence compiler warning */ 17389 return -EFAULT; 17390 } 17391 17392 static int do_check(struct bpf_verifier_env *env) 17393 { 17394 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17395 struct bpf_verifier_state *state = env->cur_state; 17396 struct bpf_insn *insns = env->prog->insnsi; 17397 int insn_cnt = env->prog->len; 17398 bool do_print_state = false; 17399 int prev_insn_idx = -1; 17400 17401 for (;;) { 17402 struct bpf_insn *insn; 17403 struct bpf_insn_aux_data *insn_aux; 17404 int err; 17405 17406 /* reset current history entry on each new instruction */ 17407 env->cur_hist_ent = NULL; 17408 17409 env->prev_insn_idx = prev_insn_idx; 17410 if (env->insn_idx >= insn_cnt) { 17411 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17412 env->insn_idx, insn_cnt); 17413 return -EFAULT; 17414 } 17415 17416 insn = &insns[env->insn_idx]; 17417 insn_aux = &env->insn_aux_data[env->insn_idx]; 17418 17419 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17420 verbose(env, 17421 "BPF program is too large. Processed %d insn\n", 17422 env->insn_processed); 17423 return -E2BIG; 17424 } 17425 17426 state->last_insn_idx = env->prev_insn_idx; 17427 state->insn_idx = env->insn_idx; 17428 17429 if (bpf_is_prune_point(env, env->insn_idx)) { 17430 err = bpf_is_state_visited(env, env->insn_idx); 17431 if (err < 0) 17432 return err; 17433 if (err == 1) { 17434 /* found equivalent state, can prune the search */ 17435 if (env->log.level & BPF_LOG_LEVEL) { 17436 if (do_print_state) 17437 verbose(env, "\nfrom %d to %d%s: safe\n", 17438 env->prev_insn_idx, env->insn_idx, 17439 env->cur_state->speculative ? 17440 " (speculative execution)" : ""); 17441 else 17442 verbose(env, "%d: safe\n", env->insn_idx); 17443 } 17444 goto process_bpf_exit; 17445 } 17446 } 17447 17448 if (bpf_is_jmp_point(env, env->insn_idx)) { 17449 err = bpf_push_jmp_history(env, state, 0, 0, 0, 0); 17450 if (err) 17451 return err; 17452 } 17453 17454 if (signal_pending(current)) 17455 return -EAGAIN; 17456 17457 if (need_resched()) 17458 cond_resched(); 17459 17460 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17461 verbose(env, "\nfrom %d to %d%s:", 17462 env->prev_insn_idx, env->insn_idx, 17463 env->cur_state->speculative ? 17464 " (speculative execution)" : ""); 17465 print_verifier_state(env, state, state->curframe, true); 17466 do_print_state = false; 17467 } 17468 17469 if (env->log.level & BPF_LOG_LEVEL) { 17470 if (verifier_state_scratched(env)) 17471 print_insn_state(env, state, state->curframe); 17472 17473 verbose_linfo(env, env->insn_idx, "; "); 17474 env->prev_log_pos = env->log.end_pos; 17475 verbose(env, "%d: ", env->insn_idx); 17476 bpf_verbose_insn(env, insn); 17477 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17478 env->prev_log_pos = env->log.end_pos; 17479 } 17480 17481 if (bpf_prog_is_offloaded(env->prog->aux)) { 17482 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17483 env->prev_insn_idx); 17484 if (err) 17485 return err; 17486 } 17487 17488 sanitize_mark_insn_seen(env); 17489 prev_insn_idx = env->insn_idx; 17490 17491 /* Sanity check: precomputed constants must match verifier state */ 17492 if (!state->speculative && insn_aux->const_reg_mask) { 17493 struct bpf_reg_state *regs = cur_regs(env); 17494 u16 mask = insn_aux->const_reg_mask; 17495 17496 for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) { 17497 u32 cval = insn_aux->const_reg_vals[r]; 17498 17499 if (!(mask & BIT(r))) 17500 continue; 17501 if (regs[r].type != SCALAR_VALUE) 17502 continue; 17503 if (!tnum_is_const(regs[r].var_off)) 17504 continue; 17505 if (verifier_bug_if((u32)regs[r].var_off.value != cval, 17506 env, "const R%d: %u != %llu", 17507 r, cval, regs[r].var_off.value)) 17508 return -EFAULT; 17509 } 17510 } 17511 17512 /* Reduce verification complexity by stopping speculative path 17513 * verification when a nospec is encountered. 17514 */ 17515 if (state->speculative && insn_aux->nospec) 17516 goto process_bpf_exit; 17517 17518 err = do_check_insn(env, &do_print_state); 17519 if (error_recoverable_with_nospec(err) && state->speculative) { 17520 /* Prevent this speculative path from ever reaching the 17521 * insn that would have been unsafe to execute. 17522 */ 17523 insn_aux->nospec = true; 17524 /* If it was an ADD/SUB insn, potentially remove any 17525 * markings for alu sanitization. 17526 */ 17527 insn_aux->alu_state = 0; 17528 goto process_bpf_exit; 17529 } else if (err < 0) { 17530 return err; 17531 } else if (err == PROCESS_BPF_EXIT) { 17532 goto process_bpf_exit; 17533 } else if (err == INSN_IDX_UPDATED) { 17534 } else if (err == 0) { 17535 env->insn_idx++; 17536 } 17537 17538 if (state->speculative && insn_aux->nospec_result) { 17539 /* If we are on a path that performed a jump-op, this 17540 * may skip a nospec patched-in after the jump. This can 17541 * currently never happen because nospec_result is only 17542 * used for the write-ops 17543 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper 17544 * calls. These must never skip the following insn 17545 * (i.e., bpf_insn_successors()'s opcode_info.can_jump 17546 * is false). Still, add a warning to document this in 17547 * case nospec_result is used elsewhere in the future. 17548 * 17549 * All non-branch instructions have a single 17550 * fall-through edge. For these, nospec_result should 17551 * already work. 17552 */ 17553 if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP || 17554 BPF_CLASS(insn->code) == BPF_JMP32) && 17555 BPF_OP(insn->code) != BPF_CALL, env, 17556 "speculation barrier after jump instruction may not have the desired effect")) 17557 return -EFAULT; 17558 process_bpf_exit: 17559 mark_verifier_state_scratched(env); 17560 err = bpf_update_branch_counts(env, env->cur_state); 17561 if (err) 17562 return err; 17563 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 17564 pop_log); 17565 if (err < 0) { 17566 if (err != -ENOENT) 17567 return err; 17568 break; 17569 } else { 17570 do_print_state = true; 17571 continue; 17572 } 17573 } 17574 } 17575 17576 return 0; 17577 } 17578 17579 static int find_btf_percpu_datasec(struct btf *btf) 17580 { 17581 const struct btf_type *t; 17582 const char *tname; 17583 int i, n; 17584 17585 /* 17586 * Both vmlinux and module each have their own ".data..percpu" 17587 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17588 * types to look at only module's own BTF types. 17589 */ 17590 n = btf_nr_types(btf); 17591 for (i = btf_named_start_id(btf, true); i < n; i++) { 17592 t = btf_type_by_id(btf, i); 17593 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17594 continue; 17595 17596 tname = btf_name_by_offset(btf, t->name_off); 17597 if (!strcmp(tname, ".data..percpu")) 17598 return i; 17599 } 17600 17601 return -ENOENT; 17602 } 17603 17604 /* 17605 * Add btf to the env->used_btfs array. If needed, refcount the 17606 * corresponding kernel module. To simplify caller's logic 17607 * in case of error or if btf was added before the function 17608 * decreases the btf refcount. 17609 */ 17610 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 17611 { 17612 struct btf_mod_pair *btf_mod; 17613 int ret = 0; 17614 int i; 17615 17616 /* check whether we recorded this BTF (and maybe module) already */ 17617 for (i = 0; i < env->used_btf_cnt; i++) 17618 if (env->used_btfs[i].btf == btf) 17619 goto ret_put; 17620 17621 if (env->signature) { 17622 verbose(env, "signed program cannot bind any BTF\n"); 17623 ret = -EACCES; 17624 goto ret_put; 17625 } 17626 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17627 verbose(env, "The total number of btfs per program has reached the limit of %u\n", 17628 MAX_USED_BTFS); 17629 ret = -E2BIG; 17630 goto ret_put; 17631 } 17632 17633 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17634 btf_mod->btf = btf; 17635 btf_mod->module = NULL; 17636 17637 /* if we reference variables from kernel module, bump its refcount */ 17638 if (btf_is_module(btf)) { 17639 btf_mod->module = btf_try_get_module(btf); 17640 if (!btf_mod->module) { 17641 ret = -ENXIO; 17642 goto ret_put; 17643 } 17644 } 17645 17646 env->used_btf_cnt++; 17647 return 0; 17648 17649 ret_put: 17650 /* Either error or this BTF was already added */ 17651 btf_put(btf); 17652 return ret; 17653 } 17654 17655 /* replace pseudo btf_id with kernel symbol address */ 17656 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 17657 struct bpf_insn *insn, 17658 struct bpf_insn_aux_data *aux, 17659 struct btf *btf) 17660 { 17661 const struct btf_var_secinfo *vsi; 17662 const struct btf_type *datasec; 17663 const struct btf_type *t; 17664 const char *sym_name; 17665 bool percpu = false; 17666 u32 type, id = insn->imm; 17667 s32 datasec_id; 17668 u64 addr; 17669 int i; 17670 17671 t = btf_type_by_id(btf, id); 17672 if (!t) { 17673 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17674 return -ENOENT; 17675 } 17676 17677 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17678 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17679 return -EINVAL; 17680 } 17681 17682 sym_name = btf_name_by_offset(btf, t->name_off); 17683 addr = kallsyms_lookup_name(sym_name); 17684 if (!addr) { 17685 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17686 sym_name); 17687 return -ENOENT; 17688 } 17689 insn[0].imm = (u32)addr; 17690 insn[1].imm = addr >> 32; 17691 17692 if (btf_type_is_func(t)) { 17693 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17694 aux->btf_var.mem_size = 0; 17695 return 0; 17696 } 17697 17698 datasec_id = find_btf_percpu_datasec(btf); 17699 if (datasec_id > 0) { 17700 datasec = btf_type_by_id(btf, datasec_id); 17701 for_each_vsi(i, datasec, vsi) { 17702 if (vsi->type == id) { 17703 percpu = true; 17704 break; 17705 } 17706 } 17707 } 17708 17709 type = t->type; 17710 t = btf_type_skip_modifiers(btf, type, NULL); 17711 if (percpu) { 17712 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17713 aux->btf_var.btf = btf; 17714 aux->btf_var.btf_id = type; 17715 } else if (!btf_type_is_struct(t)) { 17716 const struct btf_type *ret; 17717 const char *tname; 17718 u32 tsize; 17719 17720 /* resolve the type size of ksym. */ 17721 ret = btf_resolve_size(btf, t, &tsize); 17722 if (IS_ERR(ret)) { 17723 tname = btf_name_by_offset(btf, t->name_off); 17724 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17725 tname, PTR_ERR(ret)); 17726 return -EINVAL; 17727 } 17728 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17729 aux->btf_var.mem_size = tsize; 17730 } else { 17731 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17732 aux->btf_var.btf = btf; 17733 aux->btf_var.btf_id = type; 17734 } 17735 17736 return 0; 17737 } 17738 17739 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17740 struct bpf_insn *insn, 17741 struct bpf_insn_aux_data *aux) 17742 { 17743 struct btf *btf; 17744 int btf_fd; 17745 int err; 17746 17747 btf_fd = insn[1].imm; 17748 if (btf_fd) { 17749 btf = btf_get_by_fd(btf_fd); 17750 if (IS_ERR(btf)) { 17751 verbose(env, "invalid module BTF object FD specified.\n"); 17752 return -EINVAL; 17753 } 17754 } else { 17755 if (!btf_vmlinux) { 17756 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17757 return -EINVAL; 17758 } 17759 btf_get(btf_vmlinux); 17760 btf = btf_vmlinux; 17761 } 17762 17763 err = __check_pseudo_btf_id(env, insn, aux, btf); 17764 if (err) { 17765 btf_put(btf); 17766 return err; 17767 } 17768 17769 return __add_used_btf(env, btf); 17770 } 17771 17772 static bool is_tracing_prog_type(enum bpf_prog_type type) 17773 { 17774 switch (type) { 17775 case BPF_PROG_TYPE_KPROBE: 17776 case BPF_PROG_TYPE_TRACEPOINT: 17777 case BPF_PROG_TYPE_PERF_EVENT: 17778 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17779 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17780 return true; 17781 default: 17782 return false; 17783 } 17784 } 17785 17786 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17787 { 17788 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17789 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17790 } 17791 17792 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17793 struct bpf_map *map, 17794 struct bpf_prog *prog) 17795 17796 { 17797 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17798 17799 if (map->excl_prog_sha && 17800 memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) { 17801 verbose(env, "program's hash doesn't match map's excl_prog_hash\n"); 17802 return -EACCES; 17803 } 17804 17805 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17806 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17807 if (is_tracing_prog_type(prog_type)) { 17808 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17809 return -EINVAL; 17810 } 17811 } 17812 17813 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 17814 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17815 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17816 return -EINVAL; 17817 } 17818 17819 if (is_tracing_prog_type(prog_type)) { 17820 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17821 return -EINVAL; 17822 } 17823 } 17824 17825 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17826 !bpf_offload_prog_map_match(prog, map)) { 17827 verbose(env, "offload device mismatch between prog and map\n"); 17828 return -EINVAL; 17829 } 17830 17831 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17832 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17833 return -EINVAL; 17834 } 17835 17836 if (prog->sleepable) 17837 switch (map->map_type) { 17838 case BPF_MAP_TYPE_HASH: 17839 case BPF_MAP_TYPE_RHASH: 17840 case BPF_MAP_TYPE_LRU_HASH: 17841 case BPF_MAP_TYPE_ARRAY: 17842 case BPF_MAP_TYPE_PERCPU_HASH: 17843 case BPF_MAP_TYPE_PERCPU_ARRAY: 17844 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17845 case BPF_MAP_TYPE_LPM_TRIE: 17846 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17847 case BPF_MAP_TYPE_HASH_OF_MAPS: 17848 case BPF_MAP_TYPE_RINGBUF: 17849 case BPF_MAP_TYPE_USER_RINGBUF: 17850 case BPF_MAP_TYPE_INODE_STORAGE: 17851 case BPF_MAP_TYPE_SK_STORAGE: 17852 case BPF_MAP_TYPE_TASK_STORAGE: 17853 case BPF_MAP_TYPE_CGRP_STORAGE: 17854 case BPF_MAP_TYPE_QUEUE: 17855 case BPF_MAP_TYPE_STACK: 17856 case BPF_MAP_TYPE_ARENA: 17857 case BPF_MAP_TYPE_INSN_ARRAY: 17858 case BPF_MAP_TYPE_PROG_ARRAY: 17859 break; 17860 default: 17861 verbose(env, 17862 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17863 return -EINVAL; 17864 } 17865 17866 if (bpf_map_is_cgroup_storage(map) && 17867 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17868 verbose(env, "only one cgroup storage of each type is allowed\n"); 17869 return -EBUSY; 17870 } 17871 17872 if (map->map_type == BPF_MAP_TYPE_ARENA) { 17873 if (env->prog->aux->arena) { 17874 verbose(env, "Only one arena per program\n"); 17875 return -EBUSY; 17876 } 17877 if (!env->allow_ptr_leaks || !env->bpf_capable) { 17878 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 17879 return -EPERM; 17880 } 17881 if (!env->prog->jit_requested) { 17882 verbose(env, "JIT is required to use arena\n"); 17883 return -EOPNOTSUPP; 17884 } 17885 if (!bpf_jit_supports_arena()) { 17886 verbose(env, "JIT doesn't support arena\n"); 17887 return -EOPNOTSUPP; 17888 } 17889 env->prog->aux->arena = (void *)map; 17890 env->prog->jit_required = true; 17891 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 17892 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 17893 return -EINVAL; 17894 } 17895 } 17896 17897 return 0; 17898 } 17899 17900 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 17901 { 17902 int i, err; 17903 17904 /* check whether we recorded this map already */ 17905 for (i = 0; i < env->used_map_cnt; i++) 17906 if (env->used_maps[i] == map) 17907 return i; 17908 17909 if (env->signature && 17910 env->prog->aux->sig.verdict == BPF_SIG_VERIFIED) { 17911 verbose(env, "signed program cannot bind map '%s' not covered by the signature\n", 17912 map->name); 17913 return -EACCES; 17914 } 17915 if (env->used_map_cnt >= MAX_USED_MAPS) { 17916 verbose(env, "The total number of maps per program has reached the limit of %u\n", 17917 MAX_USED_MAPS); 17918 return -E2BIG; 17919 } 17920 17921 err = check_map_prog_compatibility(env, map, env->prog); 17922 if (err) 17923 return err; 17924 17925 if (env->prog->sleepable) 17926 atomic64_inc(&map->sleepable_refcnt); 17927 17928 /* hold the map. If the program is rejected by verifier, 17929 * the map will be released by release_maps() or it 17930 * will be used by the valid program until it's unloaded 17931 * and all maps are released in bpf_free_used_maps() 17932 */ 17933 bpf_map_inc(map); 17934 17935 env->used_maps[env->used_map_cnt++] = map; 17936 17937 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 17938 err = bpf_insn_array_init(map, env->prog); 17939 if (err) { 17940 verbose(env, "Failed to properly initialize insn array\n"); 17941 return err; 17942 } 17943 env->insn_array_maps[env->insn_array_map_cnt++] = map; 17944 env->prog->jit_required = true; 17945 } 17946 17947 return env->used_map_cnt - 1; 17948 } 17949 17950 /* Add map behind fd to used maps list, if it's not already there, and return 17951 * its index. 17952 * Returns <0 on error, or >= 0 index, on success. 17953 */ 17954 static int add_used_map(struct bpf_verifier_env *env, int fd) 17955 { 17956 struct bpf_map *map; 17957 CLASS(fd, f)(fd); 17958 17959 map = __bpf_map_get(f); 17960 if (IS_ERR(map)) { 17961 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 17962 return PTR_ERR(map); 17963 } 17964 17965 return __add_used_map(env, map); 17966 } 17967 17968 static int fd_array_get_map_idx_continuous(struct bpf_verifier_env *env, u32 idx) 17969 { 17970 struct bpf_map *map; 17971 17972 if (idx >= env->fd_array_cnt) { 17973 verbose(env, "fd_idx %u out of bounds, fd_array_cnt %u\n", 17974 idx, env->fd_array_cnt); 17975 return -EINVAL; 17976 } 17977 map = fd_slot_map(env->fd_array[idx]); 17978 if (!map) { 17979 verbose(env, "fd_idx %u is not a map\n", idx); 17980 return -EINVAL; 17981 } 17982 return __add_used_map(env, map); 17983 } 17984 17985 static int fd_array_get_map_idx_sparse(struct bpf_verifier_env *env, u32 idx) 17986 { 17987 int fd; 17988 17989 if (copy_from_bpfptr_offset(&fd, env->fd_array_raw, 17990 (size_t)idx * sizeof(fd), sizeof(fd))) 17991 return -EFAULT; 17992 return add_used_map(env, fd); 17993 } 17994 17995 static int fd_array_get_map_idx(struct bpf_verifier_env *env, u32 idx) 17996 { 17997 if (env->fd_array) 17998 return fd_array_get_map_idx_continuous(env, idx); 17999 if (env->signature) { 18000 verbose(env, "signed program must bind maps via a continuous fd_array (fd_array_cnt)\n"); 18001 return -EACCES; 18002 } 18003 if (!bpfptr_is_null(env->fd_array_raw)) 18004 return fd_array_get_map_idx_sparse(env, idx); 18005 18006 verbose(env, "fd_idx without fd_array is invalid\n"); 18007 return -EPROTO; 18008 } 18009 18010 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 18011 { 18012 u8 class = BPF_CLASS(insn->code); 18013 u8 opcode = BPF_OP(insn->code); 18014 18015 switch (opcode) { 18016 case BPF_NEG: 18017 if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 || 18018 insn->off != 0 || insn->imm != 0) { 18019 verbose(env, "BPF_NEG uses reserved fields\n"); 18020 return -EINVAL; 18021 } 18022 return 0; 18023 case BPF_END: 18024 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 18025 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 18026 (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) { 18027 verbose(env, "BPF_END uses reserved fields\n"); 18028 return -EINVAL; 18029 } 18030 return 0; 18031 case BPF_MOV: 18032 if (BPF_SRC(insn->code) == BPF_X) { 18033 if (class == BPF_ALU) { 18034 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 18035 insn->imm) { 18036 verbose(env, "BPF_MOV uses reserved fields\n"); 18037 return -EINVAL; 18038 } 18039 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 18040 if (insn->imm != 1 && insn->imm != 1u << 16) { 18041 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 18042 return -EINVAL; 18043 } 18044 } else if ((insn->off != 0 && insn->off != 8 && 18045 insn->off != 16 && insn->off != 32) || insn->imm) { 18046 verbose(env, "BPF_MOV uses reserved fields\n"); 18047 return -EINVAL; 18048 } 18049 } else if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 18050 verbose(env, "BPF_MOV uses reserved fields\n"); 18051 return -EINVAL; 18052 } 18053 return 0; 18054 case BPF_ADD: 18055 case BPF_SUB: 18056 case BPF_AND: 18057 case BPF_OR: 18058 case BPF_XOR: 18059 case BPF_LSH: 18060 case BPF_RSH: 18061 case BPF_ARSH: 18062 case BPF_MUL: 18063 case BPF_DIV: 18064 case BPF_MOD: 18065 if (BPF_SRC(insn->code) == BPF_X) { 18066 if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) || 18067 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 18068 verbose(env, "BPF_ALU uses reserved fields\n"); 18069 return -EINVAL; 18070 } 18071 } else if (insn->src_reg != BPF_REG_0 || 18072 (insn->off != 0 && insn->off != 1) || 18073 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 18074 verbose(env, "BPF_ALU uses reserved fields\n"); 18075 return -EINVAL; 18076 } 18077 return 0; 18078 default: 18079 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 18080 return -EINVAL; 18081 } 18082 } 18083 18084 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 18085 { 18086 u8 class = BPF_CLASS(insn->code); 18087 u8 opcode = BPF_OP(insn->code); 18088 18089 switch (opcode) { 18090 case BPF_CALL: 18091 if (BPF_SRC(insn->code) != BPF_K || 18092 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) || 18093 (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL && 18094 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 18095 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 18096 verbose(env, "BPF_CALL uses reserved fields\n"); 18097 return -EINVAL; 18098 } 18099 return 0; 18100 case BPF_JA: 18101 if (BPF_SRC(insn->code) == BPF_X) { 18102 if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) { 18103 verbose(env, "BPF_JA|BPF_X uses reserved fields\n"); 18104 return -EINVAL; 18105 } 18106 } else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 18107 (class == BPF_JMP && insn->imm != 0) || 18108 (class == BPF_JMP32 && insn->off != 0)) { 18109 verbose(env, "BPF_JA uses reserved fields\n"); 18110 return -EINVAL; 18111 } 18112 return 0; 18113 case BPF_EXIT: 18114 if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || 18115 insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 18116 class == BPF_JMP32) { 18117 verbose(env, "BPF_EXIT uses reserved fields\n"); 18118 return -EINVAL; 18119 } 18120 return 0; 18121 case BPF_JCOND: 18122 if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO || 18123 insn->dst_reg || insn->imm) { 18124 verbose(env, "invalid may_goto imm %d\n", insn->imm); 18125 return -EINVAL; 18126 } 18127 return 0; 18128 default: 18129 if (BPF_SRC(insn->code) == BPF_X) { 18130 if (insn->imm != 0) { 18131 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18132 return -EINVAL; 18133 } 18134 } else if (insn->src_reg != BPF_REG_0) { 18135 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18136 return -EINVAL; 18137 } 18138 return 0; 18139 } 18140 } 18141 18142 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 18143 { 18144 switch (BPF_CLASS(insn->code)) { 18145 case BPF_ALU: 18146 case BPF_ALU64: 18147 return check_alu_fields(env, insn); 18148 case BPF_LDX: 18149 if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18150 insn->imm != 0) { 18151 verbose(env, "BPF_LDX uses reserved fields\n"); 18152 return -EINVAL; 18153 } 18154 return 0; 18155 case BPF_STX: 18156 if (BPF_MODE(insn->code) == BPF_ATOMIC) 18157 return 0; 18158 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 18159 verbose(env, "BPF_STX uses reserved fields\n"); 18160 return -EINVAL; 18161 } 18162 return 0; 18163 case BPF_ST: 18164 if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { 18165 verbose(env, "BPF_ST uses reserved fields\n"); 18166 return -EINVAL; 18167 } 18168 return 0; 18169 case BPF_JMP: 18170 case BPF_JMP32: 18171 return check_jmp_fields(env, insn); 18172 case BPF_LD: { 18173 u8 mode = BPF_MODE(insn->code); 18174 18175 if (mode == BPF_ABS || mode == BPF_IND) { 18176 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 18177 BPF_SIZE(insn->code) == BPF_DW || 18178 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 18179 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 18180 return -EINVAL; 18181 } 18182 } else if (mode != BPF_IMM) { 18183 verbose(env, "invalid BPF_LD mode\n"); 18184 return -EINVAL; 18185 } 18186 return 0; 18187 } 18188 default: 18189 verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code)); 18190 return -EINVAL; 18191 } 18192 } 18193 18194 /* 18195 * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions: 18196 * 18197 * 1. if it accesses map FD, replace it with actual map pointer. 18198 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18199 * 18200 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18201 */ 18202 static int check_and_resolve_insns(struct bpf_verifier_env *env) 18203 { 18204 struct bpf_insn *insn = env->prog->insnsi; 18205 int insn_cnt = env->prog->len; 18206 int i, err; 18207 18208 err = bpf_prog_calc_tag(env->prog); 18209 if (err) 18210 return err; 18211 18212 for (i = 0; i < insn_cnt; i++, insn++) { 18213 if (insn->dst_reg >= MAX_BPF_REG && 18214 !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) { 18215 verbose(env, "R%d is invalid\n", insn->dst_reg); 18216 return -EINVAL; 18217 } 18218 if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) { 18219 verbose(env, "R%d is invalid\n", insn->src_reg); 18220 return -EINVAL; 18221 } 18222 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18223 struct bpf_insn_aux_data *aux; 18224 struct bpf_map *map; 18225 int map_idx; 18226 u64 addr; 18227 18228 if (i == insn_cnt - 1 || insn[1].code != 0 || 18229 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18230 insn[1].off != 0) { 18231 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18232 return -EINVAL; 18233 } 18234 18235 if (insn[0].off != 0) { 18236 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 18237 return -EINVAL; 18238 } 18239 18240 if (insn[0].src_reg == 0) 18241 /* valid generic load 64-bit imm */ 18242 goto next_insn; 18243 18244 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18245 aux = &env->insn_aux_data[i]; 18246 err = check_pseudo_btf_id(env, insn, aux); 18247 if (err) 18248 return err; 18249 goto next_insn; 18250 } 18251 18252 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18253 aux = &env->insn_aux_data[i]; 18254 aux->ptr_type = PTR_TO_FUNC; 18255 goto next_insn; 18256 } 18257 18258 /* In final convert_pseudo_ld_imm64() step, this is 18259 * converted into regular 64-bit imm load insn. 18260 */ 18261 switch (insn[0].src_reg) { 18262 case BPF_PSEUDO_MAP_VALUE: 18263 case BPF_PSEUDO_MAP_IDX_VALUE: 18264 break; 18265 case BPF_PSEUDO_MAP_FD: 18266 case BPF_PSEUDO_MAP_IDX: 18267 if (insn[1].imm == 0) 18268 break; 18269 fallthrough; 18270 default: 18271 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18272 return -EINVAL; 18273 } 18274 18275 switch (insn[0].src_reg) { 18276 case BPF_PSEUDO_MAP_IDX_VALUE: 18277 case BPF_PSEUDO_MAP_IDX: 18278 map_idx = fd_array_get_map_idx(env, insn[0].imm); 18279 break; 18280 default: 18281 if (env->signature) { 18282 verbose(env, "signed program cannot reference a map by fd, only via fd_array index\n"); 18283 return -EINVAL; 18284 } 18285 map_idx = add_used_map(env, insn[0].imm); 18286 break; 18287 } 18288 18289 if (map_idx < 0) 18290 return map_idx; 18291 map = env->used_maps[map_idx]; 18292 18293 aux = &env->insn_aux_data[i]; 18294 aux->map_index = map_idx; 18295 18296 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18297 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18298 addr = (unsigned long)map; 18299 } else { 18300 u32 off = insn[1].imm; 18301 18302 if (!map->ops->map_direct_value_addr) { 18303 verbose(env, "no direct value access support for this map type\n"); 18304 return -EINVAL; 18305 } 18306 18307 err = map->ops->map_direct_value_addr(map, &addr, off); 18308 if (err) { 18309 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18310 map->value_size, off); 18311 return err; 18312 } 18313 18314 aux->map_off = off; 18315 addr += off; 18316 } 18317 18318 insn[0].imm = (u32)addr; 18319 insn[1].imm = addr >> 32; 18320 18321 next_insn: 18322 insn++; 18323 i++; 18324 continue; 18325 } 18326 18327 /* Basic sanity check before we invest more work here. */ 18328 if (!bpf_opcode_in_insntable(insn->code)) { 18329 verbose(env, "unknown opcode %02x\n", insn->code); 18330 return -EINVAL; 18331 } 18332 18333 err = check_insn_fields(env, insn); 18334 if (err) 18335 return err; 18336 } 18337 18338 /* now all pseudo BPF_LD_IMM64 instructions load valid 18339 * 'struct bpf_map *' into a register instead of user map_fd. 18340 * These pointers will be used later by verifier to validate map access. 18341 */ 18342 return 0; 18343 } 18344 18345 /* drop refcnt of maps used by the rejected program */ 18346 static void release_maps(struct bpf_verifier_env *env) 18347 { 18348 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18349 env->used_map_cnt); 18350 } 18351 18352 /* drop refcnt of maps used by the rejected program */ 18353 static void release_btfs(struct bpf_verifier_env *env) 18354 { 18355 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 18356 } 18357 18358 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18359 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18360 { 18361 struct bpf_insn *insn = env->prog->insnsi; 18362 int insn_cnt = env->prog->len; 18363 int i; 18364 18365 for (i = 0; i < insn_cnt; i++, insn++) { 18366 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18367 continue; 18368 if (insn->src_reg == BPF_PSEUDO_FUNC) 18369 continue; 18370 insn->src_reg = 0; 18371 } 18372 } 18373 18374 static void release_insn_arrays(struct bpf_verifier_env *env) 18375 { 18376 int i; 18377 18378 for (i = 0; i < env->insn_array_map_cnt; i++) 18379 bpf_insn_array_release(env->insn_array_maps[i]); 18380 } 18381 18382 18383 18384 /* The verifier does more data flow analysis than llvm and will not 18385 * explore branches that are dead at run time. Malicious programs can 18386 * have dead code too. Therefore replace all dead at-run-time code 18387 * with 'ja -1'. 18388 * 18389 * Just nops are not optimal, e.g. if they would sit at the end of the 18390 * program and through another bug we would manage to jump there, then 18391 * we'd execute beyond program memory otherwise. Returning exception 18392 * code also wouldn't work since we can have subprogs where the dead 18393 * code could be located. 18394 */ 18395 static void sanitize_dead_code(struct bpf_verifier_env *env) 18396 { 18397 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18398 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18399 struct bpf_insn *insn = env->prog->insnsi; 18400 const int insn_cnt = env->prog->len; 18401 int i; 18402 18403 for (i = 0; i < insn_cnt; i++) { 18404 if (aux_data[i].seen) 18405 continue; 18406 memcpy(insn + i, &trap, sizeof(trap)); 18407 aux_data[i].zext_dst = false; 18408 } 18409 } 18410 18411 18412 18413 static void free_states(struct bpf_verifier_env *env) 18414 { 18415 struct bpf_verifier_state_list *sl; 18416 struct list_head *head, *pos, *tmp; 18417 struct bpf_scc_info *info; 18418 int i, j; 18419 18420 bpf_free_verifier_state(env->cur_state, true); 18421 env->cur_state = NULL; 18422 while (!pop_stack(env, NULL, NULL, false)); 18423 18424 list_for_each_safe(pos, tmp, &env->free_list) { 18425 sl = container_of(pos, struct bpf_verifier_state_list, node); 18426 bpf_free_verifier_state(&sl->state, false); 18427 kfree(sl); 18428 } 18429 INIT_LIST_HEAD(&env->free_list); 18430 18431 for (i = 0; i < env->scc_cnt; ++i) { 18432 info = env->scc_info[i]; 18433 if (!info) 18434 continue; 18435 for (j = 0; j < info->num_visits; j++) 18436 bpf_free_backedges(&info->visits[j]); 18437 kvfree(info); 18438 env->scc_info[i] = NULL; 18439 } 18440 18441 if (!env->explored_states) 18442 return; 18443 18444 for (i = 0; i < state_htab_size(env); i++) { 18445 head = &env->explored_states[i]; 18446 18447 list_for_each_safe(pos, tmp, head) { 18448 sl = container_of(pos, struct bpf_verifier_state_list, node); 18449 bpf_free_verifier_state(&sl->state, false); 18450 kfree(sl); 18451 } 18452 INIT_LIST_HEAD(&env->explored_states[i]); 18453 } 18454 } 18455 18456 static int do_check_common(struct bpf_verifier_env *env, int subprog) 18457 { 18458 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18459 struct bpf_subprog_info *sub = subprog_info(env, subprog); 18460 struct bpf_prog_aux *aux = env->prog->aux; 18461 struct bpf_verifier_state *state; 18462 struct bpf_reg_state *regs; 18463 int ret, i; 18464 18465 env->prev_linfo = NULL; 18466 env->pass_cnt++; 18467 18468 state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT); 18469 if (!state) 18470 return -ENOMEM; 18471 state->curframe = 0; 18472 state->speculative = false; 18473 state->branches = 1; 18474 state->in_sleepable = env->prog->sleepable; 18475 state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT); 18476 if (!state->frame[0]) { 18477 kfree(state); 18478 return -ENOMEM; 18479 } 18480 env->cur_state = state; 18481 init_func_state(env, state->frame[0], 18482 BPF_MAIN_FUNC /* callsite */, 18483 0 /* frameno */, 18484 subprog); 18485 state->first_insn_idx = env->subprog_info[subprog].start; 18486 state->last_insn_idx = -1; 18487 18488 regs = state->frame[state->curframe]->regs; 18489 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 18490 const char *sub_name = subprog_name(env, subprog); 18491 struct bpf_subprog_arg_info *arg; 18492 struct bpf_reg_state *reg; 18493 18494 if (env->log.level & BPF_LOG_LEVEL) 18495 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 18496 ret = btf_prepare_func_args(env, subprog); 18497 if (ret) 18498 goto out; 18499 18500 if (subprog_is_exc_cb(env, subprog)) { 18501 state->frame[0]->in_exception_callback_fn = true; 18502 18503 /* 18504 * Global functions are scalar or void, make sure 18505 * we return a scalar. 18506 */ 18507 if (subprog_returns_void(env, subprog)) { 18508 verbose(env, "exception cb cannot return void\n"); 18509 ret = -EINVAL; 18510 goto out; 18511 } 18512 18513 /* Also ensure the callback only has a single scalar argument. */ 18514 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 18515 verbose(env, "exception cb only supports single integer argument\n"); 18516 ret = -EINVAL; 18517 goto out; 18518 } 18519 } 18520 for (i = BPF_REG_1; i <= min_t(u32, sub->arg_cnt, MAX_BPF_FUNC_REG_ARGS); i++) { 18521 arg = &sub->args[i - BPF_REG_1]; 18522 reg = ®s[i]; 18523 18524 if (arg->arg_type == ARG_PTR_TO_CTX) { 18525 reg->type = PTR_TO_CTX; 18526 mark_reg_known_zero(env, regs, i); 18527 } else if (arg->arg_type == ARG_ANYTHING) { 18528 reg->type = SCALAR_VALUE; 18529 mark_reg_unknown(env, regs, i); 18530 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 18531 /* assume unspecial LOCAL dynptr type */ 18532 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen, 0); 18533 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 18534 reg->type = PTR_TO_MEM; 18535 reg->type |= arg->arg_type & 18536 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 18537 mark_reg_known_zero(env, regs, i); 18538 reg->mem_size = arg->mem_size; 18539 if (arg->arg_type & PTR_MAYBE_NULL) 18540 reg->id = ++env->id_gen; 18541 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 18542 reg->type = PTR_TO_BTF_ID; 18543 if (arg->arg_type & PTR_MAYBE_NULL) 18544 reg->type |= PTR_MAYBE_NULL; 18545 if (arg->arg_type & PTR_UNTRUSTED) 18546 reg->type |= PTR_UNTRUSTED; 18547 if (arg->arg_type & PTR_TRUSTED) 18548 reg->type |= PTR_TRUSTED; 18549 mark_reg_known_zero(env, regs, i); 18550 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 18551 reg->btf_id = arg->btf_id; 18552 reg->id = ++env->id_gen; 18553 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 18554 /* caller can pass either PTR_TO_ARENA or SCALAR */ 18555 mark_reg_unknown(env, regs, i); 18556 } else { 18557 verifier_bug(env, "unhandled arg#%d type %d", 18558 i - BPF_REG_1 + 1, arg->arg_type); 18559 ret = -EFAULT; 18560 goto out; 18561 } 18562 } 18563 if (env->prog->type == BPF_PROG_TYPE_EXT && sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS) { 18564 verbose(env, "freplace programs with >%d args not supported yet\n", 18565 MAX_BPF_FUNC_REG_ARGS); 18566 ret = -EINVAL; 18567 goto out; 18568 } 18569 } else { 18570 /* if main BPF program has associated BTF info, validate that 18571 * it's matching expected signature, and otherwise mark BTF 18572 * info for main program as unreliable 18573 */ 18574 if (env->prog->aux->func_info_aux) { 18575 ret = btf_prepare_func_args(env, 0); 18576 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) { 18577 env->prog->aux->func_info_aux[0].unreliable = true; 18578 sub->arg_cnt = 1; 18579 sub->stack_arg_cnt = 0; 18580 } 18581 } 18582 18583 /* 1st arg to a function */ 18584 regs[BPF_REG_1].type = PTR_TO_CTX; 18585 mark_reg_known_zero(env, regs, BPF_REG_1); 18586 } 18587 18588 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 18589 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 18590 for (i = 0; i < aux->ctx_arg_info_size; i++) { 18591 ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0; 18592 if (ret < 0) 18593 goto out; 18594 18595 aux->ctx_arg_info[i].ref_id = ret; 18596 } 18597 } 18598 18599 ret = do_check(env); 18600 out: 18601 if (!ret && pop_log) 18602 bpf_vlog_reset(&env->log, 0); 18603 free_states(env); 18604 return ret; 18605 } 18606 18607 /* Lazily verify all global functions based on their BTF, if they are called 18608 * from main BPF program or any of subprograms transitively. 18609 * BPF global subprogs called from dead code are not validated. 18610 * All callable global functions must pass verification. 18611 * Otherwise the whole program is rejected. 18612 * Consider: 18613 * int bar(int); 18614 * int foo(int f) 18615 * { 18616 * return bar(f); 18617 * } 18618 * int bar(int b) 18619 * { 18620 * ... 18621 * } 18622 * foo() will be verified first for R1=any_scalar_value. During verification it 18623 * will be assumed that bar() already verified successfully and call to bar() 18624 * from foo() will be checked for type match only. Later bar() will be verified 18625 * independently to check that it's safe for R1=any_scalar_value. 18626 */ 18627 static int do_check_subprogs(struct bpf_verifier_env *env) 18628 { 18629 struct bpf_prog_aux *aux = env->prog->aux; 18630 struct bpf_func_info_aux *sub_aux; 18631 int i, ret, new_cnt; 18632 u32 insn_processed; 18633 18634 if (!aux->func_info) 18635 return 0; 18636 18637 /* exception callback is presumed to be always called */ 18638 if (env->exception_callback_subprog) 18639 subprog_aux(env, env->exception_callback_subprog)->called = true; 18640 18641 again: 18642 new_cnt = 0; 18643 for (i = 1; i < env->subprog_cnt; i++) { 18644 if (!bpf_subprog_is_global(env, i)) 18645 continue; 18646 18647 insn_processed = env->insn_processed; 18648 18649 sub_aux = subprog_aux(env, i); 18650 if (!sub_aux->called || sub_aux->verified) 18651 continue; 18652 18653 env->insn_idx = env->subprog_info[i].start; 18654 WARN_ON_ONCE(env->insn_idx == 0); 18655 ret = do_check_common(env, i); 18656 env->subprog_info[i].insn_processed = env->insn_processed - insn_processed; 18657 if (ret) { 18658 return ret; 18659 } else if (env->log.level & BPF_LOG_LEVEL) { 18660 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 18661 i, subprog_name(env, i)); 18662 } 18663 18664 /* We verified new global subprog, it might have called some 18665 * more global subprogs that we haven't verified yet, so we 18666 * need to do another pass over subprogs to verify those. 18667 */ 18668 sub_aux->verified = true; 18669 new_cnt++; 18670 } 18671 18672 /* We can't loop forever as we verify at least one global subprog on 18673 * each pass. 18674 */ 18675 if (new_cnt) 18676 goto again; 18677 18678 return 0; 18679 } 18680 18681 static int do_check_main(struct bpf_verifier_env *env) 18682 { 18683 u32 insn_processed = env->insn_processed; 18684 int ret; 18685 18686 env->insn_idx = 0; 18687 ret = do_check_common(env, 0); 18688 env->subprog_info[0].insn_processed = env->insn_processed - insn_processed; 18689 if (!ret) 18690 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18691 return ret; 18692 } 18693 18694 18695 static void print_verification_stats(struct bpf_verifier_env *env) 18696 { 18697 /* Skip over hidden subprogs which are not verified. */ 18698 int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18699 18700 if (env->log.level & BPF_LOG_STATS) { 18701 verbose(env, "verification time %lld usec\n", 18702 div_u64(env->verification_time, 1000)); 18703 verbose(env, "stack depth %d", env->subprog_info[0].stack_depth); 18704 for (i = 1; i < subprog_cnt; i++) 18705 verbose(env, "+%d", env->subprog_info[i].stack_depth); 18706 verbose(env, " max %d\n", env->max_stack_depth); 18707 verbose(env, "insns processed %d", env->subprog_info[0].insn_processed); 18708 for (i = 1; i < subprog_cnt; i++) 18709 if (bpf_subprog_is_global(env, i)) 18710 verbose(env, "+%d", env->subprog_info[i].insn_processed); 18711 verbose(env, "\n"); 18712 } 18713 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 18714 "total_states %d peak_states %d mark_read %d\n", 18715 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 18716 env->max_states_per_insn, env->total_states, 18717 env->peak_states, env->longest_mark_read_walk); 18718 } 18719 18720 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 18721 const struct bpf_ctx_arg_aux *info, u32 cnt) 18722 { 18723 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 18724 prog->aux->ctx_arg_info_size = cnt; 18725 18726 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 18727 } 18728 18729 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 18730 { 18731 const struct btf_type *t, *func_proto; 18732 const struct bpf_struct_ops_desc *st_ops_desc; 18733 const struct bpf_struct_ops *st_ops; 18734 const struct btf_member *member; 18735 struct bpf_prog *prog = env->prog; 18736 bool has_refcounted_arg = false; 18737 u32 btf_id, member_idx, member_off; 18738 struct btf *btf; 18739 const char *mname; 18740 int i, err; 18741 18742 if (!prog->gpl_compatible) { 18743 verbose(env, "struct ops programs must have a GPL compatible license\n"); 18744 return -EINVAL; 18745 } 18746 18747 if (!prog->aux->attach_btf_id) 18748 return -ENOTSUPP; 18749 18750 btf = prog->aux->attach_btf; 18751 if (btf_is_module(btf)) { 18752 /* Make sure st_ops is valid through the lifetime of env */ 18753 env->attach_btf_mod = btf_try_get_module(btf); 18754 if (!env->attach_btf_mod) { 18755 verbose(env, "struct_ops module %s is not found\n", 18756 btf_get_name(btf)); 18757 return -ENOTSUPP; 18758 } 18759 } 18760 18761 btf_id = prog->aux->attach_btf_id; 18762 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 18763 if (!st_ops_desc) { 18764 verbose(env, "attach_btf_id %u is not a supported struct\n", 18765 btf_id); 18766 return -ENOTSUPP; 18767 } 18768 st_ops = st_ops_desc->st_ops; 18769 18770 t = st_ops_desc->type; 18771 member_idx = prog->expected_attach_type; 18772 if (member_idx >= btf_type_vlen(t)) { 18773 verbose(env, "attach to invalid member idx %u of struct %s\n", 18774 member_idx, st_ops->name); 18775 return -EINVAL; 18776 } 18777 18778 member = &btf_type_member(t)[member_idx]; 18779 mname = btf_name_by_offset(btf, member->name_off); 18780 func_proto = btf_type_resolve_func_ptr(btf, member->type, 18781 NULL); 18782 if (!func_proto) { 18783 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 18784 mname, member_idx, st_ops->name); 18785 return -EINVAL; 18786 } 18787 18788 member_off = __btf_member_bit_offset(t, member) / 8; 18789 err = bpf_struct_ops_supported(st_ops, member_off); 18790 if (err) { 18791 verbose(env, "attach to unsupported member %s of struct %s\n", 18792 mname, st_ops->name); 18793 return err; 18794 } 18795 18796 if (st_ops->check_member) { 18797 err = st_ops->check_member(t, member, prog); 18798 18799 if (err) { 18800 verbose(env, "attach to unsupported member %s of struct %s\n", 18801 mname, st_ops->name); 18802 return err; 18803 } 18804 } 18805 18806 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 18807 verbose(env, "Private stack not supported by jit\n"); 18808 return -EACCES; 18809 } 18810 18811 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) { 18812 if (st_ops_desc->arg_info[member_idx].info[i].refcounted) { 18813 has_refcounted_arg = true; 18814 break; 18815 } 18816 } 18817 18818 /* Tail call is not allowed for programs with refcounted arguments since we 18819 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 18820 */ 18821 for (i = 0; i < env->subprog_cnt; i++) { 18822 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 18823 verbose(env, "program with __ref argument cannot tail call\n"); 18824 return -EINVAL; 18825 } 18826 } 18827 18828 prog->aux->st_ops = st_ops; 18829 prog->aux->attach_st_ops_member_off = member_off; 18830 18831 prog->aux->attach_func_proto = func_proto; 18832 prog->aux->attach_func_name = mname; 18833 env->ops = st_ops->verifier_ops; 18834 18835 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info, 18836 st_ops_desc->arg_info[member_idx].cnt); 18837 } 18838 #define SECURITY_PREFIX "security_" 18839 18840 #ifdef CONFIG_FUNCTION_ERROR_INJECTION 18841 18842 /* list of non-sleepable functions that are otherwise on 18843 * ALLOW_ERROR_INJECTION list 18844 */ 18845 BTF_SET_START(btf_non_sleepable_error_inject) 18846 /* Three functions below can be called from sleepable and non-sleepable context. 18847 * Assume non-sleepable from bpf safety point of view. 18848 */ 18849 BTF_ID(func, __filemap_add_folio) 18850 #ifdef CONFIG_FAIL_PAGE_ALLOC 18851 BTF_ID(func, should_fail_alloc_page) 18852 #endif 18853 #ifdef CONFIG_FAILSLAB 18854 BTF_ID(func, should_failslab) 18855 #endif 18856 BTF_SET_END(btf_non_sleepable_error_inject) 18857 18858 static int check_non_sleepable_error_inject(u32 btf_id) 18859 { 18860 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 18861 } 18862 18863 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18864 { 18865 /* fentry/fexit/fmod_ret progs can be sleepable if they are 18866 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 18867 */ 18868 if (!check_non_sleepable_error_inject(btf_id) && 18869 within_error_injection_list(addr)) 18870 return 0; 18871 18872 return -EINVAL; 18873 } 18874 18875 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18876 { 18877 if (within_error_injection_list(addr) || 18878 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18879 return 0; 18880 18881 return -EINVAL; 18882 } 18883 18884 #else 18885 18886 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code 18887 * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name() 18888 * but that just compares two concrete function names. 18889 */ 18890 static bool has_arch_syscall_prefix(const char *func_name) 18891 { 18892 #if defined(__x86_64__) 18893 return !strncmp(func_name, "__x64_", 6); 18894 #elif defined(__i386__) 18895 return !strncmp(func_name, "__ia32_", 7); 18896 #elif defined(__s390x__) 18897 return !strncmp(func_name, "__s390x_", 8); 18898 #elif defined(__aarch64__) 18899 return !strncmp(func_name, "__arm64_", 8); 18900 #elif defined(__riscv) 18901 return !strncmp(func_name, "__riscv_", 8); 18902 #elif defined(__powerpc__) || defined(__powerpc64__) 18903 return !strncmp(func_name, "sys_", 4); 18904 #elif defined(__loongarch__) 18905 return !strncmp(func_name, "sys_", 4); 18906 #else 18907 return false; 18908 #endif 18909 } 18910 18911 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */ 18912 18913 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18914 { 18915 if (has_arch_syscall_prefix(func_name)) 18916 return 0; 18917 18918 return -EINVAL; 18919 } 18920 18921 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18922 { 18923 if (has_arch_syscall_prefix(func_name) || 18924 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18925 return 0; 18926 18927 return -EINVAL; 18928 } 18929 18930 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */ 18931 18932 static bool is_tracing_multi_id(const struct bpf_prog *prog, u32 btf_id) 18933 { 18934 return is_tracing_multi(prog->expected_attach_type) && bpf_multi_func_btf_id[0] == btf_id; 18935 } 18936 18937 static int btf_id_allow_sleepable(u32 btf_id, unsigned long addr, const struct bpf_prog *prog, 18938 const struct btf *btf) 18939 { 18940 const struct btf_type *t; 18941 const char *tname; 18942 18943 switch (prog->type) { 18944 case BPF_PROG_TYPE_TRACING: 18945 t = btf_type_by_id(btf, btf_id); 18946 if (!t) 18947 return -EINVAL; 18948 tname = btf_name_by_offset(btf, t->name_off); 18949 if (!tname) 18950 return -EINVAL; 18951 18952 /* 18953 * *.multi sleepable programs will pass initial sleepable check, 18954 * the actual attached btf ids are checked later during the link 18955 * attachment. 18956 */ 18957 if (is_tracing_multi_id(prog, btf_id)) 18958 return 0; 18959 if (!check_attach_sleepable(btf_id, addr, tname)) 18960 return 0; 18961 /* 18962 * fentry/fexit/fmod_ret progs can also be sleepable if they are 18963 * in the fmodret id set with the KF_SLEEPABLE flag. 18964 */ 18965 else { 18966 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog); 18967 18968 if (flags && (*flags & KF_SLEEPABLE)) 18969 return 0; 18970 } 18971 break; 18972 case BPF_PROG_TYPE_LSM: 18973 /* 18974 * LSM progs check that they are attached to bpf_lsm_*() funcs. 18975 * Only some of them are sleepable. 18976 */ 18977 if (bpf_lsm_is_sleepable_hook(btf_id)) 18978 return 0; 18979 break; 18980 default: 18981 break; 18982 } 18983 return -EINVAL; 18984 } 18985 18986 /* 18987 * Resolve the prototype describing a trace target's real ABI. A 18988 * KF_IMPLICIT_ARGS kfunc has its injected args stripped from the public 18989 * prototype, so use the _impl prototype; other targets use their own. 18990 */ 18991 static const struct btf_type * 18992 btf_attach_func_proto(struct bpf_verifier_log *log, struct btf *btf, u32 func_id) 18993 { 18994 const struct btf_type *func; 18995 struct module *mod = NULL; 18996 const char *name; 18997 int implicit; 18998 18999 func = btf_type_by_id(btf, func_id); 19000 if (!func || !btf_type_is_func(func)) 19001 return NULL; 19002 name = btf_name_by_offset(btf, func->name_off); 19003 19004 /* 19005 * btf_kfunc_check_flag() reads kfunc_set_tab, which for a module is 19006 * stable only once it is live; hold a module ref across the read to 19007 * exclude a concurrent module load. 19008 */ 19009 if (btf_is_module(btf)) { 19010 mod = btf_try_get_module(btf); 19011 if (!mod) 19012 return NULL; 19013 } 19014 implicit = btf_kfunc_check_flag(btf, func_id, KF_IMPLICIT_ARGS); 19015 module_put(mod); 19016 19017 if (implicit == -EINVAL) { 19018 bpf_log(log, "kfunc %s has inconsistent KF_IMPLICIT_ARGS\n", name); 19019 return NULL; 19020 } 19021 if (implicit > 0) 19022 return find_kfunc_impl_proto(log, btf, name); 19023 19024 return btf_type_by_id(btf, func->type); 19025 } 19026 19027 int bpf_check_attach_target(struct bpf_verifier_log *log, 19028 const struct bpf_prog *prog, 19029 const struct bpf_prog *tgt_prog, 19030 u32 btf_id, 19031 struct bpf_attach_target_info *tgt_info) 19032 { 19033 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 19034 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 19035 char trace_symbol[KSYM_SYMBOL_LEN]; 19036 const char prefix[] = "btf_trace_"; 19037 struct bpf_raw_event_map *btp; 19038 int ret = 0, subprog = -1, i; 19039 const struct btf_type *t; 19040 bool conservative = true; 19041 const char *tname, *fname; 19042 struct btf *btf; 19043 long addr = 0; 19044 struct module *mod = NULL; 19045 19046 if (!btf_id) { 19047 bpf_log(log, "Tracing programs must provide btf_id\n"); 19048 return -EINVAL; 19049 } 19050 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 19051 if (!btf) { 19052 bpf_log(log, 19053 "Tracing program can only be attached to another program annotated with BTF\n"); 19054 return -EINVAL; 19055 } 19056 t = btf_type_by_id(btf, btf_id); 19057 if (!t) { 19058 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 19059 return -EINVAL; 19060 } 19061 tname = btf_name_by_offset(btf, t->name_off); 19062 if (!tname) { 19063 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 19064 return -EINVAL; 19065 } 19066 if (tgt_prog) { 19067 struct bpf_prog_aux *aux = tgt_prog->aux; 19068 bool tgt_changes_pkt_data; 19069 bool tgt_might_sleep; 19070 19071 if (bpf_prog_is_dev_bound(prog->aux) && 19072 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 19073 bpf_log(log, "Target program bound device mismatch"); 19074 return -EINVAL; 19075 } 19076 19077 for (i = 0; i < aux->func_info_cnt; i++) 19078 if (aux->func_info[i].type_id == btf_id) { 19079 subprog = i; 19080 break; 19081 } 19082 if (subprog == -1) { 19083 bpf_log(log, "Subprog %s doesn't exist\n", tname); 19084 return -EINVAL; 19085 } 19086 if (aux->func && aux->func[subprog]->aux->exception_cb) { 19087 bpf_log(log, 19088 "%s programs cannot attach to exception callback\n", 19089 prog_extension ? "Extension" : "Tracing"); 19090 return -EINVAL; 19091 } 19092 conservative = aux->func_info_aux[subprog].unreliable; 19093 if (prog_extension) { 19094 if (conservative) { 19095 bpf_log(log, 19096 "Cannot replace static functions\n"); 19097 return -EINVAL; 19098 } 19099 if (!prog->jit_requested) { 19100 bpf_log(log, 19101 "Extension programs should be JITed\n"); 19102 return -EINVAL; 19103 } 19104 tgt_changes_pkt_data = aux->func 19105 ? aux->func[subprog]->aux->changes_pkt_data 19106 : aux->changes_pkt_data; 19107 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 19108 bpf_log(log, 19109 "Extension program changes packet data, while original does not\n"); 19110 return -EINVAL; 19111 } 19112 19113 tgt_might_sleep = aux->func 19114 ? aux->func[subprog]->aux->might_sleep 19115 : aux->might_sleep; 19116 if (prog->aux->might_sleep && !tgt_might_sleep) { 19117 bpf_log(log, 19118 "Extension program may sleep, while original does not\n"); 19119 return -EINVAL; 19120 } 19121 } 19122 if (!tgt_prog->jited) { 19123 bpf_log(log, "Can attach to only JITed progs\n"); 19124 return -EINVAL; 19125 } 19126 if (prog_tracing) { 19127 if (aux->attach_tracing_prog) { 19128 /* 19129 * Target program is an fentry/fexit which is already attached 19130 * to another tracing program. More levels of nesting 19131 * attachment are not allowed. 19132 */ 19133 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 19134 return -EINVAL; 19135 } 19136 } else if (tgt_prog->type == prog->type) { 19137 /* 19138 * To avoid potential call chain cycles, prevent attaching of a 19139 * program extension to another extension. It's ok to attach 19140 * fentry/fexit to extension program. 19141 */ 19142 bpf_log(log, "Cannot recursively attach\n"); 19143 return -EINVAL; 19144 } 19145 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19146 prog_extension && 19147 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19148 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT || 19149 tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI || 19150 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || 19151 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION || 19152 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19153 /* Program extensions can extend all program types 19154 * except fentry/fexit. The reason is the following. 19155 * The fentry/fexit programs are used for performance 19156 * analysis, stats and can be attached to any program 19157 * type. When extension program is replacing XDP function 19158 * it is necessary to allow performance analysis of all 19159 * functions. Both original XDP program and its program 19160 * extension. Hence attaching fentry/fexit to 19161 * BPF_PROG_TYPE_EXT is allowed. If extending of 19162 * fentry/fexit was allowed it would be possible to create 19163 * long call chain fentry->extension->fentry->extension 19164 * beyond reasonable stack size. Hence extending fentry 19165 * is not allowed. 19166 */ 19167 bpf_log(log, "Cannot extend fentry/fexit/fsession\n"); 19168 return -EINVAL; 19169 } 19170 } else { 19171 if (prog_extension) { 19172 bpf_log(log, "Cannot replace kernel functions\n"); 19173 return -EINVAL; 19174 } 19175 } 19176 19177 switch (prog->expected_attach_type) { 19178 case BPF_TRACE_RAW_TP: 19179 if (tgt_prog) { 19180 bpf_log(log, 19181 "Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n"); 19182 return -EINVAL; 19183 } 19184 if (!btf_type_is_typedef(t)) { 19185 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19186 btf_id); 19187 return -EINVAL; 19188 } 19189 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19190 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19191 btf_id, tname); 19192 return -EINVAL; 19193 } 19194 tname += sizeof(prefix) - 1; 19195 19196 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 19197 * names. Thus using bpf_raw_event_map to get argument names. 19198 */ 19199 btp = bpf_get_raw_tracepoint(tname); 19200 if (!btp) 19201 return -EINVAL; 19202 if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) { 19203 bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n", 19204 tname); 19205 bpf_put_raw_tracepoint(btp); 19206 return -EINVAL; 19207 } 19208 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 19209 trace_symbol); 19210 bpf_put_raw_tracepoint(btp); 19211 19212 if (fname) 19213 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 19214 19215 if (!fname || ret < 0) { 19216 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 19217 prefix, tname); 19218 t = btf_type_by_id(btf, t->type); 19219 if (!btf_type_is_ptr(t)) 19220 /* should never happen in valid vmlinux build */ 19221 return -EINVAL; 19222 } else { 19223 t = btf_type_by_id(btf, ret); 19224 if (!btf_type_is_func(t)) 19225 /* should never happen in valid vmlinux build */ 19226 return -EINVAL; 19227 } 19228 19229 t = btf_type_by_id(btf, t->type); 19230 if (!btf_type_is_func_proto(t)) 19231 /* should never happen in valid vmlinux build */ 19232 return -EINVAL; 19233 19234 break; 19235 case BPF_TRACE_ITER: 19236 if (!btf_type_is_func(t)) { 19237 bpf_log(log, "attach_btf_id %u is not a function\n", 19238 btf_id); 19239 return -EINVAL; 19240 } 19241 t = btf_type_by_id(btf, t->type); 19242 if (!btf_type_is_func_proto(t)) 19243 return -EINVAL; 19244 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19245 if (ret) 19246 return ret; 19247 break; 19248 default: 19249 if (!prog_extension) 19250 return -EINVAL; 19251 fallthrough; 19252 case BPF_MODIFY_RETURN: 19253 case BPF_LSM_MAC: 19254 case BPF_LSM_CGROUP: 19255 case BPF_TRACE_FENTRY: 19256 case BPF_TRACE_FEXIT: 19257 case BPF_TRACE_FSESSION: 19258 case BPF_TRACE_FSESSION_MULTI: 19259 case BPF_TRACE_FENTRY_MULTI: 19260 case BPF_TRACE_FEXIT_MULTI: 19261 if ((prog->expected_attach_type == BPF_TRACE_FSESSION || 19262 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) && 19263 !bpf_jit_supports_fsession()) { 19264 bpf_log(log, "JIT does not support fsession\n"); 19265 return -EOPNOTSUPP; 19266 } 19267 if (!btf_type_is_func(t)) { 19268 bpf_log(log, "attach_btf_id %u is not a function\n", 19269 btf_id); 19270 return -EINVAL; 19271 } 19272 if (prog_extension && 19273 btf_check_type_match(log, prog, btf, t)) 19274 return -EINVAL; 19275 t = btf_attach_func_proto(log, btf, btf_id); 19276 if (!t || !btf_type_is_func_proto(t)) 19277 return -EINVAL; 19278 19279 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 19280 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 19281 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 19282 return -EINVAL; 19283 19284 if (tgt_prog && conservative) 19285 t = NULL; 19286 19287 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19288 if (ret < 0) 19289 return ret; 19290 19291 /* 19292 * *.multi programs don't need an address during program 19293 * verification, we just take the module ref if needed. 19294 */ 19295 if (is_tracing_multi_id(prog, btf_id)) { 19296 if (btf_is_module(btf)) { 19297 mod = btf_try_get_module(btf); 19298 if (!mod) 19299 return -ENOENT; 19300 } 19301 addr = 0; 19302 } else if (tgt_prog) { 19303 if (subprog == 0) 19304 addr = (long) tgt_prog->bpf_func; 19305 else 19306 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 19307 } else { 19308 if (btf_is_module(btf)) { 19309 mod = btf_try_get_module(btf); 19310 if (mod) 19311 addr = find_kallsyms_symbol_value(mod, tname); 19312 else 19313 addr = 0; 19314 } else { 19315 addr = kallsyms_lookup_name(tname); 19316 } 19317 if (!addr) { 19318 module_put(mod); 19319 bpf_log(log, 19320 "The address of function %s cannot be found\n", 19321 tname); 19322 return -ENOENT; 19323 } 19324 } 19325 19326 if (prog->sleepable) { 19327 ret = btf_id_allow_sleepable(btf_id, addr, prog, btf); 19328 if (ret) { 19329 module_put(mod); 19330 bpf_log(log, "%s is not sleepable\n", tname); 19331 return ret; 19332 } 19333 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19334 if (tgt_prog) { 19335 module_put(mod); 19336 bpf_log(log, "can't modify return codes of BPF programs\n"); 19337 return -EINVAL; 19338 } 19339 ret = -EINVAL; 19340 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19341 !check_attach_modify_return(addr, tname)) 19342 ret = 0; 19343 if (ret) { 19344 module_put(mod); 19345 bpf_log(log, "%s() is not modifiable\n", tname); 19346 return ret; 19347 } 19348 } 19349 19350 break; 19351 } 19352 tgt_info->tgt_addr = addr; 19353 tgt_info->tgt_name = tname; 19354 tgt_info->tgt_type = t; 19355 tgt_info->tgt_mod = mod; 19356 return 0; 19357 } 19358 19359 BTF_SET_START(btf_id_deny) 19360 BTF_ID_UNUSED 19361 #ifdef CONFIG_SMP 19362 BTF_ID(func, ___migrate_enable) 19363 BTF_ID(func, migrate_disable) 19364 BTF_ID(func, migrate_enable) 19365 #endif 19366 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19367 BTF_ID(func, rcu_read_unlock_strict) 19368 #endif 19369 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19370 BTF_ID(func, preempt_count_add) 19371 BTF_ID(func, preempt_count_sub) 19372 #endif 19373 #ifdef CONFIG_PREEMPT_RCU 19374 BTF_ID(func, __rcu_read_lock) 19375 BTF_ID(func, __rcu_read_unlock) 19376 #endif 19377 BTF_SET_END(btf_id_deny) 19378 19379 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 19380 * Currently, we must manually list all __noreturn functions here. Once a more 19381 * robust solution is implemented, this workaround can be removed. 19382 */ 19383 BTF_SET_START(noreturn_deny) 19384 #ifdef CONFIG_IA32_EMULATION 19385 BTF_ID(func, __ia32_sys_exit) 19386 BTF_ID(func, __ia32_sys_exit_group) 19387 #endif 19388 #ifdef CONFIG_KUNIT 19389 BTF_ID(func, __kunit_abort) 19390 BTF_ID(func, kunit_try_catch_throw) 19391 #endif 19392 #ifdef CONFIG_MODULES 19393 BTF_ID(func, __module_put_and_kthread_exit) 19394 #endif 19395 #ifdef CONFIG_X86_64 19396 BTF_ID(func, __x64_sys_exit) 19397 BTF_ID(func, __x64_sys_exit_group) 19398 #endif 19399 BTF_ID(func, do_exit) 19400 BTF_ID(func, do_group_exit) 19401 BTF_ID(func, kthread_complete_and_exit) 19402 BTF_ID(func, make_task_dead) 19403 BTF_SET_END(noreturn_deny) 19404 19405 static bool can_be_sleepable(struct bpf_prog *prog) 19406 { 19407 if (prog->type == BPF_PROG_TYPE_TRACING) { 19408 switch (prog->expected_attach_type) { 19409 case BPF_TRACE_FENTRY: 19410 case BPF_TRACE_FEXIT: 19411 case BPF_MODIFY_RETURN: 19412 case BPF_TRACE_ITER: 19413 case BPF_TRACE_FSESSION: 19414 case BPF_TRACE_RAW_TP: 19415 case BPF_TRACE_FENTRY_MULTI: 19416 case BPF_TRACE_FEXIT_MULTI: 19417 case BPF_TRACE_FSESSION_MULTI: 19418 return true; 19419 default: 19420 return false; 19421 } 19422 } 19423 if (prog->type == BPF_PROG_TYPE_LSM) 19424 return prog->expected_attach_type != BPF_LSM_CGROUP; 19425 19426 return prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 19427 prog->type == BPF_PROG_TYPE_STRUCT_OPS || 19428 prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT || 19429 prog->type == BPF_PROG_TYPE_TRACEPOINT; 19430 } 19431 19432 static int check_attach_btf_id(struct bpf_verifier_env *env) 19433 { 19434 struct bpf_prog *prog = env->prog; 19435 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 19436 struct bpf_attach_target_info tgt_info = {}; 19437 u32 btf_id = prog->aux->attach_btf_id; 19438 struct bpf_trampoline *tr; 19439 int ret; 19440 u64 key; 19441 19442 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 19443 if (prog->sleepable) 19444 /* attach_btf_id checked to be zero already */ 19445 return 0; 19446 verbose(env, "Syscall programs can only be sleepable\n"); 19447 return -EINVAL; 19448 } 19449 19450 if (prog->sleepable && !can_be_sleepable(prog)) { 19451 verbose(env, "Program of this type cannot be sleepable\n"); 19452 return -EINVAL; 19453 } 19454 19455 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 19456 return check_struct_ops_btf_id(env); 19457 19458 if (prog->type != BPF_PROG_TYPE_TRACING && 19459 prog->type != BPF_PROG_TYPE_LSM && 19460 prog->type != BPF_PROG_TYPE_EXT) 19461 return 0; 19462 19463 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 19464 if (ret) 19465 return ret; 19466 19467 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 19468 /* to make freplace equivalent to their targets, they need to 19469 * inherit env->ops and expected_attach_type for the rest of the 19470 * verification 19471 */ 19472 env->ops = bpf_verifier_ops[tgt_prog->type]; 19473 prog->expected_attach_type = tgt_prog->expected_attach_type; 19474 } 19475 19476 /* store info about the attachment target that will be used later */ 19477 prog->aux->attach_func_proto = tgt_info.tgt_type; 19478 prog->aux->attach_func_name = tgt_info.tgt_name; 19479 prog->aux->mod = tgt_info.tgt_mod; 19480 19481 if (tgt_prog) { 19482 prog->aux->saved_dst_prog_type = tgt_prog->type; 19483 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 19484 } 19485 19486 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 19487 prog->aux->attach_btf_trace = true; 19488 return 0; 19489 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 19490 return bpf_iter_prog_supported(prog); 19491 } 19492 19493 if (prog->type == BPF_PROG_TYPE_LSM) { 19494 ret = bpf_lsm_verify_prog(&env->log, prog); 19495 if (ret < 0) 19496 return ret; 19497 } else if (prog->type == BPF_PROG_TYPE_TRACING && 19498 btf_id_set_contains(&btf_id_deny, btf_id)) { 19499 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 19500 tgt_info.tgt_name); 19501 return -EINVAL; 19502 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 19503 prog->expected_attach_type == BPF_TRACE_FSESSION || 19504 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI || 19505 prog->expected_attach_type == BPF_MODIFY_RETURN) && 19506 btf_id_set_contains(&noreturn_deny, btf_id)) { 19507 verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n", 19508 tgt_info.tgt_name); 19509 return -EINVAL; 19510 } 19511 19512 /* 19513 * We don't get trampoline for tracing_multi programs at this point, 19514 * it's done when tracing_multi link is created. 19515 */ 19516 if (prog->type == BPF_PROG_TYPE_TRACING && 19517 is_tracing_multi(prog->expected_attach_type)) 19518 return 0; 19519 19520 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 19521 tr = bpf_trampoline_get(key, &tgt_info); 19522 if (!tr) 19523 return -ENOMEM; 19524 19525 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 19526 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 19527 19528 prog->aux->dst_trampoline = tr; 19529 return 0; 19530 } 19531 19532 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id, 19533 struct bpf_attach_target_info *tgt_info) 19534 { 19535 const struct btf_type *t; 19536 unsigned long addr; 19537 const char *tname; 19538 int err; 19539 19540 if (!btf_id || !btf) 19541 return -EINVAL; 19542 19543 /* Check noreturn attachment. */ 19544 if ((prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || 19545 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) && 19546 btf_id_set_contains(&noreturn_deny, btf_id)) 19547 return -EINVAL; 19548 /* Check denied attachment. */ 19549 if (btf_id_set_contains(&btf_id_deny, btf_id)) 19550 return -EINVAL; 19551 19552 /* Check and get function target data. */ 19553 t = btf_type_by_id(btf, btf_id); 19554 if (!t) 19555 return -EINVAL; 19556 tname = btf_name_by_offset(btf, t->name_off); 19557 if (!tname) 19558 return -EINVAL; 19559 t = btf_attach_func_proto(NULL, btf, btf_id); 19560 if (!t || !btf_type_is_func_proto(t)) 19561 return -EINVAL; 19562 err = btf_distill_func_proto(NULL, btf, t, tname, &tgt_info->fmodel); 19563 if (err < 0) 19564 return err; 19565 if (btf_is_module(btf)) { 19566 /* The bpf program already holds reference to module. */ 19567 if (WARN_ON_ONCE(!prog->aux->mod)) 19568 return -EINVAL; 19569 addr = find_kallsyms_symbol_value(prog->aux->mod, tname); 19570 } else { 19571 addr = kallsyms_lookup_name(tname); 19572 } 19573 if (!addr || !ftrace_location(addr)) 19574 return -ENOENT; 19575 19576 /* Check sleepable program attachment. */ 19577 if (prog->sleepable) { 19578 err = btf_id_allow_sleepable(btf_id, addr, prog, btf); 19579 if (err) 19580 return err; 19581 } 19582 tgt_info->tgt_addr = addr; 19583 return 0; 19584 } 19585 19586 struct btf *bpf_get_btf_vmlinux(void) 19587 { 19588 /* Pairs with the smp_store_release() on the parse path below. */ 19589 struct btf *btf = smp_load_acquire(&btf_vmlinux); 19590 19591 if (!btf && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 19592 mutex_lock(&btf_vmlinux_lock); 19593 btf = btf_vmlinux; 19594 if (!btf) { 19595 btf = btf_parse_vmlinux(); 19596 /* 19597 * Order the parsed BTF contents and the globals the 19598 * parse populated (e.g. bpf_ctx_convert.t) before 19599 * the pointer publication. Pairs with the acquire 19600 * on the lockless fast path above. 19601 */ 19602 smp_store_release(&btf_vmlinux, btf); 19603 } 19604 mutex_unlock(&btf_vmlinux_lock); 19605 } 19606 return btf; 19607 } 19608 19609 /* 19610 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 19611 * this case expect that every file descriptor in the array is either a map or 19612 * a BTF. Everything else is considered to be trash. 19613 */ 19614 static int add_fd_from_fd_array(struct bpf_verifier_env *env, u32 idx, int fd) 19615 { 19616 struct bpf_map *map; 19617 struct btf *btf; 19618 CLASS(fd, f)(fd); 19619 int err; 19620 19621 map = __bpf_map_get(f); 19622 if (!IS_ERR(map)) { 19623 err = __add_used_map(env, map); 19624 if (err < 0) 19625 return err; 19626 fd_slot_set_map(&env->fd_array[idx], map); 19627 return 0; 19628 } 19629 19630 btf = __btf_get_by_fd(f); 19631 if (!IS_ERR(btf)) { 19632 btf_get(btf); 19633 err = __add_used_btf(env, btf); 19634 if (err < 0) 19635 return err; 19636 fd_slot_set_btf(&env->fd_array[idx], btf); 19637 return 0; 19638 } 19639 19640 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 19641 return PTR_ERR(map); 19642 } 19643 19644 /* 19645 * A continuous fd_array is resolved into an in-memory cache with one slot 19646 * per entry. The bound here is deliberately generous and not derived from 19647 * the per-program object limits: Duplicate entries /are/ permitted, and 19648 * the number of distinct maps and BTFs a program can bind is enforced when 19649 * each entry is resolved by __add_used_map() and __add_used_btf(). 19650 */ 19651 #define MAX_FD_ARRAY_CNT 4096 19652 19653 static int process_fd_array_continuous(struct bpf_verifier_env *env, 19654 bpfptr_t fd_array, u32 cnt) 19655 { 19656 int fd, ret; 19657 u32 i; 19658 19659 if (cnt > MAX_FD_ARRAY_CNT) { 19660 verbose(env, "fd_array has too many entries (%u, max %u)\n", 19661 cnt, MAX_FD_ARRAY_CNT); 19662 return -E2BIG; 19663 } 19664 19665 env->fd_array = kvcalloc(cnt, sizeof(*env->fd_array), 19666 GFP_KERNEL_ACCOUNT); 19667 if (!env->fd_array) 19668 return -ENOMEM; 19669 env->fd_array_cnt = cnt; 19670 for (i = 0; i < cnt; i++) { 19671 if (copy_from_bpfptr_offset(&fd, fd_array, 19672 (size_t)i * sizeof(fd), sizeof(fd))) 19673 return -EFAULT; 19674 ret = add_fd_from_fd_array(env, i, fd); 19675 if (ret) 19676 return ret; 19677 } 19678 return 0; 19679 } 19680 19681 static int process_fd_array(struct bpf_verifier_env *env, 19682 union bpf_attr *attr, bpfptr_t uattr) 19683 { 19684 bpfptr_t fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 19685 19686 if (bpfptr_is_null(fd_array)) { 19687 if (attr->fd_array_cnt) { 19688 verbose(env, "fd_array_cnt %u without fd_array is invalid\n", 19689 attr->fd_array_cnt); 19690 return -EINVAL; 19691 } 19692 return 0; 19693 } 19694 /* 19695 * New API: the caller passes fd_array_cnt and a continuous array that 19696 * is resolved and bound up front. Legacy API (no fd_array_cnt): keep 19697 * the caller's array and resolve entries on the spot at each reference. 19698 */ 19699 if (attr->fd_array_cnt) 19700 return process_fd_array_continuous(env, fd_array, 19701 attr->fd_array_cnt); 19702 env->fd_array_raw = fd_array; 19703 return 0; 19704 } 19705 19706 /* replace a generic kfunc with a specialized version if necessary */ 19707 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx) 19708 { 19709 struct bpf_prog *prog = env->prog; 19710 bool seen_direct_write; 19711 void *xdp_kfunc; 19712 bool is_rdonly; 19713 u32 func_id = desc->func_id; 19714 u16 offset = desc->offset; 19715 unsigned long addr = desc->addr; 19716 19717 if (offset) /* return if module BTF is used */ 19718 return 0; 19719 19720 if (bpf_dev_bound_kfunc_id(func_id)) { 19721 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19722 if (xdp_kfunc) 19723 addr = (unsigned long)xdp_kfunc; 19724 /* fallback to default kfunc when not supported by netdev */ 19725 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19726 seen_direct_write = env->seen_direct_write; 19727 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19728 19729 if (is_rdonly) 19730 addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19731 19732 /* restore env->seen_direct_write to its original value, since 19733 * may_access_direct_pkt_data mutates it 19734 */ 19735 env->seen_direct_write = seen_direct_write; 19736 } else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) { 19737 if (bpf_lsm_has_d_inode_locked(prog)) 19738 addr = (unsigned long)bpf_set_dentry_xattr_locked; 19739 } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) { 19740 if (bpf_lsm_has_d_inode_locked(prog)) 19741 addr = (unsigned long)bpf_remove_dentry_xattr_locked; 19742 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 19743 if (!env->insn_aux_data[insn_idx].non_sleepable) 19744 addr = (unsigned long)bpf_dynptr_from_file_sleepable; 19745 } else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) { 19746 if (env->insn_aux_data[insn_idx].non_sleepable) 19747 addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable; 19748 } else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) { 19749 if (env->insn_aux_data[insn_idx].non_sleepable) 19750 addr = (unsigned long)bpf_arena_free_pages_non_sleepable; 19751 } 19752 desc->addr = addr; 19753 return 0; 19754 } 19755 19756 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19757 u16 struct_meta_reg, 19758 u16 node_offset_reg, 19759 struct bpf_insn *insn, 19760 struct bpf_insn *insn_buf, 19761 int *cnt) 19762 { 19763 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19764 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19765 19766 insn_buf[0] = addr[0]; 19767 insn_buf[1] = addr[1]; 19768 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19769 insn_buf[3] = *insn; 19770 *cnt = 4; 19771 } 19772 19773 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19774 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19775 { 19776 struct bpf_kfunc_desc *desc; 19777 int err; 19778 19779 if (!insn->imm) { 19780 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19781 return -EINVAL; 19782 } 19783 19784 *cnt = 0; 19785 19786 /* insn->imm has the btf func_id. Replace it with an offset relative to 19787 * __bpf_call_base, unless the JIT needs to call functions that are 19788 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19789 */ 19790 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19791 if (!desc) { 19792 verifier_bug(env, "kernel function descriptor not found for func_id %u", 19793 insn->imm); 19794 return -EFAULT; 19795 } 19796 19797 err = specialize_kfunc(env, desc, insn_idx); 19798 if (err) 19799 return err; 19800 19801 if (!bpf_jit_supports_far_kfunc_call()) 19802 insn->imm = BPF_CALL_IMM(desc->addr); 19803 19804 if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) { 19805 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19806 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19807 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19808 19809 if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) { 19810 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19811 insn_idx); 19812 return -EFAULT; 19813 } 19814 19815 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19816 insn_buf[1] = addr[0]; 19817 insn_buf[2] = addr[1]; 19818 insn_buf[3] = *insn; 19819 *cnt = 4; 19820 } else if (is_bpf_obj_drop_kfunc(desc->func_id) || 19821 is_bpf_percpu_obj_drop_kfunc(desc->func_id) || 19822 is_bpf_refcount_acquire_kfunc(desc->func_id)) { 19823 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19824 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19825 19826 if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) { 19827 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19828 insn_idx); 19829 return -EFAULT; 19830 } 19831 19832 if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) { 19833 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19834 insn_idx); 19835 return -EFAULT; 19836 } 19837 19838 insn_buf[0] = addr[0]; 19839 insn_buf[1] = addr[1]; 19840 insn_buf[2] = *insn; 19841 *cnt = 3; 19842 } else if (is_bpf_list_push_kfunc(desc->func_id) || 19843 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19844 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19845 int struct_meta_reg = BPF_REG_3; 19846 int node_offset_reg = BPF_REG_4; 19847 19848 /* list_add/rbtree_add have an extra arg (prev/less), 19849 * so args-to-fixup are in diff regs. 19850 */ 19851 if (desc->func_id == special_kfunc_list[KF_bpf_list_add] || 19852 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19853 struct_meta_reg = BPF_REG_4; 19854 node_offset_reg = BPF_REG_5; 19855 } 19856 19857 if (!kptr_struct_meta) { 19858 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19859 insn_idx); 19860 return -EFAULT; 19861 } 19862 19863 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19864 node_offset_reg, insn, insn_buf, cnt); 19865 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19866 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19867 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19868 *cnt = 1; 19869 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] && 19870 (env->prog->expected_attach_type == BPF_TRACE_FSESSION || 19871 env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19872 19873 /* 19874 * inline the bpf_session_is_return() for fsession: 19875 * bool bpf_session_is_return(void *ctx) 19876 * { 19877 * return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1; 19878 * } 19879 */ 19880 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19881 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT); 19882 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1); 19883 *cnt = 3; 19884 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] && 19885 (env->prog->expected_attach_type == BPF_TRACE_FSESSION || 19886 env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19887 /* 19888 * inline bpf_session_cookie() for fsession: 19889 * __u64 *bpf_session_cookie(void *ctx) 19890 * { 19891 * u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF; 19892 * return &((u64 *)ctx)[-off]; 19893 * } 19894 */ 19895 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19896 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT); 19897 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF); 19898 insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19899 insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1); 19900 insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0); 19901 *cnt = 6; 19902 } 19903 19904 if (env->insn_aux_data[insn_idx].arg_prog) { 19905 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 19906 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 19907 int idx = *cnt; 19908 19909 insn_buf[idx++] = ld_addrs[0]; 19910 insn_buf[idx++] = ld_addrs[1]; 19911 insn_buf[idx++] = *insn; 19912 *cnt = idx; 19913 } 19914 return 0; 19915 } 19916 19917 static enum bpf_sig_keyring bpf_classify_keyring(s32 keyring_id) 19918 { 19919 switch (keyring_id) { 19920 case 0: 19921 return BPF_SIG_KEYRING_BUILTIN; 19922 case (s32)(unsigned long)VERIFY_USE_SECONDARY_KEYRING: 19923 return BPF_SIG_KEYRING_SECONDARY; 19924 case (s32)(unsigned long)VERIFY_USE_PLATFORM_KEYRING: 19925 return BPF_SIG_KEYRING_PLATFORM; 19926 default: 19927 return BPF_SIG_KEYRING_USER; 19928 } 19929 } 19930 19931 /* 19932 * Verify the PKCS#7 signature of a loaded program. Called from bpf_check() 19933 * once the program's metadata maps have been resolved into used_maps, so 19934 * the exact maps folded into the signature are the ones the program binds. 19935 * 19936 * The signature covers the instructions followed by the frozen contents of 19937 * each map, in @maps order: insns || map_0 || map_1 || [...]. On success the 19938 * verdict and keyring info are recorded on prog->aux. 19939 */ 19940 static int bpf_prog_verify_signature(struct bpf_verifier_env *env, 19941 union bpf_attr *attr, bool is_kernel) 19942 { 19943 bpfptr_t usig = make_bpfptr(attr->signature, is_kernel); 19944 struct bpf_dynptr_kern sig_ptr, data_ptr; 19945 struct bpf_prog *prog = env->prog; 19946 struct bpf_map **maps = env->used_maps; 19947 struct bpf_key *key = NULL; 19948 void *sig, *data = NULL; 19949 u32 map_cnt = env->used_map_cnt; 19950 u32 i, off, insns_sz; 19951 u64 data_sz; 19952 int err = 0; 19953 19954 /* 19955 * Don't attempt to use kmalloc_large or vmalloc for signatures. 19956 * Practical signature for BPF program should be below this limit. 19957 */ 19958 if (!attr->signature_size || 19959 attr->signature_size > KMALLOC_MAX_CACHE_SIZE) 19960 return -EINVAL; 19961 if (system_keyring_id_check(attr->keyring_id) == 0) 19962 key = bpf_lookup_system_key(attr->keyring_id); 19963 else 19964 key = bpf_lookup_user_key(attr->keyring_id, 0); 19965 if (!key) { 19966 verbose(env, "cannot resolve signing keyring with keyring_id %d\n", 19967 attr->keyring_id); 19968 return -EINVAL; 19969 } 19970 19971 sig = kvmemdup_bpfptr(usig, attr->signature_size); 19972 if (IS_ERR(sig)) { 19973 bpf_key_put(key); 19974 return PTR_ERR(sig); 19975 } 19976 19977 insns_sz = prog->len * sizeof(struct bpf_insn); 19978 data_sz = insns_sz; 19979 for (i = 0; i < map_cnt; i++) { 19980 struct bpf_map *map = maps[i]; 19981 19982 if (map->map_type != BPF_MAP_TYPE_ARRAY || 19983 !map->ops->map_direct_value_addr) { 19984 verbose(env, "signed program metadata map '%s' must be an array\n", 19985 map->name); 19986 err = -EINVAL; 19987 goto out; 19988 } 19989 if (!READ_ONCE(map->frozen)) { 19990 verbose(env, "signed program metadata map '%s' must be frozen\n", 19991 map->name); 19992 err = -EPERM; 19993 goto out; 19994 } 19995 if (bpf_map_write_active(map)) { 19996 verbose(env, "signed program metadata map '%s' has active writers\n", 19997 map->name); 19998 err = -EBUSY; 19999 goto out; 20000 } 20001 if (!map->excl_prog_sha) { 20002 verbose(env, "signed program metadata map '%s' must be exclusive\n", 20003 map->name); 20004 err = -EPERM; 20005 goto out; 20006 } 20007 data_sz += map->value_size; 20008 } 20009 if (bpf_dynptr_check_size(data_sz)) { 20010 verbose(env, "signed payload too large: %llu bytes\n", data_sz); 20011 err = -E2BIG; 20012 goto out; 20013 } 20014 data = kvmalloc(data_sz, GFP_KERNEL_ACCOUNT | __GFP_ZERO); 20015 if (!data) { 20016 err = -ENOMEM; 20017 goto out; 20018 } 20019 memcpy(data, prog->insnsi, insns_sz); 20020 off = insns_sz; 20021 for (i = 0; i < map_cnt; i++) { 20022 struct bpf_map *map = maps[i]; 20023 u64 addr; 20024 20025 err = map->ops->map_direct_value_addr(map, &addr, 0); 20026 if (err) { 20027 verbose(env, "failed to read signed metadata map '%s': %d\n", 20028 map->name, err); 20029 goto out; 20030 } 20031 memcpy(data + off, (void *)(unsigned long)addr, 20032 map->value_size); 20033 off += map->value_size; 20034 } 20035 20036 bpf_dynptr_init(&data_ptr, data, BPF_DYNPTR_TYPE_LOCAL, 0, data_sz); 20037 bpf_dynptr_init(&sig_ptr, sig, BPF_DYNPTR_TYPE_LOCAL, 0, 20038 attr->signature_size); 20039 20040 err = bpf_verify_pkcs7_signature((struct bpf_dynptr *)&data_ptr, 20041 (struct bpf_dynptr *)&sig_ptr, key); 20042 if (err) { 20043 verbose(env, "signature verification failed: %d\n", err); 20044 } else { 20045 verbose(env, "signature verification passed\n"); 20046 prog->aux->sig.keyring_serial = bpf_key_serial(key); 20047 prog->aux->sig.keyring_type = bpf_classify_keyring(attr->keyring_id); 20048 prog->aux->sig.verdict = BPF_SIG_VERIFIED; 20049 } 20050 out: 20051 kvfree(data); 20052 bpf_key_put(key); 20053 kvfree(sig); 20054 return err; 20055 } 20056 20057 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, 20058 struct bpf_log_attr *attr_log) 20059 { 20060 u64 start_time = ktime_get_ns(); 20061 struct bpf_verifier_env *env; 20062 int i, len, ret = -EINVAL, err; 20063 bool is_priv; 20064 20065 BTF_TYPE_EMIT(enum bpf_features); 20066 20067 /* no program is valid */ 20068 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 20069 return -EINVAL; 20070 20071 /* 'struct bpf_verifier_env' can be global, but since it's not small, 20072 * allocate/free it every time bpf_check() is called 20073 */ 20074 env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT); 20075 if (!env) 20076 return -ENOMEM; 20077 20078 env->bt.env = env; 20079 env->prog = *prog; 20080 env->ops = bpf_verifier_ops[env->prog->type]; 20081 20082 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 20083 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 20084 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 20085 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 20086 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 20087 env->signature = attr->signature; 20088 20089 /* user could have requested verbose verifier output 20090 * and supplied buffer to store the verification trace 20091 */ 20092 ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size); 20093 if (ret) 20094 goto err_free_env; 20095 if (env->signature) { 20096 ret = bpf_prog_calc_tag(env->prog); 20097 if (ret < 0) 20098 goto err_prep; 20099 } 20100 20101 ret = process_fd_array(env, attr, uattr); 20102 if (ret) 20103 goto err_prep; 20104 20105 if (env->signature) { 20106 ret = bpf_prog_verify_signature(env, attr, uattr.is_kernel); 20107 if (ret) 20108 goto err_prep; 20109 } 20110 20111 ret = security_bpf_prog_load(env->prog, attr, env->prog->aux->token, 20112 uattr.is_kernel); 20113 if (ret) 20114 goto err_prep; 20115 20116 bpf_get_btf_vmlinux(); 20117 20118 /* Serialize verification of unprivileged programs. */ 20119 if (!is_priv) 20120 mutex_lock(&bpf_verifier_lock); 20121 20122 len = env->prog->len; 20123 env->insn_aux_data = 20124 __vmalloc(array_size(sizeof(struct bpf_insn_aux_data), len), 20125 GFP_KERNEL_ACCOUNT | __GFP_ZERO); 20126 ret = -ENOMEM; 20127 if (!env->insn_aux_data) 20128 goto skip_full_check; 20129 for (i = 0; i < len; i++) 20130 env->insn_aux_data[i].orig_idx = i; 20131 env->succ = bpf_iarray_realloc(NULL, 2); 20132 if (!env->succ) 20133 goto skip_full_check; 20134 20135 mark_verifier_state_clean(env); 20136 20137 if (IS_ERR(btf_vmlinux)) { 20138 /* Either gcc or pahole or kernel are broken. */ 20139 verbose(env, "in-kernel BTF is malformed\n"); 20140 ret = PTR_ERR(btf_vmlinux); 20141 goto skip_full_check; 20142 } 20143 20144 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 20145 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 20146 env->strict_alignment = true; 20147 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 20148 env->strict_alignment = false; 20149 20150 if (is_priv) 20151 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 20152 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 20153 20154 env->explored_states = kvzalloc_objs(struct list_head, 20155 state_htab_size(env), 20156 GFP_KERNEL_ACCOUNT); 20157 ret = -ENOMEM; 20158 if (!env->explored_states) 20159 goto skip_full_check; 20160 20161 for (i = 0; i < state_htab_size(env); i++) 20162 INIT_LIST_HEAD(&env->explored_states[i]); 20163 INIT_LIST_HEAD(&env->free_list); 20164 20165 ret = bpf_check_btf_info_early(env, attr, uattr); 20166 if (ret < 0) 20167 goto skip_full_check; 20168 20169 ret = add_subprog_and_kfunc(env); 20170 if (ret < 0) 20171 goto skip_full_check; 20172 20173 ret = check_subprogs(env); 20174 if (ret < 0) 20175 goto skip_full_check; 20176 20177 ret = bpf_check_btf_info(env, attr, uattr); 20178 if (ret < 0) 20179 goto skip_full_check; 20180 20181 ret = check_and_resolve_insns(env); 20182 if (ret < 0) 20183 goto skip_full_check; 20184 20185 if (bpf_prog_is_offloaded(env->prog->aux)) { 20186 ret = bpf_prog_offload_verifier_prep(env->prog); 20187 if (ret) 20188 goto skip_full_check; 20189 } 20190 20191 ret = bpf_check_cfg(env); 20192 if (ret < 0) 20193 goto skip_full_check; 20194 20195 ret = bpf_compute_postorder(env); 20196 if (ret < 0) 20197 goto skip_full_check; 20198 20199 ret = bpf_stack_liveness_init(env); 20200 if (ret) 20201 goto skip_full_check; 20202 20203 ret = check_attach_btf_id(env); 20204 if (ret) 20205 goto skip_full_check; 20206 20207 ret = bpf_compute_const_regs(env); 20208 if (ret < 0) 20209 goto skip_full_check; 20210 20211 ret = bpf_prune_dead_branches(env); 20212 if (ret < 0) 20213 goto skip_full_check; 20214 20215 ret = sort_subprogs_topo(env); 20216 if (ret < 0) 20217 goto skip_full_check; 20218 20219 ret = bpf_compute_scc(env); 20220 if (ret < 0) 20221 goto skip_full_check; 20222 20223 ret = bpf_compute_live_registers(env); 20224 if (ret < 0) 20225 goto skip_full_check; 20226 20227 ret = mark_fastcall_patterns(env); 20228 if (ret < 0) 20229 goto skip_full_check; 20230 20231 ret = do_check_main(env); 20232 ret = ret ?: do_check_subprogs(env); 20233 20234 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20235 ret = bpf_prog_offload_finalize(env); 20236 20237 skip_full_check: 20238 kvfree(env->explored_states); 20239 20240 /* might decrease stack depth, keep it before passes that 20241 * allocate additional slots. 20242 */ 20243 if (ret == 0) 20244 ret = bpf_remove_fastcall_spills_fills(env); 20245 20246 if (ret == 0) 20247 ret = check_max_stack_depth(env); 20248 20249 /* instruction rewrites happen after this point */ 20250 if (ret == 0) 20251 ret = bpf_optimize_bpf_loop(env); 20252 20253 if (is_priv) { 20254 if (ret == 0) 20255 bpf_opt_hard_wire_dead_code_branches(env); 20256 if (ret == 0) 20257 ret = bpf_opt_remove_dead_code(env); 20258 if (ret == 0) 20259 ret = bpf_opt_remove_nops(env); 20260 } else { 20261 if (ret == 0) 20262 sanitize_dead_code(env); 20263 } 20264 20265 if (ret == 0) 20266 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20267 ret = bpf_convert_ctx_accesses(env); 20268 20269 if (ret == 0) 20270 ret = bpf_do_misc_fixups(env); 20271 20272 /* do 32-bit optimization after insn patching has done so those patched 20273 * insns could be handled correctly. 20274 */ 20275 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20276 ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr); 20277 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20278 : false; 20279 } 20280 20281 if (ret == 0) 20282 ret = bpf_fixup_call_args(env); 20283 20284 env->verification_time = ktime_get_ns() - start_time; 20285 print_verification_stats(env); 20286 env->prog->aux->verified_insns = env->insn_processed; 20287 20288 /* preserve original error even if log finalization is successful */ 20289 err = bpf_log_attr_finalize(attr_log, &env->log); 20290 if (err) 20291 ret = err; 20292 20293 if (ret) 20294 goto err_release_maps; 20295 20296 if (env->used_map_cnt) { 20297 /* if program passed verifier, update used_maps in bpf_prog_info */ 20298 env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0], 20299 env->used_map_cnt, 20300 GFP_KERNEL_ACCOUNT); 20301 20302 if (!env->prog->aux->used_maps) { 20303 ret = -ENOMEM; 20304 goto err_release_maps; 20305 } 20306 20307 memcpy(env->prog->aux->used_maps, env->used_maps, 20308 sizeof(env->used_maps[0]) * env->used_map_cnt); 20309 env->prog->aux->used_map_cnt = env->used_map_cnt; 20310 } 20311 if (env->used_btf_cnt) { 20312 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20313 env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0], 20314 env->used_btf_cnt, 20315 GFP_KERNEL_ACCOUNT); 20316 if (!env->prog->aux->used_btfs) { 20317 ret = -ENOMEM; 20318 goto err_release_maps; 20319 } 20320 20321 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20322 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20323 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20324 } 20325 if (env->used_map_cnt || env->used_btf_cnt) { 20326 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20327 * bpf_ld_imm64 instructions 20328 */ 20329 convert_pseudo_ld_imm64(env); 20330 } 20331 20332 adjust_btf_func(env); 20333 20334 /* extension progs temporarily inherit the attach_type of their targets 20335 for verification purposes, so set it back to zero before returning 20336 */ 20337 if (env->prog->type == BPF_PROG_TYPE_EXT) 20338 env->prog->expected_attach_type = 0; 20339 20340 env->prog = __bpf_prog_select_runtime(env, env->prog, &ret); 20341 20342 err_release_maps: 20343 if (ret) 20344 release_insn_arrays(env); 20345 if (!env->prog->aux->used_maps) 20346 /* if we didn't copy map pointers into bpf_prog_info, release 20347 * them now. Otherwise free_used_maps() will release them. 20348 */ 20349 release_maps(env); 20350 if (!env->prog->aux->used_btfs) 20351 release_btfs(env); 20352 20353 *prog = env->prog; 20354 20355 module_put(env->attach_btf_mod); 20356 if (!is_priv) 20357 mutex_unlock(&bpf_verifier_lock); 20358 goto err_free_env; 20359 err_prep: 20360 err = bpf_log_attr_finalize(attr_log, &env->log); 20361 if (err) 20362 ret = err; 20363 release_insn_arrays(env); 20364 release_maps(env); 20365 release_btfs(env); 20366 err_free_env: 20367 if (env->insn_aux_data) 20368 bpf_clear_insn_aux_data(env, 0, env->prog->len); 20369 vfree(env->insn_aux_data); 20370 kvfree(env->fd_array); 20371 bpf_stack_liveness_free(env); 20372 kvfree(env->cfg.insn_postorder); 20373 kvfree(env->scc_info); 20374 kvfree(env->succ); 20375 kvfree(env->gotox_tmp_buf); 20376 kvfree(env); 20377 return ret; 20378 } 20379