1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 3 * Copyright (c) 2016 Facebook 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io 5 */ 6 #include <uapi/linux/btf.h> 7 #include <linux/bpf-cgroup.h> 8 #include <linux/kernel.h> 9 #include <linux/types.h> 10 #include <linux/slab.h> 11 #include <linux/bpf.h> 12 #include <linux/btf.h> 13 #include <linux/bpf_verifier.h> 14 #include <linux/filter.h> 15 #include <net/netlink.h> 16 #include <linux/file.h> 17 #include <linux/vmalloc.h> 18 #include <linux/stringify.h> 19 #include <linux/bsearch.h> 20 #include <linux/sort.h> 21 #include <linux/perf_event.h> 22 #include <linux/ctype.h> 23 #include <linux/error-injection.h> 24 #include <linux/bpf_lsm.h> 25 #include <linux/btf_ids.h> 26 #include <linux/poison.h> 27 #include <linux/module.h> 28 #include <linux/cpumask.h> 29 #include <linux/cnum.h> 30 #include <linux/bpf_mem_alloc.h> 31 #include <net/xdp.h> 32 #include <linux/trace_events.h> 33 #include <linux/kallsyms.h> 34 35 #include "disasm.h" 36 37 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 38 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 39 [_id] = & _name ## _verifier_ops, 40 #define BPF_MAP_TYPE(_id, _ops) 41 #define BPF_LINK_TYPE(_id, _name) 42 #include <linux/bpf_types.h> 43 #undef BPF_PROG_TYPE 44 #undef BPF_MAP_TYPE 45 #undef BPF_LINK_TYPE 46 }; 47 48 enum bpf_features { 49 BPF_FEAT_RDONLY_CAST_TO_VOID = 0, 50 BPF_FEAT_STREAMS = 1, 51 __MAX_BPF_FEAT, 52 }; 53 54 struct bpf_mem_alloc bpf_global_percpu_ma; 55 static bool bpf_global_percpu_ma_set; 56 57 /* bpf_check() is a static code analyzer that walks eBPF program 58 * instruction by instruction and updates register/stack state. 59 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 60 * 61 * The first pass is depth-first-search to check that the program is a DAG. 62 * It rejects the following programs: 63 * - larger than BPF_MAXINSNS insns 64 * - if loop is present (detected via back-edge) 65 * - unreachable insns exist (shouldn't be a forest. program = one function) 66 * - out of bounds or malformed jumps 67 * The second pass is all possible path descent from the 1st insn. 68 * Since it's analyzing all paths through the program, the length of the 69 * analysis is limited to 64k insn, which may be hit even if total number of 70 * insn is less then 4K, but there are too many branches that change stack/regs. 71 * Number of 'branches to be analyzed' is limited to 1k 72 * 73 * On entry to each instruction, each register has a type, and the instruction 74 * changes the types of the registers depending on instruction semantics. 75 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 76 * copied to R1. 77 * 78 * All registers are 64-bit. 79 * R0 - return register 80 * R1-R5 argument passing registers 81 * R6-R9 callee saved registers 82 * R10 - frame pointer read-only 83 * 84 * At the start of BPF program the register R1 contains a pointer to bpf_context 85 * and has type PTR_TO_CTX. 86 * 87 * Verifier tracks arithmetic operations on pointers in case: 88 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 89 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 90 * 1st insn copies R10 (which has FRAME_PTR) type into R1 91 * and 2nd arithmetic instruction is pattern matched to recognize 92 * that it wants to construct a pointer to some element within stack. 93 * So after 2nd insn, the register R1 has type PTR_TO_STACK 94 * (and -20 constant is saved for further stack bounds checking). 95 * Meaning that this reg is a pointer to stack plus known immediate constant. 96 * 97 * Most of the time the registers have SCALAR_VALUE type, which 98 * means the register has some value, but it's not a valid pointer. 99 * (like pointer plus pointer becomes SCALAR_VALUE type) 100 * 101 * When verifier sees load or store instructions the type of base register 102 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 103 * four pointer types recognized by check_mem_access() function. 104 * 105 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 106 * and the range of [ptr, ptr + map's value_size) is accessible. 107 * 108 * registers used to pass values to function calls are checked against 109 * function argument constraints. 110 * 111 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 112 * It means that the register type passed to this function must be 113 * PTR_TO_STACK and it will be used inside the function as 114 * 'pointer to map element key' 115 * 116 * For example the argument constraints for bpf_map_lookup_elem(): 117 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 118 * .arg1_type = ARG_CONST_MAP_PTR, 119 * .arg2_type = ARG_PTR_TO_MAP_KEY, 120 * 121 * ret_type says that this function returns 'pointer to map elem value or null' 122 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 123 * 2nd argument should be a pointer to stack, which will be used inside 124 * the helper function as a pointer to map element key. 125 * 126 * On the kernel side the helper function looks like: 127 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 128 * { 129 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 130 * void *key = (void *) (unsigned long) r2; 131 * void *value; 132 * 133 * here kernel can access 'key' and 'map' pointers safely, knowing that 134 * [key, key + map->key_size) bytes are valid and were initialized on 135 * the stack of eBPF program. 136 * } 137 * 138 * Corresponding eBPF program may look like: 139 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 140 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 141 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 142 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 143 * here verifier looks at prototype of map_lookup_elem() and sees: 144 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 145 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 146 * 147 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 148 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 149 * and were initialized prior to this call. 150 * If it's ok, then verifier allows this BPF_CALL insn and looks at 151 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 152 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 153 * returns either pointer to map value or NULL. 154 * 155 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 156 * insn, the register holding that pointer in the true branch changes state to 157 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 158 * branch. See check_cond_jmp_op(). 159 * 160 * After the call R0 is set to return type of the function and registers R1-R5 161 * are set to NOT_INIT to indicate that they are no longer readable. 162 * 163 * The following reference types represent a potential reference to a kernel 164 * resource which, after first being allocated, must be checked and freed by 165 * the BPF program: 166 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 167 * 168 * When the verifier sees a helper call return a reference type, it allocates a 169 * pointer id for the reference and stores it in the current function state. 170 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 171 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 172 * passes through a NULL-check conditional. For the branch wherein the state is 173 * changed to CONST_IMM, the verifier releases the reference. 174 * 175 * For each helper function that allocates a reference, such as 176 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 177 * bpf_sk_release(). When a reference type passes into the release function, 178 * the verifier also releases the reference. If any unchecked or unreleased 179 * reference remains at the end of the program, the verifier rejects it. 180 */ 181 182 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 183 struct bpf_verifier_stack_elem { 184 /* verifier state is 'st' 185 * before processing instruction 'insn_idx' 186 * and after processing instruction 'prev_insn_idx' 187 */ 188 struct bpf_verifier_state st; 189 int insn_idx; 190 int prev_insn_idx; 191 struct bpf_verifier_stack_elem *next; 192 /* length of verifier log at the time this state was pushed on stack */ 193 u32 log_pos; 194 }; 195 196 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 197 #define BPF_COMPLEXITY_LIMIT_STATES 64 198 199 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 200 201 #define BPF_PRIV_STACK_MIN_SIZE 64 202 203 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id); 204 static int release_reference_nomark(struct bpf_verifier_state *state, int id); 205 static int release_reference(struct bpf_verifier_env *env, int id); 206 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 207 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 208 static bool is_tracing_prog_type(enum bpf_prog_type type); 209 static int ref_set_non_owning(struct bpf_verifier_env *env, 210 struct bpf_reg_state *reg); 211 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg); 212 static inline bool in_sleepable_context(struct bpf_verifier_env *env); 213 static const char *non_sleepable_context_description(struct bpf_verifier_env *env); 214 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 215 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 216 217 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 218 struct bpf_map *map, 219 bool unpriv, bool poison) 220 { 221 unpriv |= bpf_map_ptr_unpriv(aux); 222 aux->map_ptr_state.unpriv = unpriv; 223 aux->map_ptr_state.poison = poison; 224 aux->map_ptr_state.map_ptr = map; 225 } 226 227 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 228 { 229 bool poisoned = bpf_map_key_poisoned(aux); 230 231 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 232 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 233 } 234 235 static void update_ref_obj(struct ref_obj_desc *ref_obj, struct bpf_reg_state *reg) 236 { 237 ref_obj->id = reg->id; 238 ref_obj->parent_id = reg->parent_id; 239 ref_obj->cnt++; 240 } 241 242 static int validate_ref_obj(struct bpf_verifier_env *env, struct ref_obj_desc *ref_obj) 243 { 244 if (ref_obj->cnt > 1) { 245 verifier_bug(env, "function expects only one referenced object but got %d\n", 246 ref_obj->cnt); 247 return -EFAULT; 248 } 249 250 return 0; 251 } 252 253 struct bpf_call_arg_meta { 254 struct bpf_map_desc map; 255 struct bpf_dynptr_desc dynptr; 256 struct ref_obj_desc ref_obj; 257 bool raw_mode; 258 bool pkt_access; 259 u8 release_regno; 260 int regno; 261 int access_size; 262 int mem_size; 263 u64 msize_max_value; 264 int func_id; 265 struct btf *btf; 266 u32 btf_id; 267 struct btf *ret_btf; 268 u32 ret_btf_id; 269 u32 subprogno; 270 struct btf_field *kptr_field; 271 s64 const_map_key; 272 }; 273 274 struct bpf_kfunc_meta { 275 struct btf *btf; 276 const struct btf_type *proto; 277 const char *name; 278 const u32 *flags; 279 s32 id; 280 }; 281 282 struct btf *btf_vmlinux; 283 284 typedef struct argno { 285 int argno; 286 } argno_t; 287 288 static argno_t argno_from_reg(u32 regno) 289 { 290 return (argno_t){ .argno = regno }; 291 } 292 293 static argno_t argno_from_arg(u32 arg) 294 { 295 return (argno_t){ .argno = -arg }; 296 } 297 298 static int reg_from_argno(argno_t a) 299 { 300 if (a.argno >= 0) 301 return a.argno; 302 if (a.argno >= -MAX_BPF_FUNC_REG_ARGS) 303 return -a.argno; 304 return -1; 305 } 306 307 static int arg_from_argno(argno_t a) 308 { 309 if (a.argno < 0) 310 return -a.argno; 311 return -1; 312 } 313 314 static int arg_idx_from_argno(argno_t a) 315 { 316 return arg_from_argno(a) - 1; 317 } 318 319 static const char *btf_type_name(const struct btf *btf, u32 id) 320 { 321 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 322 } 323 324 static DEFINE_MUTEX(bpf_verifier_lock); 325 static DEFINE_MUTEX(bpf_percpu_ma_lock); 326 327 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 328 { 329 struct bpf_verifier_env *env = private_data; 330 va_list args; 331 332 if (!bpf_verifier_log_needed(&env->log)) 333 return; 334 335 va_start(args, fmt); 336 bpf_verifier_vlog(&env->log, fmt, args); 337 va_end(args); 338 } 339 340 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 341 struct bpf_reg_state *reg, 342 struct bpf_retval_range range, const char *ctx, 343 const char *reg_name) 344 { 345 bool unknown = true; 346 347 verbose(env, "%s the register %s has", ctx, reg_name); 348 if (reg_smin(reg) > S64_MIN) { 349 verbose(env, " smin=%lld", reg_smin(reg)); 350 unknown = false; 351 } 352 if (reg_smax(reg) < S64_MAX) { 353 verbose(env, " smax=%lld", reg_smax(reg)); 354 unknown = false; 355 } 356 if (unknown) 357 verbose(env, " unknown scalar value"); 358 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 359 } 360 361 static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 362 { 363 enum bpf_reg_type type; 364 365 type = reg->type; 366 if (type_may_be_null(type)) 367 return false; 368 369 type = base_type(type); 370 return type == PTR_TO_SOCKET || 371 type == PTR_TO_TCP_SOCK || 372 type == PTR_TO_MAP_VALUE || 373 type == PTR_TO_MAP_KEY || 374 type == PTR_TO_SOCK_COMMON || 375 (type == PTR_TO_BTF_ID && is_trusted_reg(env, reg)) || 376 (type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) || 377 type == CONST_PTR_TO_MAP; 378 } 379 380 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 381 { 382 struct btf_record *rec = NULL; 383 struct btf_struct_meta *meta; 384 385 if (reg->type == PTR_TO_MAP_VALUE) { 386 rec = reg->map_ptr->record; 387 } else if (type_is_ptr_alloc_obj(reg->type)) { 388 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 389 if (meta) 390 rec = meta->record; 391 } 392 return rec; 393 } 394 395 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog) 396 { 397 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 398 399 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 400 } 401 402 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog) 403 { 404 const struct btf_type *type, *func, *func_proto; 405 const struct btf *btf = env->prog->aux->btf; 406 u32 btf_id; 407 408 btf_id = env->prog->aux->func_info[subprog].type_id; 409 410 func = btf_type_by_id(btf, btf_id); 411 if (verifier_bug_if(!func, env, "btf_id %u not found", btf_id)) 412 return false; 413 414 func_proto = btf_type_by_id(btf, func->type); 415 if (!func_proto) 416 return false; 417 418 type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 419 if (!type) 420 return false; 421 422 return btf_type_is_void(type); 423 } 424 425 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 426 { 427 struct bpf_func_info *info; 428 429 if (!env->prog->aux->func_info) 430 return ""; 431 432 info = &env->prog->aux->func_info[subprog]; 433 return btf_type_name(env->prog->aux->btf, info->type_id); 434 } 435 436 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 437 { 438 struct bpf_subprog_info *info = subprog_info(env, subprog); 439 440 info->is_cb = true; 441 info->is_async_cb = true; 442 info->is_exception_cb = true; 443 } 444 445 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 446 { 447 return subprog_info(env, subprog)->is_exception_cb; 448 } 449 450 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 451 { 452 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK); 453 } 454 455 static bool type_is_rdonly_mem(u32 type) 456 { 457 return type & MEM_RDONLY; 458 } 459 460 static bool is_acquire_function(enum bpf_func_id func_id, 461 const struct bpf_map *map) 462 { 463 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 464 465 if (func_id == BPF_FUNC_sk_lookup_tcp || 466 func_id == BPF_FUNC_sk_lookup_udp || 467 func_id == BPF_FUNC_skc_lookup_tcp || 468 func_id == BPF_FUNC_ringbuf_reserve || 469 func_id == BPF_FUNC_kptr_xchg) 470 return true; 471 472 if (func_id == BPF_FUNC_map_lookup_elem && 473 (map_type == BPF_MAP_TYPE_SOCKMAP || 474 map_type == BPF_MAP_TYPE_SOCKHASH)) 475 return true; 476 477 return false; 478 } 479 480 static bool is_ptr_cast_function(enum bpf_func_id func_id) 481 { 482 return func_id == BPF_FUNC_tcp_sock || 483 func_id == BPF_FUNC_sk_fullsock || 484 func_id == BPF_FUNC_skc_to_tcp_sock || 485 func_id == BPF_FUNC_skc_to_tcp6_sock || 486 func_id == BPF_FUNC_skc_to_udp6_sock || 487 func_id == BPF_FUNC_skc_to_mptcp_sock || 488 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 489 func_id == BPF_FUNC_skc_to_tcp_request_sock; 490 } 491 492 static bool is_sync_callback_calling_kfunc(u32 btf_id); 493 static bool is_async_callback_calling_kfunc(u32 btf_id); 494 static bool is_callback_calling_kfunc(u32 btf_id); 495 496 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id); 497 static bool is_task_work_add_kfunc(u32 func_id); 498 499 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 500 { 501 return func_id == BPF_FUNC_for_each_map_elem || 502 func_id == BPF_FUNC_find_vma || 503 func_id == BPF_FUNC_loop || 504 func_id == BPF_FUNC_user_ringbuf_drain; 505 } 506 507 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 508 { 509 return func_id == BPF_FUNC_timer_set_callback; 510 } 511 512 static bool is_callback_calling_function(enum bpf_func_id func_id) 513 { 514 return is_sync_callback_calling_function(func_id) || 515 is_async_callback_calling_function(func_id); 516 } 517 518 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn) 519 { 520 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 521 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 522 } 523 524 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn) 525 { 526 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 527 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 528 } 529 530 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn) 531 { 532 /* bpf_timer callbacks are never sleepable. */ 533 if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback) 534 return false; 535 536 /* bpf_wq and bpf_task_work callbacks are always sleepable. */ 537 if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 538 (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm))) 539 return true; 540 541 verifier_bug(env, "unhandled async callback in is_async_cb_sleepable"); 542 return false; 543 } 544 545 bool bpf_is_may_goto_insn(struct bpf_insn *insn) 546 { 547 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 548 } 549 550 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 551 { 552 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 553 554 /* We need to check that slots between [spi - nr_slots + 1, spi] are 555 * within [0, allocated_stack). 556 * 557 * Please note that the spi grows downwards. For example, a dynptr 558 * takes the size of two stack slots; the first slot will be at 559 * spi and the second slot will be at spi - 1. 560 */ 561 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 562 } 563 564 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 565 const char *obj_kind, int nr_slots) 566 { 567 int off, spi; 568 569 if (!tnum_is_const(reg->var_off)) { 570 verbose(env, "%s has to be at a constant offset\n", obj_kind); 571 return -EINVAL; 572 } 573 574 off = reg->var_off.value; 575 if (off % BPF_REG_SIZE) { 576 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 577 return -EINVAL; 578 } 579 580 spi = bpf_get_spi(off); 581 if (spi + 1 < nr_slots) { 582 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 583 return -EINVAL; 584 } 585 586 if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots)) 587 return -ERANGE; 588 return spi; 589 } 590 591 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 592 { 593 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 594 } 595 596 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 597 { 598 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 599 } 600 601 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 602 { 603 return stack_slot_obj_get_spi(env, reg, "irq_flag", 1); 604 } 605 606 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 607 { 608 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 609 case DYNPTR_TYPE_LOCAL: 610 return BPF_DYNPTR_TYPE_LOCAL; 611 case DYNPTR_TYPE_RINGBUF: 612 return BPF_DYNPTR_TYPE_RINGBUF; 613 case DYNPTR_TYPE_SKB: 614 return BPF_DYNPTR_TYPE_SKB; 615 case DYNPTR_TYPE_XDP: 616 return BPF_DYNPTR_TYPE_XDP; 617 case DYNPTR_TYPE_SKB_META: 618 return BPF_DYNPTR_TYPE_SKB_META; 619 case DYNPTR_TYPE_FILE: 620 return BPF_DYNPTR_TYPE_FILE; 621 default: 622 return BPF_DYNPTR_TYPE_INVALID; 623 } 624 } 625 626 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 627 { 628 switch (type) { 629 case BPF_DYNPTR_TYPE_LOCAL: 630 return DYNPTR_TYPE_LOCAL; 631 case BPF_DYNPTR_TYPE_RINGBUF: 632 return DYNPTR_TYPE_RINGBUF; 633 case BPF_DYNPTR_TYPE_SKB: 634 return DYNPTR_TYPE_SKB; 635 case BPF_DYNPTR_TYPE_XDP: 636 return DYNPTR_TYPE_XDP; 637 case BPF_DYNPTR_TYPE_SKB_META: 638 return DYNPTR_TYPE_SKB_META; 639 case BPF_DYNPTR_TYPE_FILE: 640 return DYNPTR_TYPE_FILE; 641 default: 642 return 0; 643 } 644 } 645 646 static bool dynptr_type_referenced(enum bpf_dynptr_type type) 647 { 648 return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE; 649 } 650 651 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 652 enum bpf_dynptr_type type, 653 bool first_slot, int id, int parent_id); 654 655 656 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 657 struct bpf_reg_state *sreg1, 658 struct bpf_reg_state *sreg2, 659 enum bpf_dynptr_type type, int parent_id) 660 { 661 int id = ++env->id_gen; 662 663 __mark_dynptr_reg(sreg1, type, true, id, parent_id); 664 __mark_dynptr_reg(sreg2, type, false, id, parent_id); 665 } 666 667 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 668 struct bpf_reg_state *reg, 669 enum bpf_dynptr_type type) 670 { 671 __mark_dynptr_reg(reg, type, true, ++env->id_gen, 0); 672 } 673 674 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 675 struct bpf_func_state *state, int spi); 676 677 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 678 enum bpf_arg_type arg_type, int insn_idx, 679 struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr) 680 { 681 struct bpf_func_state *state = bpf_func(env, reg); 682 int spi, i, err, parent_id = 0; 683 enum bpf_dynptr_type type; 684 685 spi = dynptr_get_spi(env, reg); 686 if (spi < 0) 687 return spi; 688 689 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 690 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 691 * to ensure that for the following example: 692 * [d1][d1][d2][d2] 693 * spi 3 2 1 0 694 * So marking spi = 2 should lead to destruction of both d1 and d2. In 695 * case they do belong to same dynptr, second call won't see slot_type 696 * as STACK_DYNPTR and will simply skip destruction. 697 */ 698 err = destroy_if_dynptr_stack_slot(env, state, spi); 699 if (err) 700 return err; 701 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 702 if (err) 703 return err; 704 705 for (i = 0; i < BPF_REG_SIZE; i++) { 706 state->stack[spi].slot_type[i] = STACK_DYNPTR; 707 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 708 } 709 710 type = arg_to_dynptr_type(arg_type); 711 if (type == BPF_DYNPTR_TYPE_INVALID) 712 return -EINVAL; 713 714 if (dynptr->type == BPF_DYNPTR_TYPE_INVALID) { /* dynptr constructors */ 715 err = validate_ref_obj(env, ref_obj); 716 if (err) 717 return err; 718 719 /* Track parent's id if the parent is a referenced object */ 720 parent_id = ref_obj->id; 721 722 if (dynptr_type_referenced(type)) { 723 int id; 724 725 /* 726 * Create an intermediate reference that tracks the referenced 727 * object for the referenced dynptr. Freeing a referenced dynptr 728 * through helpers/kfuncs will invalidate all clones. 729 */ 730 id = acquire_reference(env, insn_idx, parent_id); 731 if (id < 0) 732 return id; 733 734 parent_id = id; 735 } 736 } else { /* bpf_dynptr_clone() */ 737 parent_id = dynptr->parent_id; 738 } 739 740 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 741 &state->stack[spi - 1].spilled_ptr, type, parent_id); 742 743 return 0; 744 } 745 746 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_stack_state *stack) 747 { 748 int i; 749 750 for (i = 0; i < BPF_REG_SIZE; i++) { 751 stack[0].slot_type[i] = STACK_INVALID; 752 stack[1].slot_type[i] = STACK_INVALID; 753 } 754 755 bpf_mark_reg_not_init(env, &stack[0].spilled_ptr); 756 bpf_mark_reg_not_init(env, &stack[1].spilled_ptr); 757 } 758 759 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 760 { 761 struct bpf_func_state *state = bpf_func(env, reg); 762 int spi; 763 764 spi = dynptr_get_spi(env, reg); 765 if (spi < 0) 766 return spi; 767 768 /* 769 * For referenced dynptr, release the parent ref which cascades to 770 * all clones and derived slices. For non-referenced dynptr, only 771 * the dynptr and slices derived from it will be invalidated. 772 */ 773 reg = &state->stack[spi].spilled_ptr; 774 return release_reference(env, dynptr_type_referenced(reg->dynptr.type) 775 ? reg->parent_id 776 : reg->id); 777 } 778 779 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 780 struct bpf_reg_state *reg); 781 782 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 783 { 784 if (!env->allow_ptr_leaks) 785 bpf_mark_reg_not_init(env, reg); 786 else 787 __mark_reg_unknown(env, reg); 788 } 789 790 static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id) 791 { 792 struct bpf_stack_state *stack; 793 struct bpf_func_state *state; 794 struct bpf_reg_state *reg; 795 int ref_cnt = 0; 796 797 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({ 798 if (!stack || stack->slot_type[0] != STACK_DYNPTR) 799 continue; 800 if (!stack->spilled_ptr.dynptr.first_slot) 801 continue; 802 if (stack->spilled_ptr.parent_id == v_parent_id) 803 ref_cnt++; 804 })); 805 806 return ref_cnt; 807 } 808 809 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 810 struct bpf_func_state *state, int spi) 811 { 812 int err = 0; 813 814 /* We always ensure that STACK_DYNPTR is never set partially, 815 * hence just checking for slot_type[0] is enough. This is 816 * different for STACK_SPILL, where it may be only set for 817 * 1 byte, so code has to use is_spilled_reg. 818 */ 819 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 820 return 0; 821 822 /* Reposition spi to first slot */ 823 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 824 spi = spi + 1; 825 826 /* 827 * A referenced dynptr can be overwritten only if there is at 828 * least one other dynptr sharing the same virtual ref parent, 829 * ensuring the reference can still be properly released. 830 */ 831 if (dynptr_type_referenced(state->stack[spi].spilled_ptr.dynptr.type) && 832 dynptr_ref_cnt(env, state->stack[spi].spilled_ptr.parent_id) <= 1) { 833 verbose(env, "cannot overwrite referenced dynptr\n"); 834 return -EINVAL; 835 } 836 837 /* Invalidate the dynptr and any derived slices */ 838 err = release_reference(env, state->stack[spi].spilled_ptr.id); 839 if (!err) { 840 mark_stack_slot_scratched(env, spi); 841 mark_stack_slot_scratched(env, spi - 1); 842 } 843 844 return err; 845 } 846 847 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 848 { 849 int spi; 850 851 if (reg->type == CONST_PTR_TO_DYNPTR) 852 return false; 853 854 spi = dynptr_get_spi(env, reg); 855 856 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 857 * error because this just means the stack state hasn't been updated yet. 858 * We will do check_mem_access to check and update stack bounds later. 859 */ 860 if (spi < 0 && spi != -ERANGE) 861 return false; 862 863 /* We don't need to check if the stack slots are marked by previous 864 * dynptr initializations because we allow overwriting existing unreferenced 865 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 866 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 867 * touching are completely destructed before we reinitialize them for a new 868 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 869 * instead of delaying it until the end where the user will get "Unreleased 870 * reference" error. 871 */ 872 return true; 873 } 874 875 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 876 { 877 struct bpf_func_state *state = bpf_func(env, reg); 878 int i, spi; 879 880 /* This already represents first slot of initialized bpf_dynptr. 881 * 882 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 883 * check_func_arg_reg_off's logic, so we don't need to check its 884 * offset and alignment. 885 */ 886 if (reg->type == CONST_PTR_TO_DYNPTR) 887 return true; 888 889 spi = dynptr_get_spi(env, reg); 890 if (spi < 0) 891 return false; 892 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 893 return false; 894 895 for (i = 0; i < BPF_REG_SIZE; i++) { 896 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 897 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 898 return false; 899 } 900 901 return true; 902 } 903 904 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 905 enum bpf_arg_type arg_type) 906 { 907 struct bpf_func_state *state = bpf_func(env, reg); 908 enum bpf_dynptr_type dynptr_type; 909 int spi; 910 911 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 912 if (arg_type == ARG_PTR_TO_DYNPTR) 913 return true; 914 915 dynptr_type = arg_to_dynptr_type(arg_type); 916 if (reg->type == CONST_PTR_TO_DYNPTR) { 917 return reg->dynptr.type == dynptr_type; 918 } else { 919 spi = dynptr_get_spi(env, reg); 920 if (spi < 0) 921 return false; 922 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 923 } 924 } 925 926 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 927 928 static bool in_rcu_cs(struct bpf_verifier_env *env); 929 930 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 931 932 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 933 struct bpf_kfunc_call_arg_meta *meta, 934 struct bpf_reg_state *reg, int insn_idx, 935 struct btf *btf, u32 btf_id, int nr_slots) 936 { 937 struct bpf_func_state *state = bpf_func(env, reg); 938 int spi, i, j, id; 939 940 spi = iter_get_spi(env, reg, nr_slots); 941 if (spi < 0) 942 return spi; 943 944 id = acquire_reference(env, insn_idx, 0); 945 if (id < 0) 946 return id; 947 948 for (i = 0; i < nr_slots; i++) { 949 struct bpf_stack_state *slot = &state->stack[spi - i]; 950 struct bpf_reg_state *st = &slot->spilled_ptr; 951 952 __mark_reg_known_zero(st); 953 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 954 if (is_kfunc_rcu_protected(meta)) { 955 if (in_rcu_cs(env)) 956 st->type |= MEM_RCU; 957 else 958 st->type |= PTR_UNTRUSTED; 959 } 960 st->id = i == 0 ? id : 0; 961 st->iter.btf = btf; 962 st->iter.btf_id = btf_id; 963 st->iter.state = BPF_ITER_STATE_ACTIVE; 964 st->iter.depth = 0; 965 966 for (j = 0; j < BPF_REG_SIZE; j++) 967 slot->slot_type[j] = STACK_ITER; 968 969 mark_stack_slot_scratched(env, spi - i); 970 } 971 972 return 0; 973 } 974 975 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 976 struct bpf_reg_state *reg, int nr_slots) 977 { 978 struct bpf_func_state *state = bpf_func(env, reg); 979 int spi, i, j; 980 981 spi = iter_get_spi(env, reg, nr_slots); 982 if (spi < 0) 983 return spi; 984 985 for (i = 0; i < nr_slots; i++) { 986 struct bpf_stack_state *slot = &state->stack[spi - i]; 987 struct bpf_reg_state *st = &slot->spilled_ptr; 988 989 if (i == 0) 990 WARN_ON_ONCE(release_reference(env, st->id)); 991 992 bpf_mark_reg_not_init(env, st); 993 994 for (j = 0; j < BPF_REG_SIZE; j++) 995 slot->slot_type[j] = STACK_INVALID; 996 997 mark_stack_slot_scratched(env, spi - i); 998 } 999 1000 return 0; 1001 } 1002 1003 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1004 struct bpf_reg_state *reg, int nr_slots) 1005 { 1006 struct bpf_func_state *state = bpf_func(env, reg); 1007 int spi, i, j; 1008 1009 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1010 * will do check_mem_access to check and update stack bounds later, so 1011 * return true for that case. 1012 */ 1013 spi = iter_get_spi(env, reg, nr_slots); 1014 if (spi == -ERANGE) 1015 return true; 1016 if (spi < 0) 1017 return false; 1018 1019 for (i = 0; i < nr_slots; i++) { 1020 struct bpf_stack_state *slot = &state->stack[spi - i]; 1021 1022 for (j = 0; j < BPF_REG_SIZE; j++) 1023 if (slot->slot_type[j] == STACK_ITER) 1024 return false; 1025 } 1026 1027 return true; 1028 } 1029 1030 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1031 struct btf *btf, u32 btf_id, int nr_slots) 1032 { 1033 struct bpf_func_state *state = bpf_func(env, reg); 1034 int spi, i, j; 1035 1036 spi = iter_get_spi(env, reg, nr_slots); 1037 if (spi < 0) 1038 return -EINVAL; 1039 1040 for (i = 0; i < nr_slots; i++) { 1041 struct bpf_stack_state *slot = &state->stack[spi - i]; 1042 struct bpf_reg_state *st = &slot->spilled_ptr; 1043 1044 if (st->type & PTR_UNTRUSTED) 1045 return -EPROTO; 1046 /* only main (first) slot has id set */ 1047 if (i == 0 && !st->id) 1048 return -EINVAL; 1049 if (i != 0 && st->id) 1050 return -EINVAL; 1051 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1052 return -EINVAL; 1053 1054 for (j = 0; j < BPF_REG_SIZE; j++) 1055 if (slot->slot_type[j] != STACK_ITER) 1056 return -EINVAL; 1057 } 1058 1059 return 0; 1060 } 1061 1062 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx); 1063 static int release_irq_state(struct bpf_verifier_state *state, int id); 1064 1065 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env, 1066 struct bpf_kfunc_call_arg_meta *meta, 1067 struct bpf_reg_state *reg, int insn_idx, 1068 int kfunc_class) 1069 { 1070 struct bpf_func_state *state = bpf_func(env, reg); 1071 struct bpf_stack_state *slot; 1072 struct bpf_reg_state *st; 1073 int spi, i, id; 1074 1075 spi = irq_flag_get_spi(env, reg); 1076 if (spi < 0) 1077 return spi; 1078 1079 id = acquire_irq_state(env, insn_idx); 1080 if (id < 0) 1081 return id; 1082 1083 slot = &state->stack[spi]; 1084 st = &slot->spilled_ptr; 1085 1086 __mark_reg_known_zero(st); 1087 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1088 st->id = id; 1089 st->irq.kfunc_class = kfunc_class; 1090 1091 for (i = 0; i < BPF_REG_SIZE; i++) 1092 slot->slot_type[i] = STACK_IRQ_FLAG; 1093 1094 mark_stack_slot_scratched(env, spi); 1095 return 0; 1096 } 1097 1098 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1099 int kfunc_class) 1100 { 1101 struct bpf_func_state *state = bpf_func(env, reg); 1102 struct bpf_stack_state *slot; 1103 struct bpf_reg_state *st; 1104 int spi, i, err; 1105 1106 spi = irq_flag_get_spi(env, reg); 1107 if (spi < 0) 1108 return spi; 1109 1110 slot = &state->stack[spi]; 1111 st = &slot->spilled_ptr; 1112 1113 if (st->irq.kfunc_class != kfunc_class) { 1114 const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1115 const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1116 1117 verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n", 1118 flag_kfunc, used_kfunc); 1119 return -EINVAL; 1120 } 1121 1122 err = release_irq_state(env->cur_state, st->id); 1123 WARN_ON_ONCE(err && err != -EACCES); 1124 if (err) { 1125 int insn_idx = 0; 1126 1127 for (int i = 0; i < env->cur_state->acquired_refs; i++) { 1128 if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) { 1129 insn_idx = env->cur_state->refs[i].insn_idx; 1130 break; 1131 } 1132 } 1133 1134 verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n", 1135 env->cur_state->active_irq_id, insn_idx); 1136 return err; 1137 } 1138 1139 bpf_mark_reg_not_init(env, st); 1140 1141 for (i = 0; i < BPF_REG_SIZE; i++) 1142 slot->slot_type[i] = STACK_INVALID; 1143 1144 mark_stack_slot_scratched(env, spi); 1145 return 0; 1146 } 1147 1148 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1149 { 1150 struct bpf_func_state *state = bpf_func(env, reg); 1151 struct bpf_stack_state *slot; 1152 int spi, i; 1153 1154 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1155 * will do check_mem_access to check and update stack bounds later, so 1156 * return true for that case. 1157 */ 1158 spi = irq_flag_get_spi(env, reg); 1159 if (spi == -ERANGE) 1160 return true; 1161 if (spi < 0) 1162 return false; 1163 1164 slot = &state->stack[spi]; 1165 1166 for (i = 0; i < BPF_REG_SIZE; i++) 1167 if (slot->slot_type[i] == STACK_IRQ_FLAG) 1168 return false; 1169 return true; 1170 } 1171 1172 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1173 { 1174 struct bpf_func_state *state = bpf_func(env, reg); 1175 struct bpf_stack_state *slot; 1176 struct bpf_reg_state *st; 1177 int spi, i; 1178 1179 spi = irq_flag_get_spi(env, reg); 1180 if (spi < 0) 1181 return -EINVAL; 1182 1183 slot = &state->stack[spi]; 1184 st = &slot->spilled_ptr; 1185 1186 if (!st->id) 1187 return -EINVAL; 1188 1189 for (i = 0; i < BPF_REG_SIZE; i++) 1190 if (slot->slot_type[i] != STACK_IRQ_FLAG) 1191 return -EINVAL; 1192 return 0; 1193 } 1194 1195 /* Check if given stack slot is "special": 1196 * - spilled register state (STACK_SPILL); 1197 * - dynptr state (STACK_DYNPTR); 1198 * - iter state (STACK_ITER). 1199 * - irq flag state (STACK_IRQ_FLAG) 1200 */ 1201 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1202 { 1203 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1204 1205 switch (type) { 1206 case STACK_SPILL: 1207 case STACK_DYNPTR: 1208 case STACK_ITER: 1209 case STACK_IRQ_FLAG: 1210 return true; 1211 case STACK_INVALID: 1212 case STACK_POISON: 1213 case STACK_MISC: 1214 case STACK_ZERO: 1215 return false; 1216 default: 1217 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1218 return true; 1219 } 1220 } 1221 1222 /* The reg state of a pointer or a bounded scalar was saved when 1223 * it was spilled to the stack. 1224 */ 1225 1226 /* 1227 * Mark stack slot as STACK_MISC, unless it is already: 1228 * - STACK_INVALID, in which case they are equivalent. 1229 * - STACK_ZERO, in which case we preserve more precise STACK_ZERO. 1230 * - STACK_POISON, which truly forbids access to the slot. 1231 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged 1232 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is 1233 * unnecessary as both are considered equivalent when loading data and pruning, 1234 * in case of unprivileged mode it will be incorrect to allow reads of invalid 1235 * slots. 1236 */ 1237 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1238 { 1239 if (*stype == STACK_ZERO) 1240 return; 1241 if (*stype == STACK_INVALID || *stype == STACK_POISON) 1242 return; 1243 *stype = STACK_MISC; 1244 } 1245 1246 static void scrub_spilled_slot(u8 *stype) 1247 { 1248 if (*stype != STACK_INVALID && *stype != STACK_POISON) 1249 *stype = STACK_MISC; 1250 } 1251 1252 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1253 * small to hold src. This is different from krealloc since we don't want to preserve 1254 * the contents of dst. 1255 * 1256 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1257 * not be allocated. 1258 */ 1259 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1260 { 1261 size_t alloc_bytes; 1262 void *orig = dst; 1263 size_t bytes; 1264 1265 if (ZERO_OR_NULL_PTR(src)) 1266 goto out; 1267 1268 if (unlikely(check_mul_overflow(n, size, &bytes))) 1269 return NULL; 1270 1271 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1272 dst = krealloc(orig, alloc_bytes, flags); 1273 if (!dst) { 1274 kfree(orig); 1275 return NULL; 1276 } 1277 1278 memcpy(dst, src, bytes); 1279 out: 1280 return dst ? dst : ZERO_SIZE_PTR; 1281 } 1282 1283 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1284 * small to hold new_n items. new items are zeroed out if the array grows. 1285 * 1286 * Contrary to krealloc_array, does not free arr if new_n is zero. 1287 */ 1288 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1289 { 1290 size_t alloc_size; 1291 void *new_arr; 1292 1293 if (!new_n || old_n == new_n) 1294 goto out; 1295 1296 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1297 new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT); 1298 if (!new_arr) { 1299 kfree(arr); 1300 return NULL; 1301 } 1302 arr = new_arr; 1303 1304 if (new_n > old_n) 1305 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1306 1307 out: 1308 return arr ? arr : ZERO_SIZE_PTR; 1309 } 1310 1311 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) 1312 { 1313 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1314 sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT); 1315 if (!dst->refs) 1316 return -ENOMEM; 1317 1318 dst->acquired_refs = src->acquired_refs; 1319 dst->active_locks = src->active_locks; 1320 dst->active_preempt_locks = src->active_preempt_locks; 1321 dst->active_rcu_locks = src->active_rcu_locks; 1322 dst->active_irq_id = src->active_irq_id; 1323 dst->active_lock_id = src->active_lock_id; 1324 dst->active_lock_ptr = src->active_lock_ptr; 1325 return 0; 1326 } 1327 1328 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1329 { 1330 size_t n = src->allocated_stack / BPF_REG_SIZE; 1331 1332 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1333 GFP_KERNEL_ACCOUNT); 1334 if (!dst->stack) 1335 return -ENOMEM; 1336 1337 dst->allocated_stack = src->allocated_stack; 1338 1339 /* copy stack args state */ 1340 n = src->out_stack_arg_cnt; 1341 if (n) { 1342 dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n, 1343 sizeof(struct bpf_reg_state), 1344 GFP_KERNEL_ACCOUNT); 1345 if (!dst->stack_arg_regs) 1346 return -ENOMEM; 1347 } 1348 1349 dst->out_stack_arg_cnt = src->out_stack_arg_cnt; 1350 return 0; 1351 } 1352 1353 static int resize_reference_state(struct bpf_verifier_state *state, size_t n) 1354 { 1355 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1356 sizeof(struct bpf_reference_state)); 1357 if (!state->refs) 1358 return -ENOMEM; 1359 1360 state->acquired_refs = n; 1361 return 0; 1362 } 1363 1364 /* Possibly update state->allocated_stack to be at least size bytes. Also 1365 * possibly update the function's high-water mark in its bpf_subprog_info. 1366 */ 1367 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1368 { 1369 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1370 1371 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1372 size = round_up(size, BPF_REG_SIZE); 1373 n = size / BPF_REG_SIZE; 1374 1375 if (old_n >= n) 1376 return 0; 1377 1378 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1379 if (!state->stack) 1380 return -ENOMEM; 1381 1382 state->allocated_stack = size; 1383 1384 /* update known max for given subprogram */ 1385 if (env->subprog_info[state->subprogno].stack_depth < size) 1386 env->subprog_info[state->subprogno].stack_depth = size; 1387 1388 return 0; 1389 } 1390 1391 static int grow_stack_arg_slots(struct bpf_verifier_env *env, 1392 struct bpf_func_state *state, int cnt) 1393 { 1394 size_t old_n = state->out_stack_arg_cnt; 1395 1396 if (old_n >= cnt) 1397 return 0; 1398 1399 state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt, 1400 sizeof(struct bpf_reg_state)); 1401 if (!state->stack_arg_regs) 1402 return -ENOMEM; 1403 1404 state->out_stack_arg_cnt = cnt; 1405 return 0; 1406 } 1407 1408 /* Acquire a pointer id from the env and update the state->refs to include 1409 * this new pointer reference. 1410 * On success, returns a valid pointer id to associate with the register 1411 * On failure, returns a negative errno. 1412 */ 1413 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1414 { 1415 struct bpf_verifier_state *state = env->cur_state; 1416 int new_ofs = state->acquired_refs; 1417 int err; 1418 1419 err = resize_reference_state(state, state->acquired_refs + 1); 1420 if (err) 1421 return NULL; 1422 state->refs[new_ofs].insn_idx = insn_idx; 1423 1424 return &state->refs[new_ofs]; 1425 } 1426 1427 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id) 1428 { 1429 struct bpf_reference_state *s; 1430 1431 s = acquire_reference_state(env, insn_idx); 1432 if (!s) 1433 return -ENOMEM; 1434 s->type = REF_TYPE_PTR; 1435 s->id = ++env->id_gen; 1436 s->parent_id = parent_id; 1437 return s->id; 1438 } 1439 1440 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type, 1441 int id, void *ptr) 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 = type; 1450 s->id = id; 1451 s->ptr = ptr; 1452 1453 state->active_locks++; 1454 state->active_lock_id = id; 1455 state->active_lock_ptr = ptr; 1456 return 0; 1457 } 1458 1459 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx) 1460 { 1461 struct bpf_verifier_state *state = env->cur_state; 1462 struct bpf_reference_state *s; 1463 1464 s = acquire_reference_state(env, insn_idx); 1465 if (!s) 1466 return -ENOMEM; 1467 s->type = REF_TYPE_IRQ; 1468 s->id = ++env->id_gen; 1469 1470 state->active_irq_id = s->id; 1471 return s->id; 1472 } 1473 1474 static void release_reference_state(struct bpf_verifier_state *state, int idx) 1475 { 1476 int last_idx; 1477 size_t rem; 1478 1479 /* IRQ state requires the relative ordering of elements remaining the 1480 * same, since it relies on the refs array to behave as a stack, so that 1481 * it can detect out-of-order IRQ restore. Hence use memmove to shift 1482 * the array instead of swapping the final element into the deleted idx. 1483 */ 1484 last_idx = state->acquired_refs - 1; 1485 rem = state->acquired_refs - idx - 1; 1486 if (last_idx && idx != last_idx) 1487 memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem); 1488 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1489 state->acquired_refs--; 1490 return; 1491 } 1492 1493 static bool find_reference_state(struct bpf_verifier_state *state, int id) 1494 { 1495 int i; 1496 1497 for (i = 0; i < state->acquired_refs; i++) { 1498 if (state->refs[i].type != REF_TYPE_PTR) 1499 continue; 1500 if (state->refs[i].id == id) 1501 return true; 1502 } 1503 1504 return false; 1505 } 1506 1507 static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 1508 { 1509 return find_reference_state(env->cur_state, reg->id); 1510 } 1511 1512 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr) 1513 { 1514 void *prev_ptr = NULL; 1515 u32 prev_id = 0; 1516 int i; 1517 1518 for (i = 0; i < state->acquired_refs; i++) { 1519 if (state->refs[i].type == type && state->refs[i].id == id && 1520 state->refs[i].ptr == ptr) { 1521 release_reference_state(state, i); 1522 state->active_locks--; 1523 /* Reassign active lock (id, ptr). */ 1524 state->active_lock_id = prev_id; 1525 state->active_lock_ptr = prev_ptr; 1526 return 0; 1527 } 1528 if (state->refs[i].type & REF_TYPE_LOCK_MASK) { 1529 prev_id = state->refs[i].id; 1530 prev_ptr = state->refs[i].ptr; 1531 } 1532 } 1533 return -EINVAL; 1534 } 1535 1536 static int release_irq_state(struct bpf_verifier_state *state, int id) 1537 { 1538 u32 prev_id = 0; 1539 int i; 1540 1541 if (id != state->active_irq_id) 1542 return -EACCES; 1543 1544 for (i = 0; i < state->acquired_refs; i++) { 1545 if (state->refs[i].type != REF_TYPE_IRQ) 1546 continue; 1547 if (state->refs[i].id == id) { 1548 release_reference_state(state, i); 1549 state->active_irq_id = prev_id; 1550 return 0; 1551 } else { 1552 prev_id = state->refs[i].id; 1553 } 1554 } 1555 return -EINVAL; 1556 } 1557 1558 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type, 1559 int id, void *ptr) 1560 { 1561 int i; 1562 1563 for (i = 0; i < state->acquired_refs; i++) { 1564 struct bpf_reference_state *s = &state->refs[i]; 1565 1566 if (!(s->type & type)) 1567 continue; 1568 1569 if (s->id == id && s->ptr == ptr) 1570 return s; 1571 } 1572 return NULL; 1573 } 1574 1575 static void free_func_state(struct bpf_func_state *state) 1576 { 1577 if (!state) 1578 return; 1579 kfree(state->stack_arg_regs); 1580 kfree(state->stack); 1581 kfree(state); 1582 } 1583 1584 void bpf_clear_jmp_history(struct bpf_verifier_state *state) 1585 { 1586 kfree(state->jmp_history); 1587 state->jmp_history = NULL; 1588 state->jmp_history_cnt = 0; 1589 } 1590 1591 void bpf_free_verifier_state(struct bpf_verifier_state *state, 1592 bool free_self) 1593 { 1594 int i; 1595 1596 for (i = 0; i <= state->curframe; i++) { 1597 free_func_state(state->frame[i]); 1598 state->frame[i] = NULL; 1599 } 1600 kfree(state->refs); 1601 bpf_clear_jmp_history(state); 1602 if (free_self) 1603 kfree(state); 1604 } 1605 1606 /* copy verifier state from src to dst growing dst stack space 1607 * when necessary to accommodate larger src stack 1608 */ 1609 static int copy_func_state(struct bpf_func_state *dst, 1610 const struct bpf_func_state *src) 1611 { 1612 memcpy(dst, src, offsetof(struct bpf_func_state, stack)); 1613 return copy_stack_state(dst, src); 1614 } 1615 1616 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state, 1617 const struct bpf_verifier_state *src) 1618 { 1619 struct bpf_func_state *dst; 1620 int i, err; 1621 1622 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1623 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1624 GFP_KERNEL_ACCOUNT); 1625 if (!dst_state->jmp_history) 1626 return -ENOMEM; 1627 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1628 1629 /* if dst has more stack frames then src frame, free them, this is also 1630 * necessary in case of exceptional exits using bpf_throw. 1631 */ 1632 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1633 free_func_state(dst_state->frame[i]); 1634 dst_state->frame[i] = NULL; 1635 } 1636 err = copy_reference_state(dst_state, src); 1637 if (err) 1638 return err; 1639 dst_state->speculative = src->speculative; 1640 dst_state->in_sleepable = src->in_sleepable; 1641 dst_state->curframe = src->curframe; 1642 dst_state->branches = src->branches; 1643 dst_state->parent = src->parent; 1644 dst_state->first_insn_idx = src->first_insn_idx; 1645 dst_state->last_insn_idx = src->last_insn_idx; 1646 dst_state->dfs_depth = src->dfs_depth; 1647 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1648 dst_state->may_goto_depth = src->may_goto_depth; 1649 dst_state->equal_state = src->equal_state; 1650 for (i = 0; i <= src->curframe; i++) { 1651 dst = dst_state->frame[i]; 1652 if (!dst) { 1653 dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT); 1654 if (!dst) 1655 return -ENOMEM; 1656 dst_state->frame[i] = dst; 1657 } 1658 err = copy_func_state(dst, src->frame[i]); 1659 if (err) 1660 return err; 1661 } 1662 return 0; 1663 } 1664 1665 static u32 state_htab_size(struct bpf_verifier_env *env) 1666 { 1667 return env->prog->len; 1668 } 1669 1670 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx) 1671 { 1672 struct bpf_verifier_state *cur = env->cur_state; 1673 struct bpf_func_state *state = cur->frame[cur->curframe]; 1674 1675 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1676 } 1677 1678 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1679 { 1680 int fr; 1681 1682 if (a->curframe != b->curframe) 1683 return false; 1684 1685 for (fr = a->curframe; fr >= 0; fr--) 1686 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1687 return false; 1688 1689 return true; 1690 } 1691 1692 1693 void bpf_free_backedges(struct bpf_scc_visit *visit) 1694 { 1695 struct bpf_scc_backedge *backedge, *next; 1696 1697 for (backedge = visit->backedges; backedge; backedge = next) { 1698 bpf_free_verifier_state(&backedge->state, false); 1699 next = backedge->next; 1700 kfree(backedge); 1701 } 1702 visit->backedges = NULL; 1703 } 1704 1705 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1706 int *insn_idx, bool pop_log) 1707 { 1708 struct bpf_verifier_state *cur = env->cur_state; 1709 struct bpf_verifier_stack_elem *elem, *head = env->head; 1710 int err; 1711 1712 if (env->head == NULL) 1713 return -ENOENT; 1714 1715 if (cur) { 1716 err = bpf_copy_verifier_state(cur, &head->st); 1717 if (err) 1718 return err; 1719 } 1720 if (pop_log) 1721 bpf_vlog_reset(&env->log, head->log_pos); 1722 if (insn_idx) 1723 *insn_idx = head->insn_idx; 1724 if (prev_insn_idx) 1725 *prev_insn_idx = head->prev_insn_idx; 1726 elem = head->next; 1727 bpf_free_verifier_state(&head->st, false); 1728 kfree(head); 1729 env->head = elem; 1730 env->stack_size--; 1731 return 0; 1732 } 1733 1734 static bool error_recoverable_with_nospec(int err) 1735 { 1736 /* Should only return true for non-fatal errors that are allowed to 1737 * occur during speculative verification. For these we can insert a 1738 * nospec and the program might still be accepted. Do not include 1739 * something like ENOMEM because it is likely to re-occur for the next 1740 * architectural path once it has been recovered-from in all speculative 1741 * paths. 1742 */ 1743 return err == -EPERM || err == -EACCES || err == -EINVAL; 1744 } 1745 1746 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1747 int insn_idx, int prev_insn_idx, 1748 bool speculative) 1749 { 1750 struct bpf_verifier_state *cur = env->cur_state; 1751 struct bpf_verifier_stack_elem *elem; 1752 int err; 1753 1754 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 1755 if (!elem) 1756 return ERR_PTR(-ENOMEM); 1757 1758 elem->insn_idx = insn_idx; 1759 elem->prev_insn_idx = prev_insn_idx; 1760 elem->next = env->head; 1761 elem->log_pos = env->log.end_pos; 1762 env->head = elem; 1763 env->stack_size++; 1764 err = bpf_copy_verifier_state(&elem->st, cur); 1765 if (err) 1766 return ERR_PTR(-ENOMEM); 1767 elem->st.speculative |= speculative; 1768 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1769 verbose(env, "The sequence of %d jumps is too complex.\n", 1770 env->stack_size); 1771 return ERR_PTR(-E2BIG); 1772 } 1773 if (elem->st.parent) { 1774 ++elem->st.parent->branches; 1775 /* WARN_ON(branches > 2) technically makes sense here, 1776 * but 1777 * 1. speculative states will bump 'branches' for non-branch 1778 * instructions 1779 * 2. is_state_visited() heuristics may decide not to create 1780 * a new state for a sequence of branches and all such current 1781 * and cloned states will be pointing to a single parent state 1782 * which might have large 'branches' count. 1783 */ 1784 } 1785 return &elem->st; 1786 } 1787 1788 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno) 1789 { 1790 char *buf = env->tmp_arg_name; 1791 int len = sizeof(env->tmp_arg_name); 1792 int arg, regno = reg_from_argno(argno); 1793 1794 if (regno >= 0) { 1795 snprintf(buf, len, "R%d", regno); 1796 } else { 1797 arg = arg_from_argno(argno); 1798 snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE); 1799 } 1800 1801 return buf; 1802 } 1803 1804 static const int caller_saved[CALLER_SAVED_REGS] = { 1805 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1806 }; 1807 1808 /* This helper doesn't clear reg->id */ 1809 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1810 { 1811 reg->var_off = tnum_const(imm); 1812 reg->r64 = cnum64_from_urange(imm, imm); 1813 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 1814 } 1815 1816 /* Mark the unknown part of a register (variable offset or scalar value) as 1817 * known to have the value @imm. 1818 */ 1819 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1820 { 1821 /* Clear off and union(map_ptr, range) */ 1822 memset(((u8 *)reg) + sizeof(reg->type), 0, 1823 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1824 reg->id = 0; 1825 reg->parent_id = 0; 1826 ___mark_reg_known(reg, imm); 1827 } 1828 1829 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1830 { 1831 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1832 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 1833 } 1834 1835 /* Mark the 'variable offset' part of a register as zero. This should be 1836 * used only on registers holding a pointer type. 1837 */ 1838 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1839 { 1840 __mark_reg_known(reg, 0); 1841 } 1842 1843 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1844 { 1845 __mark_reg_known(reg, 0); 1846 reg->type = SCALAR_VALUE; 1847 /* all scalars are assumed imprecise initially (unless unprivileged, 1848 * in which case everything is forced to be precise) 1849 */ 1850 reg->precise = !env->bpf_capable; 1851 } 1852 1853 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1854 struct bpf_reg_state *regs, u32 regno) 1855 { 1856 __mark_reg_known_zero(regs + regno); 1857 } 1858 1859 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1860 bool first_slot, int id, int parent_id) 1861 { 1862 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1863 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1864 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1865 */ 1866 __mark_reg_known_zero(reg); 1867 reg->type = CONST_PTR_TO_DYNPTR; 1868 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1869 reg->id = id; 1870 reg->parent_id = parent_id; 1871 reg->dynptr.type = type; 1872 reg->dynptr.first_slot = first_slot; 1873 } 1874 1875 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1876 { 1877 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1878 const struct bpf_map *map = reg->map_ptr; 1879 1880 if (map->inner_map_meta) { 1881 reg->type = CONST_PTR_TO_MAP; 1882 reg->map_ptr = map->inner_map_meta; 1883 /* transfer reg's id which is unique for every map_lookup_elem 1884 * as UID of the inner map. 1885 */ 1886 if (btf_record_has_field(map->inner_map_meta->record, 1887 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) { 1888 reg->map_uid = reg->id; 1889 } 1890 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1891 reg->type = PTR_TO_XDP_SOCK; 1892 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1893 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1894 reg->type = PTR_TO_SOCKET; 1895 } else { 1896 reg->type = PTR_TO_MAP_VALUE; 1897 } 1898 return; 1899 } 1900 1901 reg->type &= ~PTR_MAYBE_NULL; 1902 } 1903 1904 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1905 struct btf_field_graph_root *ds_head) 1906 { 1907 __mark_reg_known(®s[regno], ds_head->node_offset); 1908 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1909 regs[regno].btf = ds_head->btf; 1910 regs[regno].btf_id = ds_head->value_btf_id; 1911 } 1912 1913 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1914 { 1915 return type_is_pkt_pointer(reg->type); 1916 } 1917 1918 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1919 { 1920 return reg_is_pkt_pointer(reg) || 1921 reg->type == PTR_TO_PACKET_END; 1922 } 1923 1924 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1925 { 1926 return base_type(reg->type) == PTR_TO_MEM && 1927 (reg->type & 1928 (DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META)); 1929 } 1930 1931 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1932 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1933 enum bpf_reg_type which) 1934 { 1935 /* The register can already have a range from prior markings. 1936 * This is fine as long as it hasn't been advanced from its 1937 * origin. 1938 */ 1939 return reg->type == which && 1940 reg->id == 0 && 1941 tnum_equals_const(reg->var_off, 0); 1942 } 1943 1944 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1945 { 1946 reg->r32 = CNUM32_UNBOUNDED; 1947 } 1948 1949 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1950 { 1951 reg->r64 = CNUM64_UNBOUNDED; 1952 } 1953 1954 /* Reset the min/max bounds of a register */ 1955 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1956 { 1957 __mark_reg64_unbounded(reg); 1958 __mark_reg32_unbounded(reg); 1959 } 1960 1961 static void reset_reg64_and_tnum(struct bpf_reg_state *reg) 1962 { 1963 __mark_reg64_unbounded(reg); 1964 reg->var_off = tnum_unknown; 1965 } 1966 1967 static void reset_reg32_and_tnum(struct bpf_reg_state *reg) 1968 { 1969 __mark_reg32_unbounded(reg); 1970 reg->var_off = tnum_unknown; 1971 } 1972 1973 static struct cnum32 cnum32_from_tnum(struct tnum tnum) 1974 { 1975 tnum = tnum_subreg(tnum); 1976 if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN)) 1977 /* min signed is max(sign bit) | min(other bits) */ 1978 /* max signed is min(sign bit) | max(other bits) */ 1979 return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN), 1980 tnum.value | (tnum.mask & S32_MAX)); 1981 else 1982 return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask)); 1983 } 1984 1985 static struct cnum64 cnum64_from_tnum(struct tnum tnum) 1986 { 1987 if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN)) 1988 /* min signed is max(sign bit) | min(other bits) */ 1989 /* max signed is min(sign bit) | max(other bits) */ 1990 return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN), 1991 tnum.value | (tnum.mask & S64_MAX)); 1992 else 1993 return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask)); 1994 } 1995 1996 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1997 { 1998 cnum32_intersect_with(®->r32, cnum32_from_tnum(reg->var_off)); 1999 } 2000 2001 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2002 { 2003 u64 tnum_next, tmax; 2004 bool umin_in_tnum; 2005 2006 cnum64_intersect_with(®->r64, cnum64_from_tnum(reg->var_off)); 2007 2008 /* Check if u64 and tnum overlap in a single value */ 2009 tnum_next = tnum_step(reg->var_off, reg_umin(reg)); 2010 umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value; 2011 tmax = reg->var_off.value | reg->var_off.mask; 2012 if (umin_in_tnum && tnum_next > reg_umax(reg)) { 2013 /* The u64 range and the tnum only overlap in umin. 2014 * u64: ---[xxxxxx]----- 2015 * tnum: --xx----------x- 2016 */ 2017 ___mark_reg_known(reg, reg_umin(reg)); 2018 } else if (!umin_in_tnum && tnum_next == tmax) { 2019 /* The u64 range and the tnum only overlap in the maximum value 2020 * represented by the tnum, called tmax. 2021 * u64: ---[xxxxxx]----- 2022 * tnum: xx-----x-------- 2023 */ 2024 ___mark_reg_known(reg, tmax); 2025 } else if (!umin_in_tnum && tnum_next <= reg_umax(reg) && 2026 tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) { 2027 /* The u64 range and the tnum only overlap in between umin 2028 * (excluded) and umax. 2029 * u64: ---[xxxxxx]----- 2030 * tnum: xx----x-------x- 2031 */ 2032 ___mark_reg_known(reg, tnum_next); 2033 } 2034 } 2035 2036 static void __update_reg_bounds(struct bpf_reg_state *reg) 2037 { 2038 __update_reg32_bounds(reg); 2039 __update_reg64_bounds(reg); 2040 } 2041 2042 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg) 2043 { 2044 cnum32_intersect_with(®->r32, cnum32_from_cnum64(reg->r64)); 2045 } 2046 2047 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg) 2048 { 2049 reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32); 2050 } 2051 2052 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2053 { 2054 deduce_bounds_32_from_64(reg); 2055 deduce_bounds_64_from_32(reg); 2056 } 2057 2058 /* Attempts to improve var_off based on unsigned min/max information */ 2059 static void __reg_bound_offset(struct bpf_reg_state *reg) 2060 { 2061 struct tnum var64_off = tnum_intersect(reg->var_off, 2062 tnum_range(reg_umin(reg), 2063 reg_umax(reg))); 2064 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2065 tnum_range(reg_u32_min(reg), 2066 reg_u32_max(reg))); 2067 2068 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2069 } 2070 2071 static bool range_bounds_violation(struct bpf_reg_state *reg); 2072 2073 static void reg_bounds_sync(struct bpf_reg_state *reg) 2074 { 2075 /* If the input reg_state is invalid, we can exit early */ 2076 if (range_bounds_violation(reg)) 2077 return; 2078 /* We might have learned new bounds from the var_off. */ 2079 __update_reg_bounds(reg); 2080 /* We might have learned something about the sign bit. */ 2081 __reg_deduce_bounds(reg); 2082 __reg_deduce_bounds(reg); 2083 /* We might have learned some bits from the bounds. */ 2084 __reg_bound_offset(reg); 2085 /* Intersecting with the old var_off might have improved our bounds 2086 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2087 * then new var_off is (0; 0x7f...fc) which improves our umax. 2088 */ 2089 __update_reg_bounds(reg); 2090 } 2091 2092 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg) 2093 { 2094 if (!tnum_is_const(reg->var_off)) 2095 return false; 2096 2097 return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value; 2098 } 2099 2100 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg) 2101 { 2102 if (!tnum_subreg_is_const(reg->var_off)) 2103 return false; 2104 2105 return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value; 2106 } 2107 2108 static bool range_bounds_violation(struct bpf_reg_state *reg) 2109 { 2110 return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64); 2111 } 2112 2113 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2114 struct bpf_reg_state *reg, const char *ctx) 2115 { 2116 const char *msg; 2117 2118 if (range_bounds_violation(reg)) { 2119 msg = "range bounds violation"; 2120 goto out; 2121 } 2122 2123 if (const_tnum_range_mismatch(reg)) { 2124 msg = "const tnum out of sync with range bounds"; 2125 goto out; 2126 } 2127 2128 if (const_tnum_range_mismatch_32(reg)) { 2129 msg = "const subreg tnum out of sync with range bounds"; 2130 goto out; 2131 } 2132 2133 return 0; 2134 out: 2135 verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} " 2136 "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx)", 2137 ctx, msg, 2138 reg->r64.base, reg->r64.size, 2139 reg->r32.base, reg->r32.size, 2140 reg->var_off.value, reg->var_off.mask); 2141 if (env->test_reg_invariants) 2142 return -EFAULT; 2143 __mark_reg_unbounded(reg); 2144 return 0; 2145 } 2146 2147 /* Mark a register as having a completely unknown (scalar) value. */ 2148 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2149 { 2150 s32 subreg_def = reg->subreg_def; 2151 2152 memset(reg, 0, sizeof(*reg)); 2153 reg->type = SCALAR_VALUE; 2154 reg->var_off = tnum_unknown; 2155 reg->subreg_def = subreg_def; 2156 __mark_reg_unbounded(reg); 2157 } 2158 2159 /* Mark a register as having a completely unknown (scalar) value, 2160 * initialize .precise as true when not bpf capable. 2161 */ 2162 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2163 struct bpf_reg_state *reg) 2164 { 2165 bpf_mark_reg_unknown_imprecise(reg); 2166 reg->precise = !env->bpf_capable; 2167 } 2168 2169 static void mark_reg_unknown(struct bpf_verifier_env *env, 2170 struct bpf_reg_state *regs, u32 regno) 2171 { 2172 __mark_reg_unknown(env, regs + regno); 2173 } 2174 2175 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2176 struct bpf_reg_state *regs, 2177 u32 regno, 2178 s32 s32_min, 2179 s32 s32_max) 2180 { 2181 struct bpf_reg_state *reg = regs + regno; 2182 2183 reg_set_srange32(reg, 2184 max_t(s32, reg_s32_min(reg), s32_min), 2185 min_t(s32, reg_s32_max(reg), s32_max)); 2186 reg_set_srange64(reg, 2187 max_t(s64, reg_smin(reg), s32_min), 2188 min_t(s64, reg_smax(reg), s32_max)); 2189 2190 reg_bounds_sync(reg); 2191 2192 return reg_bounds_sanity_check(env, reg, "s32_range"); 2193 } 2194 2195 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env, 2196 struct bpf_reg_state *reg) 2197 { 2198 __mark_reg_unknown(env, reg); 2199 reg->type = NOT_INIT; 2200 } 2201 2202 static int mark_btf_ld_reg(struct bpf_verifier_env *env, 2203 struct bpf_reg_state *regs, u32 regno, 2204 enum bpf_reg_type reg_type, 2205 struct btf *btf, u32 btf_id, 2206 enum bpf_type_flag flag) 2207 { 2208 switch (reg_type) { 2209 case SCALAR_VALUE: 2210 mark_reg_unknown(env, regs, regno); 2211 return 0; 2212 case PTR_TO_BTF_ID: 2213 mark_reg_known_zero(env, regs, regno); 2214 regs[regno].type = PTR_TO_BTF_ID | flag; 2215 regs[regno].btf = btf; 2216 regs[regno].btf_id = btf_id; 2217 if (type_may_be_null(flag)) 2218 regs[regno].id = ++env->id_gen; 2219 return 0; 2220 case PTR_TO_MEM: 2221 mark_reg_known_zero(env, regs, regno); 2222 regs[regno].type = PTR_TO_MEM | flag; 2223 regs[regno].mem_size = 0; 2224 return 0; 2225 default: 2226 verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__); 2227 return -EFAULT; 2228 } 2229 } 2230 2231 #define DEF_NOT_SUBREG (0) 2232 static void init_reg_state(struct bpf_verifier_env *env, 2233 struct bpf_func_state *state) 2234 { 2235 struct bpf_reg_state *regs = state->regs; 2236 int i; 2237 2238 for (i = 0; i < MAX_BPF_REG; i++) { 2239 bpf_mark_reg_not_init(env, ®s[i]); 2240 regs[i].subreg_def = DEF_NOT_SUBREG; 2241 } 2242 2243 /* frame pointer */ 2244 regs[BPF_REG_FP].type = PTR_TO_STACK; 2245 mark_reg_known_zero(env, regs, BPF_REG_FP); 2246 regs[BPF_REG_FP].frameno = state->frameno; 2247 } 2248 2249 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2250 { 2251 /* 2252 * return_32bit is set to false by default and set explicitly 2253 * by the caller when necessary. 2254 */ 2255 return (struct bpf_retval_range){ minval, maxval, false }; 2256 } 2257 2258 static void init_func_state(struct bpf_verifier_env *env, 2259 struct bpf_func_state *state, 2260 int callsite, int frameno, int subprogno) 2261 { 2262 state->callsite = callsite; 2263 state->frameno = frameno; 2264 state->subprogno = subprogno; 2265 state->callback_ret_range = retval_range(0, 0); 2266 init_reg_state(env, state); 2267 mark_verifier_state_scratched(env); 2268 } 2269 2270 /* Similar to push_stack(), but for async callbacks */ 2271 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2272 int insn_idx, int prev_insn_idx, 2273 int subprog, bool is_sleepable) 2274 { 2275 struct bpf_verifier_stack_elem *elem; 2276 struct bpf_func_state *frame; 2277 2278 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 2279 if (!elem) 2280 return ERR_PTR(-ENOMEM); 2281 2282 elem->insn_idx = insn_idx; 2283 elem->prev_insn_idx = prev_insn_idx; 2284 elem->next = env->head; 2285 elem->log_pos = env->log.end_pos; 2286 env->head = elem; 2287 env->stack_size++; 2288 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2289 verbose(env, 2290 "The sequence of %d jumps is too complex for async cb.\n", 2291 env->stack_size); 2292 return ERR_PTR(-E2BIG); 2293 } 2294 /* Unlike push_stack() do not bpf_copy_verifier_state(). 2295 * The caller state doesn't matter. 2296 * This is async callback. It starts in a fresh stack. 2297 * Initialize it similar to do_check_common(). 2298 */ 2299 elem->st.branches = 1; 2300 elem->st.in_sleepable = is_sleepable; 2301 frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT); 2302 if (!frame) 2303 return ERR_PTR(-ENOMEM); 2304 init_func_state(env, frame, 2305 BPF_MAIN_FUNC /* callsite */, 2306 0 /* frameno within this callchain */, 2307 subprog /* subprog number within this prog */); 2308 elem->st.frame[0] = frame; 2309 return &elem->st; 2310 } 2311 2312 2313 static int cmp_subprogs(const void *a, const void *b) 2314 { 2315 return ((struct bpf_subprog_info *)a)->start - 2316 ((struct bpf_subprog_info *)b)->start; 2317 } 2318 2319 /* Find subprogram that contains instruction at 'off' */ 2320 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off) 2321 { 2322 struct bpf_subprog_info *vals = env->subprog_info; 2323 int l, r, m; 2324 2325 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0) 2326 return NULL; 2327 2328 l = 0; 2329 r = env->subprog_cnt - 1; 2330 while (l < r) { 2331 m = l + (r - l + 1) / 2; 2332 if (vals[m].start <= off) 2333 l = m; 2334 else 2335 r = m - 1; 2336 } 2337 return &vals[l]; 2338 } 2339 2340 /* Find subprogram that starts exactly at 'off' */ 2341 int bpf_find_subprog(struct bpf_verifier_env *env, int off) 2342 { 2343 struct bpf_subprog_info *p; 2344 2345 p = bpf_find_containing_subprog(env, off); 2346 if (!p || p->start != off) 2347 return -ENOENT; 2348 return p - env->subprog_info; 2349 } 2350 2351 static int add_subprog(struct bpf_verifier_env *env, int off) 2352 { 2353 int insn_cnt = env->prog->len; 2354 int ret; 2355 2356 if (off >= insn_cnt || off < 0) { 2357 verbose(env, "call to invalid destination\n"); 2358 return -EINVAL; 2359 } 2360 ret = bpf_find_subprog(env, off); 2361 if (ret >= 0) 2362 return ret; 2363 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2364 verbose(env, "too many subprograms\n"); 2365 return -E2BIG; 2366 } 2367 /* determine subprog starts. The end is one before the next starts */ 2368 env->subprog_info[env->subprog_cnt++].start = off; 2369 sort(env->subprog_info, env->subprog_cnt, 2370 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2371 return env->subprog_cnt - 1; 2372 } 2373 2374 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2375 { 2376 struct bpf_prog_aux *aux = env->prog->aux; 2377 struct btf *btf = aux->btf; 2378 const struct btf_type *t; 2379 u32 main_btf_id, id; 2380 const char *name; 2381 int ret, i; 2382 2383 /* Non-zero func_info_cnt implies valid btf */ 2384 if (!aux->func_info_cnt) 2385 return 0; 2386 main_btf_id = aux->func_info[0].type_id; 2387 2388 t = btf_type_by_id(btf, main_btf_id); 2389 if (!t) { 2390 verbose(env, "invalid btf id for main subprog in func_info\n"); 2391 return -EINVAL; 2392 } 2393 2394 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2395 if (IS_ERR(name)) { 2396 ret = PTR_ERR(name); 2397 /* If there is no tag present, there is no exception callback */ 2398 if (ret == -ENOENT) 2399 ret = 0; 2400 else if (ret == -EEXIST) 2401 verbose(env, "multiple exception callback tags for main subprog\n"); 2402 return ret; 2403 } 2404 2405 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2406 if (ret < 0) { 2407 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2408 return ret; 2409 } 2410 id = ret; 2411 t = btf_type_by_id(btf, id); 2412 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2413 verbose(env, "exception callback '%s' must have global linkage\n", name); 2414 return -EINVAL; 2415 } 2416 ret = 0; 2417 for (i = 0; i < aux->func_info_cnt; i++) { 2418 if (aux->func_info[i].type_id != id) 2419 continue; 2420 ret = aux->func_info[i].insn_off; 2421 /* Further func_info and subprog checks will also happen 2422 * later, so assume this is the right insn_off for now. 2423 */ 2424 if (!ret) { 2425 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2426 ret = -EINVAL; 2427 } 2428 } 2429 if (!ret) { 2430 verbose(env, "exception callback type id not found in func_info\n"); 2431 ret = -EINVAL; 2432 } 2433 return ret; 2434 } 2435 2436 #define MAX_KFUNC_BTFS 256 2437 2438 struct bpf_kfunc_btf { 2439 struct btf *btf; 2440 struct module *module; 2441 u16 offset; 2442 }; 2443 2444 struct bpf_kfunc_btf_tab { 2445 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2446 u32 nr_descs; 2447 }; 2448 2449 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2450 { 2451 const struct bpf_kfunc_desc *d0 = a; 2452 const struct bpf_kfunc_desc *d1 = b; 2453 2454 /* func_id is not greater than BTF_MAX_TYPE */ 2455 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2456 } 2457 2458 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2459 { 2460 const struct bpf_kfunc_btf *d0 = a; 2461 const struct bpf_kfunc_btf *d1 = b; 2462 2463 return d0->offset - d1->offset; 2464 } 2465 2466 static struct bpf_kfunc_desc * 2467 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2468 { 2469 struct bpf_kfunc_desc desc = { 2470 .func_id = func_id, 2471 .offset = offset, 2472 }; 2473 struct bpf_kfunc_desc_tab *tab; 2474 2475 tab = prog->aux->kfunc_tab; 2476 return bsearch(&desc, tab->descs, tab->nr_descs, 2477 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2478 } 2479 2480 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2481 u16 btf_fd_idx, u8 **func_addr) 2482 { 2483 const struct bpf_kfunc_desc *desc; 2484 2485 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2486 if (!desc) 2487 return -EFAULT; 2488 2489 *func_addr = (u8 *)desc->addr; 2490 return 0; 2491 } 2492 2493 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2494 s16 offset) 2495 { 2496 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2497 struct bpf_kfunc_btf_tab *tab; 2498 struct bpf_kfunc_btf *b; 2499 struct module *mod; 2500 struct btf *btf; 2501 int btf_fd; 2502 2503 tab = env->prog->aux->kfunc_btf_tab; 2504 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2505 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2506 if (!b) { 2507 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2508 verbose(env, "too many different module BTFs\n"); 2509 return ERR_PTR(-E2BIG); 2510 } 2511 2512 if (bpfptr_is_null(env->fd_array)) { 2513 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2514 return ERR_PTR(-EPROTO); 2515 } 2516 2517 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2518 offset * sizeof(btf_fd), 2519 sizeof(btf_fd))) 2520 return ERR_PTR(-EFAULT); 2521 2522 btf = btf_get_by_fd(btf_fd); 2523 if (IS_ERR(btf)) { 2524 verbose(env, "invalid module BTF fd specified\n"); 2525 return btf; 2526 } 2527 2528 if (!btf_is_module(btf)) { 2529 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2530 btf_put(btf); 2531 return ERR_PTR(-EINVAL); 2532 } 2533 2534 mod = btf_try_get_module(btf); 2535 if (!mod) { 2536 btf_put(btf); 2537 return ERR_PTR(-ENXIO); 2538 } 2539 2540 b = &tab->descs[tab->nr_descs++]; 2541 b->btf = btf; 2542 b->module = mod; 2543 b->offset = offset; 2544 2545 /* sort() reorders entries by value, so b may no longer point 2546 * to the right entry after this 2547 */ 2548 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2549 kfunc_btf_cmp_by_off, NULL); 2550 } else { 2551 btf = b->btf; 2552 } 2553 2554 return btf; 2555 } 2556 2557 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2558 { 2559 if (!tab) 2560 return; 2561 2562 while (tab->nr_descs--) { 2563 module_put(tab->descs[tab->nr_descs].module); 2564 btf_put(tab->descs[tab->nr_descs].btf); 2565 } 2566 kfree(tab); 2567 } 2568 2569 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2570 { 2571 if (offset) { 2572 if (offset < 0) { 2573 /* In the future, this can be allowed to increase limit 2574 * of fd index into fd_array, interpreted as u16. 2575 */ 2576 verbose(env, "negative offset disallowed for kernel module function call\n"); 2577 return ERR_PTR(-EINVAL); 2578 } 2579 2580 return __find_kfunc_desc_btf(env, offset); 2581 } 2582 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2583 } 2584 2585 #define KF_IMPL_SUFFIX "_impl" 2586 2587 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_env *env, 2588 struct btf *btf, 2589 const char *func_name) 2590 { 2591 char *buf = env->tmp_str_buf; 2592 const struct btf_type *func; 2593 s32 impl_id; 2594 int len; 2595 2596 len = snprintf(buf, TMP_STR_BUF_LEN, "%s%s", func_name, KF_IMPL_SUFFIX); 2597 if (len < 0 || len >= TMP_STR_BUF_LEN) { 2598 verbose(env, "function name %s%s is too long\n", func_name, KF_IMPL_SUFFIX); 2599 return NULL; 2600 } 2601 2602 impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC); 2603 if (impl_id <= 0) { 2604 verbose(env, "cannot find function %s in BTF\n", buf); 2605 return NULL; 2606 } 2607 2608 func = btf_type_by_id(btf, impl_id); 2609 2610 return btf_type_by_id(btf, func->type); 2611 } 2612 2613 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 2614 s32 func_id, 2615 s16 offset, 2616 struct bpf_kfunc_meta *kfunc) 2617 { 2618 const struct btf_type *func, *func_proto; 2619 const char *func_name; 2620 u32 *kfunc_flags; 2621 struct btf *btf; 2622 2623 if (func_id <= 0) { 2624 verbose(env, "invalid kernel function btf_id %d\n", func_id); 2625 return -EINVAL; 2626 } 2627 2628 btf = find_kfunc_desc_btf(env, offset); 2629 if (IS_ERR(btf)) { 2630 verbose(env, "failed to find BTF for kernel function\n"); 2631 return PTR_ERR(btf); 2632 } 2633 2634 /* 2635 * Note that kfunc_flags may be NULL at this point, which 2636 * means that we couldn't find func_id in any relevant 2637 * kfunc_id_set. This most likely indicates an invalid kfunc 2638 * call. However we don't fail with an error here, 2639 * and let the caller decide what to do with NULL kfunc->flags. 2640 */ 2641 kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog); 2642 2643 func = btf_type_by_id(btf, func_id); 2644 if (!func || !btf_type_is_func(func)) { 2645 verbose(env, "kernel btf_id %d is not a function\n", func_id); 2646 return -EINVAL; 2647 } 2648 2649 func_name = btf_name_by_offset(btf, func->name_off); 2650 2651 /* 2652 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag 2653 * can be found through the counterpart _impl kfunc. 2654 */ 2655 if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS)) 2656 func_proto = find_kfunc_impl_proto(env, btf, func_name); 2657 else 2658 func_proto = btf_type_by_id(btf, func->type); 2659 2660 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2661 verbose(env, "kernel function btf_id %d does not have a valid func_proto\n", 2662 func_id); 2663 return -EINVAL; 2664 } 2665 2666 memset(kfunc, 0, sizeof(*kfunc)); 2667 kfunc->btf = btf; 2668 kfunc->id = func_id; 2669 kfunc->name = func_name; 2670 kfunc->proto = func_proto; 2671 kfunc->flags = kfunc_flags; 2672 2673 return 0; 2674 } 2675 2676 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset) 2677 { 2678 struct bpf_kfunc_btf_tab *btf_tab; 2679 struct btf_func_model func_model; 2680 struct bpf_kfunc_desc_tab *tab; 2681 struct bpf_prog_aux *prog_aux; 2682 struct bpf_kfunc_meta kfunc; 2683 struct bpf_kfunc_desc *desc; 2684 unsigned long addr; 2685 int err; 2686 2687 prog_aux = env->prog->aux; 2688 tab = prog_aux->kfunc_tab; 2689 btf_tab = prog_aux->kfunc_btf_tab; 2690 if (!tab) { 2691 if (!btf_vmlinux) { 2692 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2693 return -ENOTSUPP; 2694 } 2695 2696 if (!env->prog->jit_requested) { 2697 verbose(env, "JIT is required for calling kernel function\n"); 2698 return -ENOTSUPP; 2699 } 2700 2701 if (!bpf_jit_supports_kfunc_call()) { 2702 verbose(env, "JIT does not support calling kernel function\n"); 2703 return -ENOTSUPP; 2704 } 2705 2706 if (!env->prog->gpl_compatible) { 2707 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2708 return -EINVAL; 2709 } 2710 2711 tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT); 2712 if (!tab) 2713 return -ENOMEM; 2714 prog_aux->kfunc_tab = tab; 2715 } 2716 2717 /* func_id == 0 is always invalid, but instead of returning an error, be 2718 * conservative and wait until the code elimination pass before returning 2719 * error, so that invalid calls that get pruned out can be in BPF programs 2720 * loaded from userspace. It is also required that offset be untouched 2721 * for such calls. 2722 */ 2723 if (!func_id && !offset) 2724 return 0; 2725 2726 if (!btf_tab && offset) { 2727 btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT); 2728 if (!btf_tab) 2729 return -ENOMEM; 2730 prog_aux->kfunc_btf_tab = btf_tab; 2731 } 2732 2733 if (find_kfunc_desc(env->prog, func_id, offset)) 2734 return 0; 2735 2736 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2737 verbose(env, "too many different kernel function calls\n"); 2738 return -E2BIG; 2739 } 2740 2741 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 2742 if (err) 2743 return err; 2744 2745 addr = kallsyms_lookup_name(kfunc.name); 2746 if (!addr) { 2747 verbose(env, "cannot find address for kernel function %s\n", kfunc.name); 2748 return -EINVAL; 2749 } 2750 2751 if (bpf_dev_bound_kfunc_id(func_id)) { 2752 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2753 if (err) 2754 return err; 2755 } 2756 2757 err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model); 2758 if (err) 2759 return err; 2760 2761 desc = &tab->descs[tab->nr_descs++]; 2762 desc->func_id = func_id; 2763 desc->offset = offset; 2764 desc->addr = addr; 2765 desc->func_model = func_model; 2766 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2767 kfunc_desc_cmp_by_id_off, NULL); 2768 return 0; 2769 } 2770 2771 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2772 { 2773 return !!prog->aux->kfunc_tab; 2774 } 2775 2776 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2777 { 2778 struct bpf_subprog_info *subprog = env->subprog_info; 2779 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2780 struct bpf_insn *insn = env->prog->insnsi; 2781 2782 /* Add entry function. */ 2783 ret = add_subprog(env, 0); 2784 if (ret) 2785 return ret; 2786 2787 for (i = 0; i < insn_cnt; i++, insn++) { 2788 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2789 !bpf_pseudo_kfunc_call(insn)) 2790 continue; 2791 2792 if (!env->bpf_capable) { 2793 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2794 return -EPERM; 2795 } 2796 2797 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2798 ret = add_subprog(env, i + insn->imm + 1); 2799 else 2800 ret = bpf_add_kfunc_call(env, insn->imm, insn->off); 2801 2802 if (ret < 0) 2803 return ret; 2804 } 2805 2806 ret = bpf_find_exception_callback_insn_off(env); 2807 if (ret < 0) 2808 return ret; 2809 ex_cb_insn = ret; 2810 2811 /* If ex_cb_insn > 0, this means that the main program has a subprog 2812 * marked using BTF decl tag to serve as the exception callback. 2813 */ 2814 if (ex_cb_insn) { 2815 ret = add_subprog(env, ex_cb_insn); 2816 if (ret < 0) 2817 return ret; 2818 for (i = 1; i < env->subprog_cnt; i++) { 2819 if (env->subprog_info[i].start != ex_cb_insn) 2820 continue; 2821 env->exception_callback_subprog = i; 2822 bpf_mark_subprog_exc_cb(env, i); 2823 break; 2824 } 2825 } 2826 2827 /* Add a fake 'exit' subprog which could simplify subprog iteration 2828 * logic. 'subprog_cnt' should not be increased. 2829 */ 2830 subprog[env->subprog_cnt].start = insn_cnt; 2831 2832 if (env->log.level & BPF_LOG_LEVEL2) 2833 for (i = 0; i < env->subprog_cnt; i++) 2834 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2835 2836 return 0; 2837 } 2838 2839 static int check_subprogs(struct bpf_verifier_env *env) 2840 { 2841 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2842 struct bpf_subprog_info *subprog = env->subprog_info; 2843 struct bpf_insn *insn = env->prog->insnsi; 2844 int insn_cnt = env->prog->len; 2845 2846 /* now check that all jumps are within the same subprog */ 2847 subprog_start = subprog[cur_subprog].start; 2848 subprog_end = subprog[cur_subprog + 1].start; 2849 for (i = 0; i < insn_cnt; i++) { 2850 u8 code = insn[i].code; 2851 2852 if (code == (BPF_JMP | BPF_CALL) && 2853 insn[i].src_reg == 0 && 2854 insn[i].imm == BPF_FUNC_tail_call) { 2855 subprog[cur_subprog].has_tail_call = true; 2856 subprog[cur_subprog].tail_call_reachable = true; 2857 } 2858 if (BPF_CLASS(code) == BPF_LD && 2859 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2860 subprog[cur_subprog].has_ld_abs = true; 2861 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2862 goto next; 2863 if (BPF_OP(code) == BPF_CALL) 2864 goto next; 2865 if (BPF_OP(code) == BPF_EXIT) { 2866 subprog[cur_subprog].exit_idx = i; 2867 goto next; 2868 } 2869 off = i + bpf_jmp_offset(&insn[i]) + 1; 2870 if (off < subprog_start || off >= subprog_end) { 2871 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2872 return -EINVAL; 2873 } 2874 next: 2875 if (i == subprog_end - 1) { 2876 /* to avoid fall-through from one subprog into another 2877 * the last insn of the subprog should be either exit 2878 * or unconditional jump back or bpf_throw call 2879 */ 2880 if (code != (BPF_JMP | BPF_EXIT) && 2881 code != (BPF_JMP32 | BPF_JA) && 2882 code != (BPF_JMP | BPF_JA)) { 2883 verbose(env, "last insn is not an exit or jmp\n"); 2884 return -EINVAL; 2885 } 2886 subprog_start = subprog_end; 2887 cur_subprog++; 2888 if (cur_subprog < env->subprog_cnt) 2889 subprog_end = subprog[cur_subprog + 1].start; 2890 } 2891 } 2892 return 0; 2893 } 2894 2895 /* 2896 * Sort subprogs in topological order so that leaf subprogs come first and 2897 * their callers come later. This is a DFS post-order traversal of the call 2898 * graph. Scan only reachable instructions (those in the computed postorder) of 2899 * the current subprog to discover callees (direct subprogs and sync 2900 * callbacks). 2901 */ 2902 static int sort_subprogs_topo(struct bpf_verifier_env *env) 2903 { 2904 struct bpf_subprog_info *si = env->subprog_info; 2905 int *insn_postorder = env->cfg.insn_postorder; 2906 struct bpf_insn *insn = env->prog->insnsi; 2907 int cnt = env->subprog_cnt; 2908 int *dfs_stack = NULL; 2909 int top = 0, order = 0; 2910 int i, ret = 0; 2911 u8 *color = NULL; 2912 2913 color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT); 2914 dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT); 2915 if (!color || !dfs_stack) { 2916 ret = -ENOMEM; 2917 goto out; 2918 } 2919 2920 /* 2921 * DFS post-order traversal. 2922 * Color values: 0 = unvisited, 1 = on stack, 2 = done. 2923 */ 2924 for (i = 0; i < cnt; i++) { 2925 if (color[i]) 2926 continue; 2927 color[i] = 1; 2928 dfs_stack[top++] = i; 2929 2930 while (top > 0) { 2931 int cur = dfs_stack[top - 1]; 2932 int po_start = si[cur].postorder_start; 2933 int po_end = si[cur + 1].postorder_start; 2934 bool pushed = false; 2935 int j; 2936 2937 for (j = po_start; j < po_end; j++) { 2938 int idx = insn_postorder[j]; 2939 int callee; 2940 2941 if (!bpf_pseudo_call(&insn[idx]) && !bpf_pseudo_func(&insn[idx])) 2942 continue; 2943 callee = bpf_find_subprog(env, idx + insn[idx].imm + 1); 2944 if (callee < 0) { 2945 ret = -EFAULT; 2946 goto out; 2947 } 2948 if (color[callee] == 2) 2949 continue; 2950 if (color[callee] == 1) { 2951 if (bpf_pseudo_func(&insn[idx])) 2952 continue; 2953 verbose(env, "recursive call from %s() to %s()\n", 2954 subprog_name(env, cur), 2955 subprog_name(env, callee)); 2956 ret = -EINVAL; 2957 goto out; 2958 } 2959 color[callee] = 1; 2960 dfs_stack[top++] = callee; 2961 pushed = true; 2962 break; 2963 } 2964 2965 if (!pushed) { 2966 color[cur] = 2; 2967 env->subprog_topo_order[order++] = cur; 2968 top--; 2969 } 2970 } 2971 } 2972 2973 if (env->log.level & BPF_LOG_LEVEL2) 2974 for (i = 0; i < cnt; i++) 2975 verbose(env, "topo_order[%d] = %s\n", 2976 i, subprog_name(env, env->subprog_topo_order[i])); 2977 out: 2978 kvfree(dfs_stack); 2979 kvfree(color); 2980 return ret; 2981 } 2982 2983 static void mark_stack_slots_scratched(struct bpf_verifier_env *env, 2984 int spi, int nr_slots) 2985 { 2986 int i; 2987 2988 for (i = 0; i < nr_slots; i++) 2989 mark_stack_slot_scratched(env, spi - i); 2990 } 2991 2992 /* This function is supposed to be used by the following 32-bit optimization 2993 * code only. It returns TRUE if the source or destination register operates 2994 * on 64-bit, otherwise return FALSE. 2995 */ 2996 bool bpf_is_reg64(struct bpf_insn *insn, 2997 u32 regno, struct bpf_reg_state *reg, enum bpf_reg_arg_type t) 2998 { 2999 u8 code, class, op; 3000 3001 code = insn->code; 3002 class = BPF_CLASS(code); 3003 op = BPF_OP(code); 3004 if (class == BPF_JMP) { 3005 /* BPF_EXIT for "main" will reach here. Return TRUE 3006 * conservatively. 3007 */ 3008 if (op == BPF_EXIT) 3009 return true; 3010 if (op == BPF_CALL) { 3011 /* BPF to BPF call will reach here because of marking 3012 * caller saved clobber with DST_OP_NO_MARK for which we 3013 * don't care the register def because they are anyway 3014 * marked as NOT_INIT already. 3015 */ 3016 if (insn->src_reg == BPF_PSEUDO_CALL) 3017 return false; 3018 /* Helper call will reach here because of arg type 3019 * check, conservatively return TRUE. 3020 */ 3021 if (t == SRC_OP) 3022 return true; 3023 3024 return false; 3025 } 3026 } 3027 3028 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3029 return false; 3030 3031 if (class == BPF_ALU64 || class == BPF_JMP || 3032 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3033 return true; 3034 3035 if (class == BPF_ALU || class == BPF_JMP32) 3036 return false; 3037 3038 if (class == BPF_LDX) { 3039 if (t != SRC_OP) 3040 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3041 /* LDX source must be ptr. */ 3042 return true; 3043 } 3044 3045 if (class == BPF_STX) { 3046 /* BPF_STX (including atomic variants) has one or more source 3047 * operands, one of which is a ptr. Check whether the caller is 3048 * asking about it. 3049 */ 3050 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3051 return true; 3052 return BPF_SIZE(code) == BPF_DW; 3053 } 3054 3055 if (class == BPF_LD) { 3056 u8 mode = BPF_MODE(code); 3057 3058 /* LD_IMM64 */ 3059 if (mode == BPF_IMM) 3060 return true; 3061 3062 /* Both LD_IND and LD_ABS return 32-bit data. */ 3063 if (t != SRC_OP) 3064 return false; 3065 3066 /* Implicit ctx ptr. */ 3067 if (regno == BPF_REG_6) 3068 return true; 3069 3070 /* Explicit source could be any width. */ 3071 return true; 3072 } 3073 3074 if (class == BPF_ST) 3075 /* The only source register for BPF_ST is a ptr. */ 3076 return true; 3077 3078 /* Conservatively return true at default. */ 3079 return true; 3080 } 3081 3082 static void mark_insn_zext(struct bpf_verifier_env *env, 3083 struct bpf_reg_state *reg) 3084 { 3085 s32 def_idx = reg->subreg_def; 3086 3087 if (def_idx == DEF_NOT_SUBREG) 3088 return; 3089 3090 env->insn_aux_data[def_idx - 1].zext_dst = true; 3091 /* The dst will be zero extended, so won't be sub-register anymore. */ 3092 reg->subreg_def = DEF_NOT_SUBREG; 3093 } 3094 3095 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3096 enum bpf_reg_arg_type t) 3097 { 3098 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3099 struct bpf_reg_state *reg; 3100 bool rw64; 3101 3102 mark_reg_scratched(env, regno); 3103 3104 reg = ®s[regno]; 3105 rw64 = bpf_is_reg64(insn, regno, reg, t); 3106 if (t == SRC_OP) { 3107 /* check whether register used as source operand can be read */ 3108 if (reg->type == NOT_INIT) { 3109 verbose(env, "R%d !read_ok\n", regno); 3110 return -EACCES; 3111 } 3112 /* We don't need to worry about FP liveness because it's read-only */ 3113 if (regno == BPF_REG_FP) 3114 return 0; 3115 3116 if (rw64) 3117 mark_insn_zext(env, reg); 3118 3119 return 0; 3120 } else { 3121 /* check whether register used as dest operand can be written to */ 3122 if (regno == BPF_REG_FP) { 3123 verbose(env, "frame pointer is read only\n"); 3124 return -EACCES; 3125 } 3126 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3127 if (t == DST_OP) 3128 mark_reg_unknown(env, regs, regno); 3129 } 3130 return 0; 3131 } 3132 3133 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3134 enum bpf_reg_arg_type t) 3135 { 3136 struct bpf_verifier_state *vstate = env->cur_state; 3137 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3138 3139 return __check_reg_arg(env, state->regs, regno, t); 3140 } 3141 3142 static void mark_indirect_target(struct bpf_verifier_env *env, int idx) 3143 { 3144 env->insn_aux_data[idx].indirect_target = true; 3145 } 3146 3147 #define LR_FRAMENO_BITS 4 3148 #define LR_SPI_BITS 6 3149 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3150 #define LR_SIZE_BITS 4 3151 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3152 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3153 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3154 #define LR_SPI_OFF LR_FRAMENO_BITS 3155 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3156 #define LINKED_REGS_MAX 5 3157 3158 static_assert(MAX_CALL_FRAMES <= (1 << LR_FRAMENO_BITS)); 3159 static_assert(LINKED_REGS_MAX < (1 << LR_SIZE_BITS)); 3160 static_assert(LINKED_REGS_MAX * LR_ENTRY_BITS + LR_SIZE_BITS <= 64); 3161 3162 struct linked_reg { 3163 u8 frameno; 3164 union { 3165 u8 spi; 3166 u8 regno; 3167 }; 3168 bool is_reg; 3169 }; 3170 3171 struct linked_regs { 3172 int cnt; 3173 struct linked_reg entries[LINKED_REGS_MAX]; 3174 }; 3175 3176 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3177 { 3178 if (s->cnt < LINKED_REGS_MAX) 3179 return &s->entries[s->cnt++]; 3180 3181 return NULL; 3182 } 3183 3184 /* 3185 * Use u64 as a vector of 5 11-bit values, use first 4-bits to track 3186 * number of elements currently in stack. 3187 * Pack one history entry for linked registers as 11 bits in the following format: 3188 * - 4-bits frameno 3189 * - 6-bits spi_or_reg 3190 * - 1-bit is_reg 3191 */ 3192 static u64 linked_regs_pack(struct linked_regs *s) 3193 { 3194 u64 val = 0; 3195 int i; 3196 3197 for (i = 0; i < s->cnt; ++i) { 3198 struct linked_reg *e = &s->entries[i]; 3199 u64 tmp = 0; 3200 3201 tmp |= e->frameno; 3202 tmp |= e->spi << LR_SPI_OFF; 3203 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3204 3205 val <<= LR_ENTRY_BITS; 3206 val |= tmp; 3207 } 3208 val <<= LR_SIZE_BITS; 3209 val |= s->cnt; 3210 return val; 3211 } 3212 3213 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3214 { 3215 int i; 3216 3217 s->cnt = val & LR_SIZE_MASK; 3218 val >>= LR_SIZE_BITS; 3219 3220 for (i = 0; i < s->cnt; ++i) { 3221 struct linked_reg *e = &s->entries[i]; 3222 3223 e->frameno = val & LR_FRAMENO_MASK; 3224 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3225 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3226 val >>= LR_ENTRY_BITS; 3227 } 3228 } 3229 3230 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3231 { 3232 const struct btf_type *func; 3233 struct btf *desc_btf; 3234 3235 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3236 return NULL; 3237 3238 desc_btf = find_kfunc_desc_btf(data, insn->off); 3239 if (IS_ERR(desc_btf)) 3240 return "<error>"; 3241 3242 func = btf_type_by_id(desc_btf, insn->imm); 3243 return btf_name_by_offset(desc_btf, func->name_off); 3244 } 3245 3246 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn) 3247 { 3248 const struct bpf_insn_cbs cbs = { 3249 .cb_call = disasm_kfunc_name, 3250 .cb_print = verbose, 3251 .private_data = env, 3252 }; 3253 3254 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3255 } 3256 3257 /* If any register R in hist->linked_regs is marked as precise in bt, 3258 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 3259 */ 3260 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 3261 { 3262 struct linked_regs linked_regs; 3263 bool some_precise = false; 3264 int i; 3265 3266 if (!hist || hist->linked_regs == 0) 3267 return; 3268 3269 linked_regs_unpack(hist->linked_regs, &linked_regs); 3270 for (i = 0; i < linked_regs.cnt; ++i) { 3271 struct linked_reg *e = &linked_regs.entries[i]; 3272 3273 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 3274 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 3275 some_precise = true; 3276 break; 3277 } 3278 } 3279 3280 if (!some_precise) 3281 return; 3282 3283 for (i = 0; i < linked_regs.cnt; ++i) { 3284 struct linked_reg *e = &linked_regs.entries[i]; 3285 3286 if (e->is_reg) 3287 bpf_bt_set_frame_reg(bt, e->frameno, e->regno); 3288 else 3289 bpf_bt_set_frame_slot(bt, e->frameno, e->spi); 3290 } 3291 } 3292 3293 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3294 { 3295 return bpf_mark_chain_precision(env, env->cur_state, regno, NULL); 3296 } 3297 3298 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 3299 * desired reg and stack masks across all relevant frames 3300 */ 3301 static int mark_chain_precision_batch(struct bpf_verifier_env *env, 3302 struct bpf_verifier_state *starting_state) 3303 { 3304 return bpf_mark_chain_precision(env, starting_state, -1, NULL); 3305 } 3306 3307 static bool is_spillable_regtype(enum bpf_reg_type type) 3308 { 3309 switch (base_type(type)) { 3310 case PTR_TO_MAP_VALUE: 3311 case PTR_TO_STACK: 3312 case PTR_TO_CTX: 3313 case PTR_TO_PACKET: 3314 case PTR_TO_PACKET_META: 3315 case PTR_TO_PACKET_END: 3316 case PTR_TO_FLOW_KEYS: 3317 case CONST_PTR_TO_MAP: 3318 case PTR_TO_SOCKET: 3319 case PTR_TO_SOCK_COMMON: 3320 case PTR_TO_TCP_SOCK: 3321 case PTR_TO_XDP_SOCK: 3322 case PTR_TO_BTF_ID: 3323 case PTR_TO_BUF: 3324 case PTR_TO_MEM: 3325 case PTR_TO_FUNC: 3326 case PTR_TO_MAP_KEY: 3327 case PTR_TO_ARENA: 3328 return true; 3329 default: 3330 return false; 3331 } 3332 } 3333 3334 3335 /* check if register is a constant scalar value */ 3336 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 3337 { 3338 return reg->type == SCALAR_VALUE && 3339 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 3340 } 3341 3342 /* assuming is_reg_const() is true, return constant value of a register */ 3343 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 3344 { 3345 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 3346 } 3347 3348 static bool __is_pointer_value(bool allow_ptr_leaks, 3349 const struct bpf_reg_state *reg) 3350 { 3351 if (allow_ptr_leaks) 3352 return false; 3353 3354 return reg->type != SCALAR_VALUE; 3355 } 3356 3357 static void clear_scalar_id(struct bpf_reg_state *reg) 3358 { 3359 reg->id = 0; 3360 reg->delta = 0; 3361 } 3362 3363 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 3364 struct bpf_reg_state *src_reg) 3365 { 3366 if (src_reg->type != SCALAR_VALUE) 3367 return; 3368 /* 3369 * The verifier is processing rX = rY insn and 3370 * rY->id has special linked register already. 3371 * Cleared it, since multiple rX += const are not supported. 3372 */ 3373 if (src_reg->id & BPF_ADD_CONST) 3374 clear_scalar_id(src_reg); 3375 /* 3376 * Ensure that src_reg has a valid ID that will be copied to 3377 * dst_reg and then will be used by sync_linked_regs() to 3378 * propagate min/max range. 3379 */ 3380 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 3381 src_reg->id = ++env->id_gen; 3382 } 3383 3384 static void save_register_state(struct bpf_verifier_env *env, 3385 struct bpf_func_state *state, 3386 int spi, struct bpf_reg_state *reg, 3387 int size) 3388 { 3389 int i; 3390 3391 state->stack[spi].spilled_ptr = *reg; 3392 3393 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3394 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 3395 3396 /* size < 8 bytes spill */ 3397 for (; i; i--) 3398 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 3399 } 3400 3401 static bool is_bpf_st_mem(struct bpf_insn *insn) 3402 { 3403 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 3404 } 3405 3406 static int get_reg_width(struct bpf_reg_state *reg) 3407 { 3408 return fls64(reg_umax(reg)); 3409 } 3410 3411 /* See comment for mark_fastcall_pattern_for_call() */ 3412 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 3413 struct bpf_func_state *state, int insn_idx, int off) 3414 { 3415 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 3416 struct bpf_insn_aux_data *aux = env->insn_aux_data; 3417 int i; 3418 3419 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 3420 return; 3421 /* access to the region [max_stack_depth .. fastcall_stack_off) 3422 * from something that is not a part of the fastcall pattern, 3423 * disable fastcall rewrites for current subprogram by setting 3424 * fastcall_stack_off to a value smaller than any possible offset. 3425 */ 3426 subprog->fastcall_stack_off = S16_MIN; 3427 /* reset fastcall aux flags within subprogram, 3428 * happens at most once per subprogram 3429 */ 3430 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 3431 aux[i].fastcall_spills_num = 0; 3432 aux[i].fastcall_pattern = 0; 3433 } 3434 } 3435 3436 static void scrub_special_slot(struct bpf_func_state *state, int spi) 3437 { 3438 int i; 3439 3440 /* regular write of data into stack destroys any spilled ptr */ 3441 state->stack[spi].spilled_ptr.type = NOT_INIT; 3442 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 3443 if (is_stack_slot_special(&state->stack[spi])) 3444 for (i = 0; i < BPF_REG_SIZE; i++) 3445 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 3446 } 3447 3448 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3449 * stack boundary and alignment are checked in check_mem_access() 3450 */ 3451 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3452 /* stack frame we're writing to */ 3453 struct bpf_func_state *state, 3454 int off, int size, int value_regno, 3455 int insn_idx) 3456 { 3457 struct bpf_func_state *cur; /* state of the current function */ 3458 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3459 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3460 struct bpf_reg_state *reg = NULL; 3461 int insn_flags = INSN_F_STACK_ACCESS; 3462 int hist_spi = spi, hist_frame = state->frameno; 3463 3464 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 3465 * so it's aligned access and [off, off + size) are within stack limits 3466 */ 3467 if (!env->allow_ptr_leaks && 3468 bpf_is_spilled_reg(&state->stack[spi]) && 3469 !bpf_is_spilled_scalar_reg(&state->stack[spi]) && 3470 size != BPF_REG_SIZE) { 3471 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3472 return -EACCES; 3473 } 3474 3475 cur = env->cur_state->frame[env->cur_state->curframe]; 3476 if (value_regno >= 0) 3477 reg = &cur->regs[value_regno]; 3478 if (!env->bypass_spec_v4) { 3479 bool sanitize = reg && is_spillable_regtype(reg->type); 3480 3481 for (i = 0; i < size; i++) { 3482 u8 type = state->stack[spi].slot_type[(slot - i) % 3483 BPF_REG_SIZE]; 3484 3485 if (type != STACK_MISC && type != STACK_ZERO) { 3486 sanitize = true; 3487 break; 3488 } 3489 } 3490 3491 if (sanitize) 3492 env->insn_aux_data[insn_idx].nospec_result = true; 3493 } 3494 3495 err = destroy_if_dynptr_stack_slot(env, state, spi); 3496 if (err) 3497 return err; 3498 3499 check_fastcall_stack_contract(env, state, insn_idx, off); 3500 mark_stack_slot_scratched(env, spi); 3501 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 3502 bool reg_value_fits; 3503 3504 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 3505 /* Make sure that reg had an ID to build a relation on spill. */ 3506 if (reg_value_fits) 3507 assign_scalar_id_before_mov(env, reg); 3508 save_register_state(env, state, spi, reg, size); 3509 /* Break the relation on a narrowing spill. */ 3510 if (!reg_value_fits) 3511 state->stack[spi].spilled_ptr.id = 0; 3512 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 3513 env->bpf_capable) { 3514 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 3515 3516 memset(tmp_reg, 0, sizeof(*tmp_reg)); 3517 __mark_reg_known(tmp_reg, insn->imm); 3518 tmp_reg->type = SCALAR_VALUE; 3519 save_register_state(env, state, spi, tmp_reg, size); 3520 } else if (reg && is_spillable_regtype(reg->type)) { 3521 /* register containing pointer is being spilled into stack */ 3522 if (size != BPF_REG_SIZE) { 3523 verbose_linfo(env, insn_idx, "; "); 3524 verbose(env, "invalid size of register spill\n"); 3525 return -EACCES; 3526 } 3527 if (state != cur && reg->type == PTR_TO_STACK) { 3528 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 3529 return -EINVAL; 3530 } 3531 save_register_state(env, state, spi, reg, size); 3532 } else { 3533 u8 type = STACK_MISC; 3534 3535 scrub_special_slot(state, spi); 3536 3537 /* when we zero initialize stack slots mark them as such */ 3538 if ((reg && bpf_register_is_null(reg)) || 3539 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 3540 /* STACK_ZERO case happened because register spill 3541 * wasn't properly aligned at the stack slot boundary, 3542 * so it's not a register spill anymore; force 3543 * originating register to be precise to make 3544 * STACK_ZERO correct for subsequent states 3545 */ 3546 err = mark_chain_precision(env, value_regno); 3547 if (err) 3548 return err; 3549 type = STACK_ZERO; 3550 } 3551 3552 /* Mark slots affected by this stack write. */ 3553 for (i = 0; i < size; i++) 3554 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 3555 insn_flags = 0; /* not a register spill */ 3556 } 3557 3558 if (insn_flags) 3559 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3560 hist_spi, hist_frame, 0); 3561 return 0; 3562 } 3563 3564 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is 3565 * known to contain a variable offset. 3566 * This function checks whether the write is permitted and conservatively 3567 * tracks the effects of the write, considering that each stack slot in the 3568 * dynamic range is potentially written to. 3569 * 3570 * 'value_regno' can be -1, meaning that an unknown value is being written to 3571 * the stack. 3572 * 3573 * Spilled pointers in range are not marked as written because we don't know 3574 * what's going to be actually written. This means that read propagation for 3575 * future reads cannot be terminated by this write. 3576 * 3577 * For privileged programs, uninitialized stack slots are considered 3578 * initialized by this write (even though we don't know exactly what offsets 3579 * are going to be written to). The idea is that we don't want the verifier to 3580 * reject future reads that access slots written to through variable offsets. 3581 */ 3582 static int check_stack_write_var_off(struct bpf_verifier_env *env, 3583 /* func where register points to */ 3584 struct bpf_func_state *state, 3585 struct bpf_reg_state *ptr_reg, int off, int size, 3586 int value_regno, int insn_idx) 3587 { 3588 struct bpf_func_state *cur; /* state of the current function */ 3589 int min_off, max_off; 3590 int i, err; 3591 struct bpf_reg_state *value_reg = NULL; 3592 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3593 bool writing_zero = false; 3594 /* set if the fact that we're writing a zero is used to let any 3595 * stack slots remain STACK_ZERO 3596 */ 3597 bool zero_used = false; 3598 3599 cur = env->cur_state->frame[env->cur_state->curframe]; 3600 min_off = reg_smin(ptr_reg) + off; 3601 max_off = reg_smax(ptr_reg) + off + size; 3602 if (value_regno >= 0) 3603 value_reg = &cur->regs[value_regno]; 3604 if ((value_reg && bpf_register_is_null(value_reg)) || 3605 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 3606 writing_zero = true; 3607 3608 for (i = min_off; i < max_off; i++) { 3609 int spi; 3610 3611 spi = bpf_get_spi(i); 3612 err = destroy_if_dynptr_stack_slot(env, state, spi); 3613 if (err) 3614 return err; 3615 } 3616 3617 check_fastcall_stack_contract(env, state, insn_idx, min_off); 3618 /* Variable offset writes destroy any spilled pointers in range. */ 3619 for (i = min_off; i < max_off; i++) { 3620 u8 new_type, *stype; 3621 int slot, spi; 3622 3623 slot = -i - 1; 3624 spi = slot / BPF_REG_SIZE; 3625 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 3626 mark_stack_slot_scratched(env, spi); 3627 3628 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 3629 /* Reject the write if range we may write to has not 3630 * been initialized beforehand. If we didn't reject 3631 * here, the ptr status would be erased below (even 3632 * though not all slots are actually overwritten), 3633 * possibly opening the door to leaks. 3634 * 3635 * We do however catch STACK_INVALID case below, and 3636 * only allow reading possibly uninitialized memory 3637 * later for CAP_PERFMON, as the write may not happen to 3638 * that slot. 3639 */ 3640 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 3641 insn_idx, i); 3642 return -EINVAL; 3643 } 3644 3645 /* If writing_zero and the spi slot contains a spill of value 0, 3646 * maintain the spill type. 3647 */ 3648 if (writing_zero && *stype == STACK_SPILL && 3649 bpf_is_spilled_scalar_reg(&state->stack[spi])) { 3650 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 3651 3652 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 3653 zero_used = true; 3654 continue; 3655 } 3656 } 3657 3658 /* 3659 * Scrub slots if variable-offset stack write goes over spilled pointers. 3660 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT 3661 * and valid program is rejected by check_stack_read_fixed_off() 3662 * with obscure "invalid size of register fill" message. 3663 */ 3664 scrub_special_slot(state, spi); 3665 3666 /* Update the slot type. */ 3667 new_type = STACK_MISC; 3668 if (writing_zero && *stype == STACK_ZERO) { 3669 new_type = STACK_ZERO; 3670 zero_used = true; 3671 } 3672 /* If the slot is STACK_INVALID, we check whether it's OK to 3673 * pretend that it will be initialized by this write. The slot 3674 * might not actually be written to, and so if we mark it as 3675 * initialized future reads might leak uninitialized memory. 3676 * For privileged programs, we will accept such reads to slots 3677 * that may or may not be written because, if we're reject 3678 * them, the error would be too confusing. 3679 * Conservatively, treat STACK_POISON in a similar way. 3680 */ 3681 if ((*stype == STACK_INVALID || *stype == STACK_POISON) && 3682 !env->allow_uninit_stack) { 3683 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 3684 insn_idx, i); 3685 return -EINVAL; 3686 } 3687 *stype = new_type; 3688 } 3689 if (zero_used) { 3690 /* backtracking doesn't work for STACK_ZERO yet. */ 3691 err = mark_chain_precision(env, value_regno); 3692 if (err) 3693 return err; 3694 } 3695 return 0; 3696 } 3697 3698 /* When register 'dst_regno' is assigned some values from stack[min_off, 3699 * max_off), we set the register's type according to the types of the 3700 * respective stack slots. If all the stack values are known to be zeros, then 3701 * so is the destination reg. Otherwise, the register is considered to be 3702 * SCALAR. This function does not deal with register filling; the caller must 3703 * ensure that all spilled registers in the stack range have been marked as 3704 * read. 3705 */ 3706 static void mark_reg_stack_read(struct bpf_verifier_env *env, 3707 /* func where src register points to */ 3708 struct bpf_func_state *ptr_state, 3709 int min_off, int max_off, int dst_regno) 3710 { 3711 struct bpf_verifier_state *vstate = env->cur_state; 3712 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3713 int i, slot, spi; 3714 u8 *stype; 3715 int zeros = 0; 3716 3717 for (i = min_off; i < max_off; i++) { 3718 slot = -i - 1; 3719 spi = slot / BPF_REG_SIZE; 3720 mark_stack_slot_scratched(env, spi); 3721 stype = ptr_state->stack[spi].slot_type; 3722 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 3723 break; 3724 zeros++; 3725 } 3726 if (zeros == max_off - min_off) { 3727 /* Any access_size read into register is zero extended, 3728 * so the whole register == const_zero. 3729 */ 3730 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3731 } else { 3732 /* have read misc data from the stack */ 3733 mark_reg_unknown(env, state->regs, dst_regno); 3734 } 3735 } 3736 3737 /* Read the stack at 'off' and put the results into the register indicated by 3738 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 3739 * spilled reg. 3740 * 3741 * 'dst_regno' can be -1, meaning that the read value is not going to a 3742 * register. 3743 * 3744 * The access is assumed to be within the current stack bounds. 3745 */ 3746 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 3747 /* func where src register points to */ 3748 struct bpf_func_state *reg_state, 3749 int off, int size, int dst_regno) 3750 { 3751 struct bpf_verifier_state *vstate = env->cur_state; 3752 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3753 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 3754 struct bpf_reg_state *reg; 3755 u8 *stype, type; 3756 int insn_flags = INSN_F_STACK_ACCESS; 3757 int hist_spi = spi, hist_frame = reg_state->frameno; 3758 3759 stype = reg_state->stack[spi].slot_type; 3760 reg = ®_state->stack[spi].spilled_ptr; 3761 3762 mark_stack_slot_scratched(env, spi); 3763 check_fastcall_stack_contract(env, state, env->insn_idx, off); 3764 3765 if (bpf_is_spilled_reg(®_state->stack[spi])) { 3766 u8 spill_size = 1; 3767 3768 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 3769 spill_size++; 3770 3771 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 3772 if (reg->type != SCALAR_VALUE) { 3773 verbose_linfo(env, env->insn_idx, "; "); 3774 verbose(env, "invalid size of register fill\n"); 3775 return -EACCES; 3776 } 3777 3778 if (dst_regno < 0) 3779 return 0; 3780 3781 if (size <= spill_size && 3782 bpf_stack_narrow_access_ok(off, size, spill_size)) { 3783 /* The earlier check_reg_arg() has decided the 3784 * subreg_def for this insn. Save it first. 3785 */ 3786 s32 subreg_def = state->regs[dst_regno].subreg_def; 3787 3788 if (env->bpf_capable && size == 4 && spill_size == 4 && 3789 get_reg_width(reg) <= 32) 3790 /* Ensure stack slot has an ID to build a relation 3791 * with the destination register on fill. 3792 */ 3793 assign_scalar_id_before_mov(env, reg); 3794 state->regs[dst_regno] = *reg; 3795 state->regs[dst_regno].subreg_def = subreg_def; 3796 3797 /* Break the relation on a narrowing fill. 3798 * coerce_reg_to_size will adjust the boundaries. 3799 */ 3800 if (get_reg_width(reg) > size * BITS_PER_BYTE) 3801 clear_scalar_id(&state->regs[dst_regno]); 3802 } else { 3803 int spill_cnt = 0, zero_cnt = 0; 3804 3805 for (i = 0; i < size; i++) { 3806 type = stype[(slot - i) % BPF_REG_SIZE]; 3807 if (type == STACK_SPILL) { 3808 spill_cnt++; 3809 continue; 3810 } 3811 if (type == STACK_MISC) 3812 continue; 3813 if (type == STACK_ZERO) { 3814 zero_cnt++; 3815 continue; 3816 } 3817 if (type == STACK_INVALID && env->allow_uninit_stack) 3818 continue; 3819 if (type == STACK_POISON) { 3820 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3821 off, i, size); 3822 } else { 3823 verbose(env, "invalid read from stack off %d+%d size %d\n", 3824 off, i, size); 3825 } 3826 return -EACCES; 3827 } 3828 3829 if (spill_cnt == size && 3830 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 3831 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3832 /* this IS register fill, so keep insn_flags */ 3833 } else if (zero_cnt == size) { 3834 /* similarly to mark_reg_stack_read(), preserve zeroes */ 3835 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3836 insn_flags = 0; /* not restoring original register state */ 3837 } else { 3838 mark_reg_unknown(env, state->regs, dst_regno); 3839 insn_flags = 0; /* not restoring original register state */ 3840 } 3841 } 3842 } else if (dst_regno >= 0) { 3843 /* restore register state from stack */ 3844 if (env->bpf_capable) 3845 /* Ensure stack slot has an ID to build a relation 3846 * with the destination register on fill. 3847 */ 3848 assign_scalar_id_before_mov(env, reg); 3849 state->regs[dst_regno] = *reg; 3850 /* mark reg as written since spilled pointer state likely 3851 * has its liveness marks cleared by is_state_visited() 3852 * which resets stack/reg liveness for state transitions 3853 */ 3854 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 3855 /* If dst_regno==-1, the caller is asking us whether 3856 * it is acceptable to use this value as a SCALAR_VALUE 3857 * (e.g. for XADD). 3858 * We must not allow unprivileged callers to do that 3859 * with spilled pointers. 3860 */ 3861 verbose(env, "leaking pointer from stack off %d\n", 3862 off); 3863 return -EACCES; 3864 } 3865 } else { 3866 for (i = 0; i < size; i++) { 3867 type = stype[(slot - i) % BPF_REG_SIZE]; 3868 if (type == STACK_MISC) 3869 continue; 3870 if (type == STACK_ZERO) 3871 continue; 3872 if (type == STACK_INVALID && env->allow_uninit_stack) 3873 continue; 3874 if (type == STACK_POISON) { 3875 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3876 off, i, size); 3877 } else { 3878 verbose(env, "invalid read from stack off %d+%d size %d\n", 3879 off, i, size); 3880 } 3881 return -EACCES; 3882 } 3883 if (dst_regno >= 0) 3884 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3885 insn_flags = 0; /* we are not restoring spilled register */ 3886 } 3887 if (insn_flags) 3888 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3889 hist_spi, hist_frame, 0); 3890 return 0; 3891 } 3892 3893 enum bpf_access_src { 3894 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3895 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3896 }; 3897 3898 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3899 argno_t argno, int off, int access_size, 3900 bool zero_size_allowed, 3901 enum bpf_access_type type, 3902 struct bpf_call_arg_meta *meta); 3903 3904 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3905 { 3906 return cur_regs(env) + regno; 3907 } 3908 3909 /* Read the stack at 'reg + off' and put the result into the register 3910 * 'dst_regno'. 3911 * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'), 3912 * but not its variable offset. 3913 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3914 * 3915 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3916 * filling registers (i.e. reads of spilled register cannot be detected when 3917 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3918 * SCALAR_VALUE. That's why we assert that the 'reg' has a variable 3919 * offset; for a fixed offset check_stack_read_fixed_off should be used 3920 * instead. 3921 */ 3922 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3923 argno_t ptr_argno, int off, int size, int dst_regno) 3924 { 3925 struct bpf_func_state *ptr_state = bpf_func(env, reg); 3926 int err; 3927 int min_off, max_off; 3928 3929 /* Note that we pass a NULL meta, so raw access will not be permitted. 3930 */ 3931 err = check_stack_range_initialized(env, reg, ptr_argno, off, size, 3932 false, BPF_READ, NULL); 3933 if (err) 3934 return err; 3935 3936 min_off = reg_smin(reg) + off; 3937 max_off = reg_smax(reg) + off; 3938 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 3939 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 3940 return 0; 3941 } 3942 3943 /* check_stack_read dispatches to check_stack_read_fixed_off or 3944 * check_stack_read_var_off. 3945 * 3946 * The caller must ensure that the offset falls within the allocated stack 3947 * bounds. 3948 * 3949 * 'dst_regno' is a register which will receive the value from the stack. It 3950 * can be -1, meaning that the read value is not going to a register. 3951 */ 3952 static int check_stack_read(struct bpf_verifier_env *env, 3953 struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size, 3954 int dst_regno) 3955 { 3956 struct bpf_func_state *state = bpf_func(env, reg); 3957 int err; 3958 /* Some accesses are only permitted with a static offset. */ 3959 bool var_off = !tnum_is_const(reg->var_off); 3960 3961 /* The offset is required to be static when reads don't go to a 3962 * register, in order to not leak pointers (see 3963 * check_stack_read_fixed_off). 3964 */ 3965 if (dst_regno < 0 && var_off) { 3966 char tn_buf[48]; 3967 3968 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3969 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 3970 tn_buf, off, size); 3971 return -EACCES; 3972 } 3973 /* Variable offset is prohibited for unprivileged mode for simplicity 3974 * since it requires corresponding support in Spectre masking for stack 3975 * ALU. See also retrieve_ptr_limit(). The check in 3976 * check_stack_access_for_ptr_arithmetic() called by 3977 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 3978 * with variable offsets, therefore no check is required here. Further, 3979 * just checking it here would be insufficient as speculative stack 3980 * writes could still lead to unsafe speculative behaviour. 3981 */ 3982 if (!var_off) { 3983 off += reg->var_off.value; 3984 err = check_stack_read_fixed_off(env, state, off, size, 3985 dst_regno); 3986 } else { 3987 /* Variable offset stack reads need more conservative handling 3988 * than fixed offset ones. Note that dst_regno >= 0 on this 3989 * branch. 3990 */ 3991 err = check_stack_read_var_off(env, reg, ptr_argno, off, size, 3992 dst_regno); 3993 } 3994 return err; 3995 } 3996 3997 3998 /* check_stack_write dispatches to check_stack_write_fixed_off or 3999 * check_stack_write_var_off. 4000 * 4001 * 'reg' is the register used as a pointer into the stack. 4002 * 'value_regno' is the register whose value we're writing to the stack. It can 4003 * be -1, meaning that we're not writing from a register. 4004 * 4005 * The caller must ensure that the offset falls within the maximum stack size. 4006 */ 4007 static int check_stack_write(struct bpf_verifier_env *env, 4008 struct bpf_reg_state *reg, int off, int size, 4009 int value_regno, int insn_idx) 4010 { 4011 struct bpf_func_state *state = bpf_func(env, reg); 4012 int err; 4013 4014 if (tnum_is_const(reg->var_off)) { 4015 off += reg->var_off.value; 4016 err = check_stack_write_fixed_off(env, state, off, size, 4017 value_regno, insn_idx); 4018 } else { 4019 /* Variable offset stack reads need more conservative handling 4020 * than fixed offset ones. 4021 */ 4022 err = check_stack_write_var_off(env, state, 4023 reg, off, size, 4024 value_regno, insn_idx); 4025 } 4026 return err; 4027 } 4028 4029 /* 4030 * Write a value to the outgoing stack arg area. 4031 * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7). 4032 */ 4033 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state, 4034 int off, struct bpf_reg_state *value_reg) 4035 { 4036 int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS; 4037 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4038 int spi = -off / BPF_REG_SIZE - 1; 4039 struct bpf_reg_state *arg; 4040 int err; 4041 4042 if (spi >= max_stack_arg_regs) { 4043 verbose(env, "stack arg write offset %d exceeds max %d stack args\n", 4044 off, max_stack_arg_regs); 4045 return -EINVAL; 4046 } 4047 4048 err = grow_stack_arg_slots(env, state, spi + 1); 4049 if (err) 4050 return err; 4051 4052 /* Track the max outgoing stack arg slot count. */ 4053 if (spi + 1 > subprog->max_out_stack_arg_cnt) 4054 subprog->max_out_stack_arg_cnt = spi + 1; 4055 4056 if (value_reg) { 4057 state->stack_arg_regs[spi] = *value_reg; 4058 } else { 4059 /* BPF_ST: store immediate, treat as scalar */ 4060 arg = &state->stack_arg_regs[spi]; 4061 arg->type = SCALAR_VALUE; 4062 __mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm); 4063 } 4064 state->no_stack_arg_load = true; 4065 return bpf_push_jmp_history(env, env->cur_state, 4066 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4067 } 4068 4069 /* 4070 * Read a value from the incoming stack arg area. 4071 * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7). 4072 */ 4073 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state, 4074 int off, int dst_regno) 4075 { 4076 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4077 struct bpf_verifier_state *vstate = env->cur_state; 4078 int spi = off / BPF_REG_SIZE - 1; 4079 struct bpf_func_state *caller, *cur; 4080 struct bpf_reg_state *arg; 4081 4082 if (state->no_stack_arg_load) { 4083 verbose(env, "r11 load must be before any r11 store or call insn\n"); 4084 return -EINVAL; 4085 } 4086 4087 if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) { 4088 verbose(env, "invalid read from stack arg off %d depth %d\n", 4089 off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE); 4090 return -EACCES; 4091 } 4092 4093 caller = vstate->frame[vstate->curframe - 1]; 4094 arg = &caller->stack_arg_regs[spi]; 4095 cur = vstate->frame[vstate->curframe]; 4096 cur->regs[dst_regno] = *arg; 4097 return bpf_push_jmp_history(env, env->cur_state, 4098 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4099 } 4100 4101 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx) 4102 { 4103 struct bpf_func_state *caller = cur_func(env); 4104 int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS; 4105 4106 bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi); 4107 return mark_chain_precision_batch(env, env->cur_state); 4108 } 4109 4110 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller, 4111 int nargs) 4112 { 4113 int i, spi; 4114 4115 for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) { 4116 spi = i - MAX_BPF_FUNC_REG_ARGS; 4117 if (spi >= caller->out_stack_arg_cnt || 4118 caller->stack_arg_regs[spi].type == NOT_INIT) { 4119 verbose(env, "callee expects %d args, stack arg%d is not initialized\n", 4120 nargs, spi + 1); 4121 return -EFAULT; 4122 } 4123 } 4124 4125 return 0; 4126 } 4127 4128 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller, 4129 struct bpf_reg_state *regs, int arg) 4130 { 4131 if (arg < MAX_BPF_FUNC_REG_ARGS) 4132 return ®s[arg + 1]; 4133 4134 return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS]; 4135 } 4136 4137 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4138 int off, int size, enum bpf_access_type type) 4139 { 4140 struct bpf_map *map = reg->map_ptr; 4141 u32 cap = bpf_map_flags_to_cap(map); 4142 4143 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4144 verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n", 4145 map->value_size, reg_smin(reg) + off, size); 4146 return -EACCES; 4147 } 4148 4149 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4150 verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n", 4151 map->value_size, reg_smin(reg) + off, size); 4152 return -EACCES; 4153 } 4154 4155 return 0; 4156 } 4157 4158 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4159 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4160 int off, int size, u32 mem_size, 4161 bool zero_size_allowed) 4162 { 4163 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4164 4165 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4166 return 0; 4167 4168 switch (reg->type) { 4169 case PTR_TO_MAP_KEY: 4170 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4171 mem_size, off, size); 4172 break; 4173 case PTR_TO_MAP_VALUE: 4174 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4175 mem_size, off, size); 4176 break; 4177 case PTR_TO_PACKET: 4178 case PTR_TO_PACKET_META: 4179 case PTR_TO_PACKET_END: 4180 verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n", 4181 off, size, reg_arg_name(env, argno), reg->id, off, mem_size); 4182 break; 4183 case PTR_TO_CTX: 4184 verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n", 4185 mem_size, off, size); 4186 break; 4187 case PTR_TO_MEM: 4188 default: 4189 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4190 mem_size, off, size); 4191 } 4192 4193 return -EACCES; 4194 } 4195 4196 /* check read/write into a memory region with possible variable offset */ 4197 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4198 int off, int size, u32 mem_size, 4199 bool zero_size_allowed) 4200 { 4201 int err; 4202 4203 /* We may have adjusted the register pointing to memory region, so we 4204 * need to try adding each of min_value and max_value to off 4205 * to make sure our theoretical access will be safe. 4206 * 4207 * The minimum value is only important with signed 4208 * comparisons where we can't assume the floor of a 4209 * value is 0. If we are using signed variables for our 4210 * index'es we need to make sure that whatever we use 4211 * will have a set floor within our range. 4212 */ 4213 if (reg_smin(reg) < 0 && 4214 (reg_smin(reg) == S64_MIN || 4215 (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) || 4216 reg_smin(reg) + off < 0)) { 4217 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4218 reg_arg_name(env, argno)); 4219 return -EACCES; 4220 } 4221 err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size, 4222 mem_size, zero_size_allowed); 4223 if (err) { 4224 verbose(env, "%s min value is outside of the allowed memory range\n", 4225 reg_arg_name(env, argno)); 4226 return err; 4227 } 4228 4229 /* If we haven't set a max value then we need to bail since we can't be 4230 * sure we won't do bad things. 4231 * If reg_umax(reg) + off could overflow, treat that as unbounded too. 4232 */ 4233 if (reg_umax(reg) >= BPF_MAX_VAR_OFF) { 4234 verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n", 4235 reg_arg_name(env, argno)); 4236 return -EACCES; 4237 } 4238 err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size, 4239 mem_size, zero_size_allowed); 4240 if (err) { 4241 verbose(env, "%s max value is outside of the allowed memory range\n", 4242 reg_arg_name(env, argno)); 4243 return err; 4244 } 4245 4246 return 0; 4247 } 4248 4249 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4250 const struct bpf_reg_state *reg, argno_t argno, 4251 bool fixed_off_ok) 4252 { 4253 /* Access to this pointer-typed register or passing it to a helper 4254 * is only allowed in its original, unmodified form. 4255 */ 4256 4257 if (!tnum_is_const(reg->var_off)) { 4258 char tn_buf[48]; 4259 4260 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4261 verbose(env, "variable %s access var_off=%s disallowed\n", 4262 reg_type_str(env, reg->type), tn_buf); 4263 return -EACCES; 4264 } 4265 4266 if (reg_smin(reg) < 0) { 4267 verbose(env, "negative offset %s ptr %s off=%lld disallowed\n", 4268 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4269 return -EACCES; 4270 } 4271 4272 if (!fixed_off_ok && reg->var_off.value != 0) { 4273 verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n", 4274 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4275 return -EACCES; 4276 } 4277 4278 return 0; 4279 } 4280 4281 static int check_ptr_off_reg(struct bpf_verifier_env *env, 4282 const struct bpf_reg_state *reg, int regno) 4283 { 4284 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 4285 } 4286 4287 static int map_kptr_match_type(struct bpf_verifier_env *env, 4288 struct btf_field *kptr_field, 4289 struct bpf_reg_state *reg, u32 regno) 4290 { 4291 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4292 int perm_flags; 4293 const char *reg_name = ""; 4294 4295 if (base_type(reg->type) != PTR_TO_BTF_ID) 4296 goto bad_type; 4297 4298 if (btf_is_kernel(reg->btf)) { 4299 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 4300 4301 /* Only unreferenced case accepts untrusted pointers */ 4302 if (kptr_field->type == BPF_KPTR_UNREF) 4303 perm_flags |= PTR_UNTRUSTED; 4304 } else { 4305 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 4306 if (kptr_field->type == BPF_KPTR_PERCPU) 4307 perm_flags |= MEM_PERCPU; 4308 } 4309 4310 if (type_flag(reg->type) & ~perm_flags) 4311 goto bad_type; 4312 4313 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4314 reg_name = btf_type_name(reg->btf, reg->btf_id); 4315 4316 /* For ref_ptr case, release function check should ensure we get one 4317 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4318 * normal store of unreferenced kptr, we must ensure var_off is zero. 4319 * Since ref_ptr cannot be accessed directly by BPF insns, check for 4320 * reg->id is not needed here. 4321 */ 4322 if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true)) 4323 return -EACCES; 4324 4325 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 4326 * we also need to take into account the reg->var_off. 4327 * 4328 * We want to support cases like: 4329 * 4330 * struct foo { 4331 * struct bar br; 4332 * struct baz bz; 4333 * }; 4334 * 4335 * struct foo *v; 4336 * v = func(); // PTR_TO_BTF_ID 4337 * val->foo = v; // reg->var_off is zero, btf and btf_id match type 4338 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with 4339 * // first member type of struct after comparison fails 4340 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked 4341 * // to match type 4342 * 4343 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off 4344 * is zero. We must also ensure that btf_struct_ids_match does not walk 4345 * the struct to match type against first member of struct, i.e. reject 4346 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4347 * strict mode to true for type match. 4348 */ 4349 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value, 4350 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4351 kptr_field->type != BPF_KPTR_UNREF)) 4352 goto bad_type; 4353 return 0; 4354 bad_type: 4355 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4356 reg_type_str(env, reg->type), reg_name); 4357 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4358 if (kptr_field->type == BPF_KPTR_UNREF) 4359 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4360 targ_name); 4361 else 4362 verbose(env, "\n"); 4363 return -EINVAL; 4364 } 4365 4366 static bool in_sleepable(struct bpf_verifier_env *env) 4367 { 4368 return env->cur_state->in_sleepable; 4369 } 4370 4371 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 4372 * can dereference RCU protected pointers and result is PTR_TRUSTED. 4373 */ 4374 static bool in_rcu_cs(struct bpf_verifier_env *env) 4375 { 4376 return env->cur_state->active_rcu_locks || 4377 env->cur_state->active_locks || 4378 !in_sleepable(env); 4379 } 4380 4381 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 4382 BTF_SET_START(rcu_protected_types) 4383 #ifdef CONFIG_NET 4384 BTF_ID(struct, prog_test_ref_kfunc) 4385 #endif 4386 #ifdef CONFIG_CGROUPS 4387 BTF_ID(struct, cgroup) 4388 #endif 4389 #ifdef CONFIG_BPF_JIT 4390 BTF_ID(struct, bpf_cpumask) 4391 #endif 4392 BTF_ID(struct, task_struct) 4393 #ifdef CONFIG_CRYPTO 4394 BTF_ID(struct, bpf_crypto_ctx) 4395 #endif 4396 BTF_SET_END(rcu_protected_types) 4397 4398 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 4399 { 4400 if (!btf_is_kernel(btf)) 4401 return true; 4402 return btf_id_set_contains(&rcu_protected_types, btf_id); 4403 } 4404 4405 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 4406 { 4407 struct btf_struct_meta *meta; 4408 4409 if (btf_is_kernel(kptr_field->kptr.btf)) 4410 return NULL; 4411 4412 meta = btf_find_struct_meta(kptr_field->kptr.btf, 4413 kptr_field->kptr.btf_id); 4414 4415 return meta ? meta->record : NULL; 4416 } 4417 4418 static bool rcu_safe_kptr(const struct btf_field *field) 4419 { 4420 const struct btf_field_kptr *kptr = &field->kptr; 4421 4422 return field->type == BPF_KPTR_PERCPU || 4423 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 4424 } 4425 4426 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 4427 { 4428 struct btf_record *rec; 4429 u32 ret; 4430 4431 ret = PTR_MAYBE_NULL; 4432 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 4433 ret |= MEM_RCU; 4434 if (kptr_field->type == BPF_KPTR_PERCPU) 4435 ret |= MEM_PERCPU; 4436 else if (!btf_is_kernel(kptr_field->kptr.btf)) 4437 ret |= MEM_ALLOC; 4438 4439 rec = kptr_pointee_btf_record(kptr_field); 4440 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 4441 ret |= NON_OWN_REF; 4442 } else { 4443 ret |= PTR_UNTRUSTED; 4444 } 4445 4446 return ret; 4447 } 4448 4449 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 4450 struct btf_field *field) 4451 { 4452 struct bpf_reg_state *reg; 4453 const struct btf_type *t; 4454 4455 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 4456 mark_reg_known_zero(env, cur_regs(env), regno); 4457 reg = reg_state(env, regno); 4458 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 4459 reg->mem_size = t->size; 4460 reg->id = ++env->id_gen; 4461 4462 return 0; 4463 } 4464 4465 static int check_map_kptr_access(struct bpf_verifier_env *env, 4466 int value_regno, int insn_idx, 4467 struct btf_field *kptr_field) 4468 { 4469 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4470 int class = BPF_CLASS(insn->code); 4471 struct bpf_reg_state *val_reg; 4472 int ret; 4473 4474 /* Things we already checked for in check_map_access and caller: 4475 * - Reject cases where variable offset may touch kptr 4476 * - size of access (must be BPF_DW) 4477 * - tnum_is_const(reg->var_off) 4478 * - kptr_field->offset == off + reg->var_off.value 4479 */ 4480 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4481 if (BPF_MODE(insn->code) != BPF_MEM) { 4482 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4483 return -EACCES; 4484 } 4485 4486 /* We only allow loading referenced kptr, since it will be marked as 4487 * untrusted, similar to unreferenced kptr. 4488 */ 4489 if (class != BPF_LDX && 4490 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 4491 verbose(env, "store to referenced kptr disallowed\n"); 4492 return -EACCES; 4493 } 4494 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 4495 verbose(env, "store to uptr disallowed\n"); 4496 return -EACCES; 4497 } 4498 4499 if (class == BPF_LDX) { 4500 if (kptr_field->type == BPF_UPTR) 4501 return mark_uptr_ld_reg(env, value_regno, kptr_field); 4502 4503 /* We can simply mark the value_regno receiving the pointer 4504 * value from map as PTR_TO_BTF_ID, with the correct type. 4505 */ 4506 ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, 4507 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4508 btf_ld_kptr_type(env, kptr_field)); 4509 if (ret < 0) 4510 return ret; 4511 } else if (class == BPF_STX) { 4512 val_reg = reg_state(env, value_regno); 4513 if (!bpf_register_is_null(val_reg) && 4514 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4515 return -EACCES; 4516 } else if (class == BPF_ST) { 4517 if (insn->imm) { 4518 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4519 kptr_field->offset); 4520 return -EACCES; 4521 } 4522 } else { 4523 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4524 return -EACCES; 4525 } 4526 return 0; 4527 } 4528 4529 /* 4530 * Return the size of the memory region accessible from a pointer to map value. 4531 * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible. 4532 */ 4533 static u32 map_mem_size(const struct bpf_map *map) 4534 { 4535 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) 4536 return map->max_entries * sizeof(long); 4537 4538 return map->value_size; 4539 } 4540 4541 /* check read/write into a map element with possible variable offset */ 4542 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4543 int off, int size, bool zero_size_allowed, 4544 enum bpf_access_src src) 4545 { 4546 struct bpf_map *map = reg->map_ptr; 4547 u32 mem_size = map_mem_size(map); 4548 struct btf_record *rec; 4549 int err, i; 4550 4551 err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed); 4552 if (err) 4553 return err; 4554 4555 if (IS_ERR_OR_NULL(map->record)) 4556 return 0; 4557 rec = map->record; 4558 for (i = 0; i < rec->cnt; i++) { 4559 struct btf_field *field = &rec->fields[i]; 4560 u32 p = field->offset; 4561 4562 /* If any part of a field can be touched by load/store, reject 4563 * this program. To check that [x1, x2) overlaps with [y1, y2), 4564 * it is sufficient to check x1 < y2 && y1 < x2. 4565 */ 4566 if (reg_smin(reg) + off < p + field->size && 4567 p < reg_umax(reg) + off + size) { 4568 switch (field->type) { 4569 case BPF_KPTR_UNREF: 4570 case BPF_KPTR_REF: 4571 case BPF_KPTR_PERCPU: 4572 case BPF_UPTR: 4573 if (src != ACCESS_DIRECT) { 4574 verbose(env, "%s cannot be accessed indirectly by helper\n", 4575 btf_field_type_name(field->type)); 4576 return -EACCES; 4577 } 4578 if (!tnum_is_const(reg->var_off)) { 4579 verbose(env, "%s access cannot have variable offset\n", 4580 btf_field_type_name(field->type)); 4581 return -EACCES; 4582 } 4583 if (p != off + reg->var_off.value) { 4584 verbose(env, "%s access misaligned expected=%u off=%llu\n", 4585 btf_field_type_name(field->type), 4586 p, off + reg->var_off.value); 4587 return -EACCES; 4588 } 4589 if (size != bpf_size_to_bytes(BPF_DW)) { 4590 verbose(env, "%s access size must be BPF_DW\n", 4591 btf_field_type_name(field->type)); 4592 return -EACCES; 4593 } 4594 break; 4595 default: 4596 verbose(env, "%s cannot be accessed directly by load/store\n", 4597 btf_field_type_name(field->type)); 4598 return -EACCES; 4599 } 4600 } 4601 } 4602 return 0; 4603 } 4604 4605 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4606 const struct bpf_call_arg_meta *meta, 4607 enum bpf_access_type t) 4608 { 4609 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4610 4611 switch (prog_type) { 4612 /* Program types only with direct read access go here! */ 4613 case BPF_PROG_TYPE_LWT_IN: 4614 case BPF_PROG_TYPE_LWT_OUT: 4615 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4616 case BPF_PROG_TYPE_SK_REUSEPORT: 4617 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4618 case BPF_PROG_TYPE_CGROUP_SKB: 4619 if (t == BPF_WRITE) 4620 return false; 4621 fallthrough; 4622 4623 /* Program types with direct read + write access go here! */ 4624 case BPF_PROG_TYPE_SCHED_CLS: 4625 case BPF_PROG_TYPE_SCHED_ACT: 4626 case BPF_PROG_TYPE_XDP: 4627 case BPF_PROG_TYPE_LWT_XMIT: 4628 case BPF_PROG_TYPE_SK_SKB: 4629 case BPF_PROG_TYPE_SK_MSG: 4630 if (meta) 4631 return meta->pkt_access; 4632 4633 env->seen_direct_write = true; 4634 return true; 4635 4636 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4637 if (t == BPF_WRITE) 4638 env->seen_direct_write = true; 4639 4640 return true; 4641 4642 default: 4643 return false; 4644 } 4645 } 4646 4647 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 4648 int size, bool zero_size_allowed) 4649 { 4650 int err; 4651 4652 if (reg->range < 0) { 4653 verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno)); 4654 return -EINVAL; 4655 } 4656 4657 err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed); 4658 if (err) 4659 return err; 4660 4661 /* __check_mem_access has made sure "off + size - 1" is within u16. 4662 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff, 4663 * otherwise find_good_pkt_pointers would have refused to set range info 4664 * that __check_mem_access would have rejected this pkt access. 4665 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32. 4666 */ 4667 env->prog->aux->max_pkt_offset = 4668 max_t(u32, env->prog->aux->max_pkt_offset, 4669 off + reg_umax(reg) + size - 1); 4670 4671 return 0; 4672 } 4673 4674 static bool is_var_ctx_off_allowed(struct bpf_prog *prog) 4675 { 4676 return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL; 4677 } 4678 4679 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 4680 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 4681 enum bpf_access_type t, struct bpf_insn_access_aux *info) 4682 { 4683 if (env->ops->is_valid_access && 4684 env->ops->is_valid_access(off, size, t, env->prog, info)) { 4685 /* A non zero info.ctx_field_size indicates that this field is a 4686 * candidate for later verifier transformation to load the whole 4687 * field and then apply a mask when accessed with a narrower 4688 * access than actual ctx access size. A zero info.ctx_field_size 4689 * will only allow for whole field access and rejects any other 4690 * type of narrower access. 4691 */ 4692 if (base_type(info->reg_type) == PTR_TO_BTF_ID) { 4693 if (info->ref_id && 4694 !find_reference_state(env->cur_state, info->ref_id)) { 4695 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n", 4696 off); 4697 return -EACCES; 4698 } 4699 } else { 4700 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size; 4701 } 4702 /* remember the offset of last byte accessed in ctx */ 4703 if (env->prog->aux->max_ctx_offset < off + size) 4704 env->prog->aux->max_ctx_offset = off + size; 4705 return 0; 4706 } 4707 4708 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 4709 return -EACCES; 4710 } 4711 4712 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 4713 int off, int access_size, enum bpf_access_type t, 4714 struct bpf_insn_access_aux *info) 4715 { 4716 /* 4717 * Program types that don't rewrite ctx accesses can safely 4718 * dereference ctx pointers with fixed offsets. 4719 */ 4720 bool var_off_ok = is_var_ctx_off_allowed(env->prog); 4721 bool fixed_off_ok = !env->ops->convert_ctx_access; 4722 int err; 4723 4724 if (var_off_ok) 4725 err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false); 4726 else 4727 err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok); 4728 if (err) 4729 return err; 4730 off += reg_umax(reg); 4731 4732 err = __check_ctx_access(env, insn_idx, off, access_size, t, info); 4733 if (err) 4734 verbose_linfo(env, insn_idx, "; "); 4735 return err; 4736 } 4737 4738 static int check_flow_keys_access(struct bpf_verifier_env *env, 4739 struct bpf_reg_state *reg, argno_t argno, 4740 int off, int size) 4741 { 4742 /* Only a constant offset is allowed here; fold it into off. */ 4743 if (!tnum_is_const(reg->var_off)) { 4744 char tn_buf[48]; 4745 4746 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4747 verbose(env, "%s invalid variable offset to flow keys: off=%d, var_off=%s\n", 4748 reg_arg_name(env, argno), off, tn_buf); 4749 return -EACCES; 4750 } 4751 off += reg->var_off.value; 4752 4753 if (size < 0 || off < 0 || 4754 (u64)off + size > sizeof(struct bpf_flow_keys)) { 4755 verbose(env, "invalid access to flow keys off=%d size=%d\n", 4756 off, size); 4757 return -EACCES; 4758 } 4759 return 0; 4760 } 4761 4762 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 4763 struct bpf_reg_state *reg, argno_t argno, int off, int size, 4764 enum bpf_access_type t) 4765 { 4766 struct bpf_insn_access_aux info = {}; 4767 bool valid; 4768 4769 if (reg_smin(reg) < 0) { 4770 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4771 reg_arg_name(env, argno)); 4772 return -EACCES; 4773 } 4774 4775 switch (reg->type) { 4776 case PTR_TO_SOCK_COMMON: 4777 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 4778 break; 4779 case PTR_TO_SOCKET: 4780 valid = bpf_sock_is_valid_access(off, size, t, &info); 4781 break; 4782 case PTR_TO_TCP_SOCK: 4783 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 4784 break; 4785 case PTR_TO_XDP_SOCK: 4786 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 4787 break; 4788 default: 4789 valid = false; 4790 } 4791 4792 4793 if (valid) { 4794 env->insn_aux_data[insn_idx].ctx_field_size = 4795 info.ctx_field_size; 4796 return 0; 4797 } 4798 4799 verbose(env, "%s invalid %s access off=%d size=%d\n", 4800 reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size); 4801 4802 return -EACCES; 4803 } 4804 4805 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 4806 { 4807 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 4808 } 4809 4810 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 4811 { 4812 const struct bpf_reg_state *reg = reg_state(env, regno); 4813 4814 return reg->type == PTR_TO_CTX; 4815 } 4816 4817 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 4818 { 4819 const struct bpf_reg_state *reg = reg_state(env, regno); 4820 4821 return type_is_sk_pointer(reg->type); 4822 } 4823 4824 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 4825 { 4826 const struct bpf_reg_state *reg = reg_state(env, regno); 4827 4828 return type_is_pkt_pointer(reg->type); 4829 } 4830 4831 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 4832 { 4833 const struct bpf_reg_state *reg = reg_state(env, regno); 4834 4835 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 4836 return reg->type == PTR_TO_FLOW_KEYS; 4837 } 4838 4839 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 4840 { 4841 const struct bpf_reg_state *reg = reg_state(env, regno); 4842 4843 return reg->type == PTR_TO_ARENA; 4844 } 4845 4846 /* Return false if @regno contains a pointer whose type isn't supported for 4847 * atomic instruction @insn. 4848 */ 4849 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno, 4850 struct bpf_insn *insn) 4851 { 4852 if (is_ctx_reg(env, regno)) 4853 return false; 4854 if (is_pkt_reg(env, regno)) 4855 return false; 4856 if (is_flow_key_reg(env, regno)) 4857 return false; 4858 if (is_sk_reg(env, regno)) 4859 return false; 4860 if (is_arena_reg(env, regno)) 4861 return bpf_jit_supports_insn(insn, true); 4862 4863 return true; 4864 } 4865 4866 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 4867 #ifdef CONFIG_NET 4868 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 4869 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 4870 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 4871 #endif 4872 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 4873 }; 4874 4875 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 4876 { 4877 /* A referenced register is always trusted. */ 4878 if (reg_is_referenced(env, reg)) 4879 return true; 4880 4881 /* Types listed in the reg2btf_ids are always trusted */ 4882 if (reg2btf_ids[base_type(reg->type)] && 4883 !bpf_type_has_unsafe_modifiers(reg->type)) 4884 return true; 4885 4886 /* If a register is not referenced, it is trusted if it has the 4887 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 4888 * other type modifiers may be safe, but we elect to take an opt-in 4889 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 4890 * not. 4891 * 4892 * Eventually, we should make PTR_TRUSTED the single source of truth 4893 * for whether a register is trusted. 4894 */ 4895 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 4896 !bpf_type_has_unsafe_modifiers(reg->type); 4897 } 4898 4899 static bool is_rcu_reg(const struct bpf_reg_state *reg) 4900 { 4901 return reg->type & MEM_RCU; 4902 } 4903 4904 static void clear_trusted_flags(enum bpf_type_flag *flag) 4905 { 4906 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 4907 } 4908 4909 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 4910 const struct bpf_reg_state *reg, 4911 int off, int size, bool strict) 4912 { 4913 struct tnum reg_off; 4914 int ip_align; 4915 4916 /* Byte size accesses are always allowed. */ 4917 if (!strict || size == 1) 4918 return 0; 4919 4920 /* For platforms that do not have a Kconfig enabling 4921 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 4922 * NET_IP_ALIGN is universally set to '2'. And on platforms 4923 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 4924 * to this code only in strict mode where we want to emulate 4925 * the NET_IP_ALIGN==2 checking. Therefore use an 4926 * unconditional IP align value of '2'. 4927 */ 4928 ip_align = 2; 4929 4930 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off)); 4931 if (!tnum_is_aligned(reg_off, size)) { 4932 char tn_buf[48]; 4933 4934 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4935 verbose(env, 4936 "misaligned packet access off %d+%s+%d size %d\n", 4937 ip_align, tn_buf, off, size); 4938 return -EACCES; 4939 } 4940 4941 return 0; 4942 } 4943 4944 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 4945 const struct bpf_reg_state *reg, 4946 const char *pointer_desc, 4947 int off, int size, bool strict) 4948 { 4949 struct tnum reg_off; 4950 4951 /* Byte size accesses are always allowed. */ 4952 if (!strict || size == 1) 4953 return 0; 4954 4955 reg_off = tnum_add(reg->var_off, tnum_const(off)); 4956 if (!tnum_is_aligned(reg_off, size)) { 4957 char tn_buf[48]; 4958 4959 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4960 verbose(env, "misaligned %saccess off %s+%d size %d\n", 4961 pointer_desc, tn_buf, off, size); 4962 return -EACCES; 4963 } 4964 4965 return 0; 4966 } 4967 4968 static int check_ptr_alignment(struct bpf_verifier_env *env, 4969 const struct bpf_reg_state *reg, int off, 4970 int size, bool strict_alignment_once) 4971 { 4972 bool strict = env->strict_alignment || strict_alignment_once; 4973 const char *pointer_desc = ""; 4974 4975 switch (reg->type) { 4976 case PTR_TO_PACKET: 4977 case PTR_TO_PACKET_META: 4978 /* Special case, because of NET_IP_ALIGN. Given metadata sits 4979 * right in front, treat it the very same way. 4980 */ 4981 return check_pkt_ptr_alignment(env, reg, off, size, strict); 4982 case PTR_TO_FLOW_KEYS: 4983 pointer_desc = "flow keys "; 4984 break; 4985 case PTR_TO_MAP_KEY: 4986 pointer_desc = "key "; 4987 break; 4988 case PTR_TO_MAP_VALUE: 4989 pointer_desc = "value "; 4990 if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY) 4991 strict = true; 4992 break; 4993 case PTR_TO_CTX: 4994 pointer_desc = "context "; 4995 break; 4996 case PTR_TO_STACK: 4997 pointer_desc = "stack "; 4998 /* The stack spill tracking logic in check_stack_write_fixed_off() 4999 * and check_stack_read_fixed_off() relies on stack accesses being 5000 * aligned. 5001 */ 5002 strict = true; 5003 break; 5004 case PTR_TO_SOCKET: 5005 pointer_desc = "sock "; 5006 break; 5007 case PTR_TO_SOCK_COMMON: 5008 pointer_desc = "sock_common "; 5009 break; 5010 case PTR_TO_TCP_SOCK: 5011 pointer_desc = "tcp_sock "; 5012 break; 5013 case PTR_TO_XDP_SOCK: 5014 pointer_desc = "xdp_sock "; 5015 break; 5016 case PTR_TO_ARENA: 5017 return 0; 5018 default: 5019 break; 5020 } 5021 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5022 strict); 5023 } 5024 5025 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 5026 { 5027 if (!bpf_jit_supports_private_stack()) 5028 return NO_PRIV_STACK; 5029 5030 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 5031 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 5032 * explicitly. 5033 */ 5034 switch (prog->type) { 5035 case BPF_PROG_TYPE_KPROBE: 5036 case BPF_PROG_TYPE_TRACEPOINT: 5037 case BPF_PROG_TYPE_PERF_EVENT: 5038 case BPF_PROG_TYPE_RAW_TRACEPOINT: 5039 return PRIV_STACK_ADAPTIVE; 5040 case BPF_PROG_TYPE_TRACING: 5041 case BPF_PROG_TYPE_LSM: 5042 case BPF_PROG_TYPE_STRUCT_OPS: 5043 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 5044 return PRIV_STACK_ADAPTIVE; 5045 fallthrough; 5046 default: 5047 break; 5048 } 5049 5050 return NO_PRIV_STACK; 5051 } 5052 5053 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5054 { 5055 if (env->prog->jit_requested) 5056 return round_up(stack_depth, 16); 5057 5058 /* round up to 32-bytes, since this is granularity 5059 * of interpreter stack size 5060 */ 5061 return round_up(max_t(u32, stack_depth, 1), 32); 5062 } 5063 5064 /* temporary state used for call frame depth calculation */ 5065 struct bpf_subprog_call_depth_info { 5066 int ret_insn; /* caller instruction where we return to. */ 5067 int caller; /* caller subprogram idx */ 5068 int frame; /* # of consecutive static call stack frames on top of stack */ 5069 }; 5070 5071 /* starting from main bpf function walk all instructions of the function 5072 * and recursively walk all callees that given function can call. 5073 * Ignore jump and exit insns. 5074 */ 5075 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 5076 struct bpf_subprog_call_depth_info *dinfo, 5077 bool priv_stack_supported) 5078 { 5079 struct bpf_subprog_info *subprog = env->subprog_info; 5080 struct bpf_insn *insn = env->prog->insnsi; 5081 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 5082 bool tail_call_reachable = false; 5083 int total; 5084 int tmp; 5085 5086 /* no caller idx */ 5087 dinfo[idx].caller = -1; 5088 5089 i = subprog[idx].start; 5090 if (!priv_stack_supported) 5091 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5092 process_func: 5093 /* protect against potential stack overflow that might happen when 5094 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5095 * depth for such case down to 256 so that the worst case scenario 5096 * would result in 8k stack size (32 which is tailcall limit * 256 = 5097 * 8k). 5098 * 5099 * To get the idea what might happen, see an example: 5100 * func1 -> sub rsp, 128 5101 * subfunc1 -> sub rsp, 256 5102 * tailcall1 -> add rsp, 256 5103 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5104 * subfunc2 -> sub rsp, 64 5105 * subfunc22 -> sub rsp, 128 5106 * tailcall2 -> add rsp, 128 5107 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5108 * 5109 * tailcall will unwind the current stack frame but it will not get rid 5110 * of caller's stack as shown on the example above. 5111 */ 5112 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5113 verbose(env, 5114 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5115 depth); 5116 return -EACCES; 5117 } 5118 5119 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 5120 if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) { 5121 /* x86-64 uses R9 for both private stack frame pointer and arg6. */ 5122 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5123 } else if (priv_stack_supported) { 5124 /* Request private stack support only if the subprog stack 5125 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 5126 * avoid jit penalty if the stack usage is small. 5127 */ 5128 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 5129 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 5130 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 5131 } 5132 5133 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5134 if (subprog_depth > env->max_stack_depth) 5135 env->max_stack_depth = subprog_depth; 5136 if (subprog_depth > MAX_BPF_STACK) { 5137 verbose(env, "stack size of subprog %d is %d. Too large\n", 5138 idx, subprog_depth); 5139 return -EACCES; 5140 } 5141 } else { 5142 depth += subprog_depth; 5143 if (depth > env->max_stack_depth) 5144 env->max_stack_depth = depth; 5145 if (depth > MAX_BPF_STACK) { 5146 total = 0; 5147 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) 5148 total++; 5149 5150 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5151 total, depth); 5152 return -EACCES; 5153 } 5154 } 5155 continue_func: 5156 subprog_end = subprog[idx + 1].start; 5157 for (; i < subprog_end; i++) { 5158 int next_insn, sidx; 5159 5160 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5161 bool err = false; 5162 5163 if (!bpf_is_throw_kfunc(insn + i)) 5164 continue; 5165 for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) { 5166 if (subprog[tmp].is_cb) { 5167 err = true; 5168 break; 5169 } 5170 } 5171 if (!err) 5172 continue; 5173 verbose(env, 5174 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5175 i, idx); 5176 return -EINVAL; 5177 } 5178 5179 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5180 continue; 5181 /* remember insn and function to return to */ 5182 5183 /* find the callee */ 5184 next_insn = i + insn[i].imm + 1; 5185 sidx = bpf_find_subprog(env, next_insn); 5186 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn)) 5187 return -EFAULT; 5188 if (subprog[sidx].is_async_cb) { 5189 if (subprog[sidx].has_tail_call) { 5190 verifier_bug(env, "subprog has tail_call and async cb"); 5191 return -EFAULT; 5192 } 5193 /* async callbacks don't increase bpf prog stack size unless called directly */ 5194 if (!bpf_pseudo_call(insn + i)) 5195 continue; 5196 if (subprog[sidx].is_exception_cb) { 5197 verbose(env, "insn %d cannot call exception cb directly", i); 5198 return -EINVAL; 5199 } 5200 } 5201 5202 /* store caller info for after we return from callee */ 5203 dinfo[idx].frame = frame; 5204 dinfo[idx].ret_insn = i + 1; 5205 5206 /* push caller idx into callee's dinfo */ 5207 dinfo[sidx].caller = idx; 5208 5209 i = next_insn; 5210 5211 idx = sidx; 5212 if (!priv_stack_supported) 5213 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5214 5215 if (subprog[idx].has_tail_call) 5216 tail_call_reachable = true; 5217 5218 frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1; 5219 if (frame >= MAX_CALL_FRAMES) { 5220 verbose(env, "the call stack of %d frames is too deep !\n", 5221 frame); 5222 return -E2BIG; 5223 } 5224 goto process_func; 5225 } 5226 /* if tail call got detected across bpf2bpf calls then mark each of the 5227 * currently present subprog frames as tail call reachable subprogs; 5228 * this info will be utilized by JIT so that we will be preserving the 5229 * tail call counter throughout bpf2bpf calls combined with tailcalls 5230 */ 5231 if (tail_call_reachable) { 5232 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) { 5233 if (subprog[tmp].is_exception_cb) { 5234 verbose(env, "cannot tail call within exception cb\n"); 5235 return -EINVAL; 5236 } 5237 if (subprog[tmp].stack_arg_cnt) { 5238 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5239 return -EINVAL; 5240 } 5241 subprog[tmp].tail_call_reachable = true; 5242 } 5243 } else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) { 5244 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5245 return -EINVAL; 5246 } 5247 5248 if (subprog[0].tail_call_reachable) 5249 env->prog->aux->tail_call_reachable = true; 5250 5251 /* end of for() loop means the last insn of the 'subprog' 5252 * was reached. Doesn't matter whether it was JA or EXIT 5253 */ 5254 if (frame == 0 && dinfo[idx].caller < 0) 5255 return 0; 5256 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 5257 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 5258 5259 /* pop caller idx from callee */ 5260 idx = dinfo[idx].caller; 5261 5262 /* retrieve caller state from its frame */ 5263 frame = dinfo[idx].frame; 5264 i = dinfo[idx].ret_insn; 5265 5266 /* reset tail_call_reachable to the parent's actual state */ 5267 tail_call_reachable = subprog[idx].tail_call_reachable; 5268 5269 goto continue_func; 5270 } 5271 5272 static int check_max_stack_depth(struct bpf_verifier_env *env) 5273 { 5274 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 5275 struct bpf_subprog_call_depth_info *dinfo; 5276 struct bpf_subprog_info *si = env->subprog_info; 5277 bool priv_stack_supported; 5278 int ret; 5279 5280 dinfo = kvcalloc(env->subprog_cnt, sizeof(*dinfo), GFP_KERNEL_ACCOUNT); 5281 if (!dinfo) 5282 return -ENOMEM; 5283 5284 for (int i = 0; i < env->subprog_cnt; i++) { 5285 if (si[i].has_tail_call) { 5286 priv_stack_mode = NO_PRIV_STACK; 5287 break; 5288 } 5289 } 5290 5291 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 5292 priv_stack_mode = bpf_enable_priv_stack(env->prog); 5293 5294 /* All async_cb subprogs use normal kernel stack. If a particular 5295 * subprog appears in both main prog and async_cb subtree, that 5296 * subprog will use normal kernel stack to avoid potential nesting. 5297 * The reverse subprog traversal ensures when main prog subtree is 5298 * checked, the subprogs appearing in async_cb subtrees are already 5299 * marked as using normal kernel stack, so stack size checking can 5300 * be done properly. 5301 */ 5302 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 5303 if (!i || si[i].is_async_cb) { 5304 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 5305 ret = check_max_stack_depth_subprog(env, i, dinfo, 5306 priv_stack_supported); 5307 if (ret < 0) { 5308 kvfree(dinfo); 5309 return ret; 5310 } 5311 } 5312 } 5313 5314 for (int i = 0; i < env->subprog_cnt; i++) { 5315 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5316 env->prog->aux->jits_use_priv_stack = true; 5317 break; 5318 } 5319 } 5320 5321 kvfree(dinfo); 5322 5323 return 0; 5324 } 5325 5326 static int __check_buffer_access(struct bpf_verifier_env *env, 5327 const char *buf_info, 5328 const struct bpf_reg_state *reg, 5329 argno_t argno, int off, int size) 5330 { 5331 if (off < 0) { 5332 verbose(env, 5333 "%s invalid %s buffer access: off=%d, size=%d\n", 5334 reg_arg_name(env, argno), buf_info, off, size); 5335 return -EACCES; 5336 } 5337 if (!tnum_is_const(reg->var_off)) { 5338 char tn_buf[48]; 5339 5340 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5341 verbose(env, 5342 "%s invalid variable buffer offset: off=%d, var_off=%s\n", 5343 reg_arg_name(env, argno), off, tn_buf); 5344 return -EACCES; 5345 } 5346 5347 return 0; 5348 } 5349 5350 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5351 const struct bpf_reg_state *reg, 5352 argno_t argno, int off, int size) 5353 { 5354 int err; 5355 5356 err = __check_buffer_access(env, "tracepoint", reg, argno, off, size); 5357 if (err) 5358 return err; 5359 5360 env->prog->aux->max_tp_access = max(reg->var_off.value + off + size, 5361 env->prog->aux->max_tp_access); 5362 5363 return 0; 5364 } 5365 5366 static int check_buffer_access(struct bpf_verifier_env *env, 5367 const struct bpf_reg_state *reg, 5368 argno_t argno, int off, int size, 5369 bool zero_size_allowed, 5370 u32 *max_access) 5371 { 5372 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5373 int err; 5374 5375 err = __check_buffer_access(env, buf_info, reg, argno, off, size); 5376 if (err) 5377 return err; 5378 5379 *max_access = max(reg->var_off.value + off + size, *max_access); 5380 5381 return 0; 5382 } 5383 5384 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5385 static void zext_32_to_64(struct bpf_reg_state *reg) 5386 { 5387 reg->var_off = tnum_subreg(reg->var_off); 5388 reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg)); 5389 } 5390 5391 /* truncate register to smaller size (in bytes) 5392 * must be called with size < BPF_REG_SIZE 5393 */ 5394 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5395 { 5396 u64 mask; 5397 5398 /* clear high bits in bit representation */ 5399 reg->var_off = tnum_cast(reg->var_off, size); 5400 5401 /* fix arithmetic bounds */ 5402 mask = ((u64)1 << (size * 8)) - 1; 5403 if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask)) 5404 reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask); 5405 else 5406 reg_set_urange64(reg, 0, mask); 5407 5408 /* If size is smaller than 32bit register the 32bit register 5409 * values are also truncated so we push 64-bit bounds into 5410 * 32-bit bounds. Above were truncated < 32-bits already. 5411 */ 5412 if (size < 4) 5413 __mark_reg32_unbounded(reg); 5414 5415 reg_bounds_sync(reg); 5416 } 5417 5418 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 5419 { 5420 if (size == 1) { 5421 reg_set_srange64(reg, S8_MIN, S8_MAX); 5422 reg_set_srange32(reg, S8_MIN, S8_MAX); 5423 } else if (size == 2) { 5424 reg_set_srange64(reg, S16_MIN, S16_MAX); 5425 reg_set_srange32(reg, S16_MIN, S16_MAX); 5426 } else { 5427 /* size == 4 */ 5428 reg_set_srange64(reg, S32_MIN, S32_MAX); 5429 reg_set_srange32(reg, S32_MIN, S32_MAX); 5430 } 5431 reg->var_off = tnum_unknown; 5432 } 5433 5434 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 5435 { 5436 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 5437 u64 top_smax_value, top_smin_value; 5438 u64 num_bits = size * 8; 5439 5440 if (tnum_is_const(reg->var_off)) { 5441 u64_cval = reg->var_off.value; 5442 if (size == 1) 5443 reg->var_off = tnum_const((s8)u64_cval); 5444 else if (size == 2) 5445 reg->var_off = tnum_const((s16)u64_cval); 5446 else 5447 /* size == 4 */ 5448 reg->var_off = tnum_const((s32)u64_cval); 5449 5450 u64_cval = reg->var_off.value; 5451 reg->r64 = cnum64_from_urange(u64_cval, u64_cval); 5452 reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval); 5453 return; 5454 } 5455 5456 top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits; 5457 top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits; 5458 5459 if (top_smax_value != top_smin_value) 5460 goto out; 5461 5462 /* find the s64_min and s64_min after sign extension */ 5463 if (size == 1) { 5464 init_s64_max = (s8)reg_smax(reg); 5465 init_s64_min = (s8)reg_smin(reg); 5466 } else if (size == 2) { 5467 init_s64_max = (s16)reg_smax(reg); 5468 init_s64_min = (s16)reg_smin(reg); 5469 } else { 5470 init_s64_max = (s32)reg_smax(reg); 5471 init_s64_min = (s32)reg_smin(reg); 5472 } 5473 5474 s64_max = max(init_s64_max, init_s64_min); 5475 s64_min = min(init_s64_max, init_s64_min); 5476 5477 /* both of s64_max/s64_min positive or negative */ 5478 if ((s64_max >= 0) == (s64_min >= 0)) { 5479 reg_set_srange64(reg, s64_min, s64_max); 5480 reg_set_srange32(reg, s64_min, s64_max); 5481 reg->var_off = tnum_range(s64_min, s64_max); 5482 return; 5483 } 5484 5485 out: 5486 set_sext64_default_val(reg, size); 5487 } 5488 5489 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 5490 { 5491 if (size == 1) 5492 reg_set_srange32(reg, S8_MIN, S8_MAX); 5493 else 5494 /* size == 2 */ 5495 reg_set_srange32(reg, S16_MIN, S16_MAX); 5496 reg->var_off = tnum_subreg(tnum_unknown); 5497 } 5498 5499 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 5500 { 5501 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 5502 u32 top_smax_value, top_smin_value; 5503 u32 num_bits = size * 8; 5504 5505 if (tnum_is_const(reg->var_off)) { 5506 u32_val = reg->var_off.value; 5507 if (size == 1) 5508 reg->var_off = tnum_const((s8)u32_val); 5509 else 5510 reg->var_off = tnum_const((s16)u32_val); 5511 5512 u32_val = reg->var_off.value; 5513 reg_set_srange32(reg, u32_val, u32_val); 5514 return; 5515 } 5516 5517 top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits; 5518 top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits; 5519 5520 if (top_smax_value != top_smin_value) 5521 goto out; 5522 5523 /* find the s32_min and s32_min after sign extension */ 5524 if (size == 1) { 5525 init_s32_max = (s8)reg_s32_max(reg); 5526 init_s32_min = (s8)reg_s32_min(reg); 5527 } else { 5528 /* size == 2 */ 5529 init_s32_max = (s16)reg_s32_max(reg); 5530 init_s32_min = (s16)reg_s32_min(reg); 5531 } 5532 s32_max = max(init_s32_max, init_s32_min); 5533 s32_min = min(init_s32_max, init_s32_min); 5534 5535 if ((s32_min >= 0) == (s32_max >= 0)) { 5536 reg_set_srange32(reg, s32_min, s32_max); 5537 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 5538 return; 5539 } 5540 5541 out: 5542 set_sext32_default_val(reg, size); 5543 } 5544 5545 bool bpf_map_is_rdonly(const struct bpf_map *map) 5546 { 5547 /* A map is considered read-only if the following condition are true: 5548 * 5549 * 1) BPF program side cannot change any of the map content. The 5550 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 5551 * and was set at map creation time. 5552 * 2) The map value(s) have been initialized from user space by a 5553 * loader and then "frozen", such that no new map update/delete 5554 * operations from syscall side are possible for the rest of 5555 * the map's lifetime from that point onwards. 5556 * 3) Any parallel/pending map update/delete operations from syscall 5557 * side have been completed. Only after that point, it's safe to 5558 * assume that map value(s) are immutable. 5559 */ 5560 return (map->map_flags & BPF_F_RDONLY_PROG) && 5561 READ_ONCE(map->frozen) && 5562 !bpf_map_write_active(map); 5563 } 5564 5565 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 5566 bool is_ldsx) 5567 { 5568 void *ptr; 5569 u64 addr; 5570 int err; 5571 5572 err = map->ops->map_direct_value_addr(map, &addr, off); 5573 if (err) 5574 return err; 5575 ptr = (void *)(long)addr + off; 5576 5577 switch (size) { 5578 case sizeof(u8): 5579 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 5580 break; 5581 case sizeof(u16): 5582 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 5583 break; 5584 case sizeof(u32): 5585 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 5586 break; 5587 case sizeof(u64): 5588 *val = *(u64 *)ptr; 5589 break; 5590 default: 5591 return -EINVAL; 5592 } 5593 return 0; 5594 } 5595 5596 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 5597 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 5598 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 5599 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 5600 5601 /* 5602 * Allow list few fields as RCU trusted or full trusted. 5603 * This logic doesn't allow mix tagging and will be removed once GCC supports 5604 * btf_type_tag. 5605 */ 5606 5607 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 5608 BTF_TYPE_SAFE_RCU(struct task_struct) { 5609 const cpumask_t *cpus_ptr; 5610 struct css_set __rcu *cgroups; 5611 struct task_struct __rcu *real_parent; 5612 struct task_struct *group_leader; 5613 }; 5614 5615 BTF_TYPE_SAFE_RCU(struct cgroup) { 5616 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 5617 struct kernfs_node *kn; 5618 }; 5619 5620 BTF_TYPE_SAFE_RCU(struct css_set) { 5621 struct cgroup *dfl_cgrp; 5622 }; 5623 5624 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) { 5625 struct cgroup *cgroup; 5626 }; 5627 5628 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 5629 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 5630 struct file __rcu *exe_file; 5631 #ifdef CONFIG_MEMCG 5632 struct task_struct __rcu *owner; 5633 #endif 5634 }; 5635 5636 /* skb->sk, req->sk are not RCU protected, but we mark them as such 5637 * because bpf prog accessible sockets are SOCK_RCU_FREE. 5638 */ 5639 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 5640 struct sock *sk; 5641 }; 5642 5643 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 5644 struct sock *sk; 5645 }; 5646 5647 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 5648 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 5649 struct seq_file *seq; 5650 }; 5651 5652 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 5653 struct bpf_iter_meta *meta; 5654 struct task_struct *task; 5655 }; 5656 5657 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 5658 struct file *file; 5659 }; 5660 5661 BTF_TYPE_SAFE_TRUSTED(struct file) { 5662 struct inode *f_inode; 5663 }; 5664 5665 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) { 5666 struct inode *d_inode; 5667 }; 5668 5669 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 5670 struct sock *sk; 5671 }; 5672 5673 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) { 5674 struct mm_struct *vm_mm; 5675 struct file *vm_file; 5676 }; 5677 5678 static bool type_is_rcu(struct bpf_verifier_env *env, 5679 struct bpf_reg_state *reg, 5680 const char *field_name, u32 btf_id) 5681 { 5682 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 5683 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 5684 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 5685 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)); 5686 5687 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 5688 } 5689 5690 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 5691 struct bpf_reg_state *reg, 5692 const char *field_name, u32 btf_id) 5693 { 5694 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 5695 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 5696 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 5697 5698 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 5699 } 5700 5701 static bool type_is_trusted(struct bpf_verifier_env *env, 5702 struct bpf_reg_state *reg, 5703 const char *field_name, u32 btf_id) 5704 { 5705 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 5706 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 5707 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 5708 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 5709 5710 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 5711 } 5712 5713 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 5714 struct bpf_reg_state *reg, 5715 const char *field_name, u32 btf_id) 5716 { 5717 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 5718 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)); 5719 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct)); 5720 5721 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 5722 "__safe_trusted_or_null"); 5723 } 5724 5725 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 5726 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5727 argno_t argno, int off, int size, 5728 enum bpf_access_type atype, 5729 int value_regno) 5730 { 5731 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 5732 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 5733 const char *field_name = NULL; 5734 enum bpf_type_flag flag = 0; 5735 u32 btf_id = 0; 5736 int ret; 5737 5738 if (!env->allow_ptr_leaks) { 5739 verbose(env, 5740 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5741 tname); 5742 return -EPERM; 5743 } 5744 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 5745 verbose(env, 5746 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 5747 tname); 5748 return -EINVAL; 5749 } 5750 5751 if (!tnum_is_const(reg->var_off)) { 5752 char tn_buf[48]; 5753 5754 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5755 verbose(env, 5756 "%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 5757 reg_arg_name(env, argno), tname, off, tn_buf); 5758 return -EACCES; 5759 } 5760 5761 off += reg->var_off.value; 5762 5763 if (off < 0) { 5764 verbose(env, 5765 "%s is ptr_%s invalid negative access: off=%d\n", 5766 reg_arg_name(env, argno), tname, off); 5767 return -EACCES; 5768 } 5769 5770 if (reg->type & MEM_USER) { 5771 verbose(env, 5772 "%s is ptr_%s access user memory: off=%d\n", 5773 reg_arg_name(env, argno), tname, off); 5774 return -EACCES; 5775 } 5776 5777 if (reg->type & MEM_PERCPU) { 5778 verbose(env, 5779 "%s is ptr_%s access percpu memory: off=%d\n", 5780 reg_arg_name(env, argno), tname, off); 5781 return -EACCES; 5782 } 5783 5784 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 5785 if (!btf_is_kernel(reg->btf)) { 5786 verifier_bug(env, "reg->btf must be kernel btf"); 5787 return -EFAULT; 5788 } 5789 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 5790 if (ret < 0) 5791 verbose(env, 5792 "%s cannot write into ptr_%s at off=%d size=%d\n", 5793 reg_arg_name(env, argno), tname, off, size); 5794 } else { 5795 /* Writes are permitted with default btf_struct_access for 5796 * program allocated objects (which always have id > 0), 5797 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 5798 */ 5799 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 5800 verbose(env, "only read is supported\n"); 5801 return -EACCES; 5802 } 5803 5804 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 5805 !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) { 5806 verifier_bug(env, "allocated object must have a referenced id"); 5807 return -EFAULT; 5808 } 5809 5810 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 5811 } 5812 5813 if (ret < 0) 5814 return ret; 5815 5816 if (ret != PTR_TO_BTF_ID) { 5817 /* just mark; */ 5818 5819 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 5820 /* If this is an untrusted pointer, all pointers formed by walking it 5821 * also inherit the untrusted flag. 5822 */ 5823 flag = PTR_UNTRUSTED; 5824 5825 } else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) { 5826 /* By default any pointer obtained from walking a trusted pointer is no 5827 * longer trusted, unless the field being accessed has explicitly been 5828 * marked as inheriting its parent's state of trust (either full or RCU). 5829 * For example: 5830 * 'cgroups' pointer is untrusted if task->cgroups dereference 5831 * happened in a sleepable program outside of bpf_rcu_read_lock() 5832 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 5833 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 5834 * 5835 * A regular RCU-protected pointer with __rcu tag can also be deemed 5836 * trusted if we are in an RCU CS. Such pointer can be NULL. 5837 */ 5838 if (type_is_trusted(env, reg, field_name, btf_id)) { 5839 flag |= PTR_TRUSTED; 5840 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 5841 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 5842 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 5843 if (type_is_rcu(env, reg, field_name, btf_id)) { 5844 /* ignore __rcu tag and mark it MEM_RCU */ 5845 flag |= MEM_RCU; 5846 } else if (flag & MEM_RCU || 5847 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 5848 /* __rcu tagged pointers can be NULL */ 5849 flag |= MEM_RCU | PTR_MAYBE_NULL; 5850 5851 /* We always trust them */ 5852 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 5853 flag & PTR_UNTRUSTED) 5854 flag &= ~PTR_UNTRUSTED; 5855 } else if (flag & (MEM_PERCPU | MEM_USER)) { 5856 /* keep as-is */ 5857 } else { 5858 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 5859 clear_trusted_flags(&flag); 5860 } 5861 } else { 5862 /* 5863 * If not in RCU CS or MEM_RCU pointer can be NULL then 5864 * aggressively mark as untrusted otherwise such 5865 * pointers will be plain PTR_TO_BTF_ID without flags 5866 * and will be allowed to be passed into helpers for 5867 * compat reasons. 5868 */ 5869 flag = PTR_UNTRUSTED; 5870 } 5871 } else { 5872 /* Old compat. Deprecated */ 5873 clear_trusted_flags(&flag); 5874 } 5875 5876 if (atype == BPF_READ && value_regno >= 0) { 5877 ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5878 if (ret < 0) 5879 return ret; 5880 } 5881 5882 return 0; 5883 } 5884 5885 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5886 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5887 argno_t argno, int off, int size, 5888 enum bpf_access_type atype, 5889 int value_regno) 5890 { 5891 struct bpf_map *map = reg->map_ptr; 5892 struct bpf_reg_state map_reg; 5893 enum bpf_type_flag flag = 0; 5894 const struct btf_type *t; 5895 const char *tname; 5896 u32 btf_id; 5897 int ret; 5898 5899 if (!btf_vmlinux) { 5900 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5901 return -ENOTSUPP; 5902 } 5903 5904 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5905 verbose(env, "map_ptr access not supported for map type %d\n", 5906 map->map_type); 5907 return -ENOTSUPP; 5908 } 5909 5910 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5911 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5912 5913 if (!env->allow_ptr_leaks) { 5914 verbose(env, 5915 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5916 tname); 5917 return -EPERM; 5918 } 5919 5920 if (off < 0) { 5921 verbose(env, "%s is %s invalid negative access: off=%d\n", 5922 reg_arg_name(env, argno), tname, off); 5923 return -EACCES; 5924 } 5925 5926 if (atype != BPF_READ) { 5927 verbose(env, "only read from %s is supported\n", tname); 5928 return -EACCES; 5929 } 5930 5931 /* Simulate access to a PTR_TO_BTF_ID */ 5932 memset(&map_reg, 0, sizeof(map_reg)); 5933 ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, 5934 btf_vmlinux, *map->ops->map_btf_id, 0); 5935 if (ret < 0) 5936 return ret; 5937 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 5938 if (ret < 0) 5939 return ret; 5940 5941 if (value_regno >= 0) { 5942 ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 5943 if (ret < 0) 5944 return ret; 5945 } 5946 5947 return 0; 5948 } 5949 5950 /* Check that the stack access at the given offset is within bounds. The 5951 * maximum valid offset is -1. 5952 * 5953 * The minimum valid offset is -MAX_BPF_STACK for writes, and 5954 * -state->allocated_stack for reads. 5955 */ 5956 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 5957 s64 off, 5958 struct bpf_func_state *state, 5959 enum bpf_access_type t) 5960 { 5961 int min_valid_off; 5962 5963 if (t == BPF_WRITE || env->allow_uninit_stack) 5964 min_valid_off = -MAX_BPF_STACK; 5965 else 5966 min_valid_off = -state->allocated_stack; 5967 5968 if (off < min_valid_off || off > -1) 5969 return -EACCES; 5970 return 0; 5971 } 5972 5973 /* Check that the stack access at 'regno + off' falls within the maximum stack 5974 * bounds. 5975 * 5976 * 'off' includes `regno->offset`, but not its dynamic part (if any). 5977 */ 5978 static int check_stack_access_within_bounds( 5979 struct bpf_verifier_env *env, struct bpf_reg_state *reg, 5980 argno_t argno, int off, int access_size, 5981 enum bpf_access_type type) 5982 { 5983 struct bpf_func_state *state = bpf_func(env, reg); 5984 s64 min_off, max_off; 5985 int err; 5986 char *err_extra; 5987 5988 if (type == BPF_READ) 5989 err_extra = " read from"; 5990 else 5991 err_extra = " write to"; 5992 5993 if (tnum_is_const(reg->var_off)) { 5994 min_off = (s64)reg->var_off.value + off; 5995 max_off = min_off + access_size; 5996 } else { 5997 if (reg_smax(reg) >= BPF_MAX_VAR_OFF || 5998 reg_smin(reg) <= -BPF_MAX_VAR_OFF) { 5999 verbose(env, "invalid unbounded variable-offset%s stack %s\n", 6000 err_extra, reg_arg_name(env, argno)); 6001 return -EACCES; 6002 } 6003 min_off = reg_smin(reg) + off; 6004 max_off = reg_smax(reg) + off + access_size; 6005 } 6006 6007 err = check_stack_slot_within_bounds(env, min_off, state, type); 6008 if (!err && max_off > 0) 6009 err = -EINVAL; /* out of stack access into non-negative offsets */ 6010 if (!err && access_size < 0) 6011 /* access_size should not be negative (or overflow an int); others checks 6012 * along the way should have prevented such an access. 6013 */ 6014 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6015 6016 if (err) { 6017 if (tnum_is_const(reg->var_off)) { 6018 verbose(env, "invalid%s stack %s off=%lld size=%d\n", 6019 err_extra, reg_arg_name(env, argno), min_off, access_size); 6020 } else { 6021 char tn_buf[48]; 6022 6023 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6024 verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n", 6025 err_extra, reg_arg_name(env, argno), tn_buf, off, access_size); 6026 } 6027 return err; 6028 } 6029 6030 /* Note that there is no stack access with offset zero, so the needed stack 6031 * size is -min_off, not -min_off+1. 6032 */ 6033 return grow_stack_state(env, state, -min_off /* size */); 6034 } 6035 6036 static bool get_func_retval_range(struct bpf_prog *prog, 6037 struct bpf_retval_range *range) 6038 { 6039 if (prog->type == BPF_PROG_TYPE_LSM && 6040 prog->expected_attach_type == BPF_LSM_MAC && 6041 !bpf_lsm_get_retval_range(prog, range)) { 6042 return true; 6043 } 6044 return false; 6045 } 6046 6047 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val) 6048 { 6049 struct bpf_reg_state fake_reg; 6050 6051 if (!val) 6052 return; 6053 6054 fake_reg.type = SCALAR_VALUE; 6055 __mark_reg_known(&fake_reg, val); 6056 6057 scalar32_min_max_add(dst_reg, &fake_reg); 6058 scalar_min_max_add(dst_reg, &fake_reg); 6059 dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off); 6060 6061 reg_bounds_sync(dst_reg); 6062 } 6063 6064 /* check whether memory at (regno + off) is accessible for t = (read | write) 6065 * if t==write, value_regno is a register which value is stored into memory 6066 * if t==read, value_regno is a register which will receive the value from memory 6067 * if t==write && value_regno==-1, some unknown value is stored into memory 6068 * if t==read && value_regno==-1, don't care what we read from memory 6069 */ 6070 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 6071 int off, int bpf_size, enum bpf_access_type t, 6072 int value_regno, bool strict_alignment_once, bool is_ldsx) 6073 { 6074 struct bpf_reg_state *regs = cur_regs(env); 6075 int size, err = 0; 6076 6077 size = bpf_size_to_bytes(bpf_size); 6078 if (size < 0) 6079 return size; 6080 6081 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6082 if (err) 6083 return err; 6084 6085 if (reg->type == PTR_TO_MAP_KEY) { 6086 if (t == BPF_WRITE) { 6087 verbose(env, "write to change key %s not allowed\n", 6088 reg_arg_name(env, argno)); 6089 return -EACCES; 6090 } 6091 6092 err = check_mem_region_access(env, reg, argno, off, size, 6093 reg->map_ptr->key_size, false); 6094 if (err) 6095 return err; 6096 if (value_regno >= 0) 6097 mark_reg_unknown(env, regs, value_regno); 6098 } else if (reg->type == PTR_TO_MAP_VALUE) { 6099 struct btf_field *kptr_field = NULL; 6100 6101 if (t == BPF_WRITE && value_regno >= 0 && 6102 is_pointer_value(env, value_regno)) { 6103 verbose(env, "R%d leaks addr into map\n", value_regno); 6104 return -EACCES; 6105 } 6106 err = check_map_access_type(env, reg, off, size, t); 6107 if (err) 6108 return err; 6109 err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT); 6110 if (err) 6111 return err; 6112 if (tnum_is_const(reg->var_off)) 6113 kptr_field = btf_record_find(reg->map_ptr->record, 6114 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 6115 if (kptr_field) { 6116 err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field); 6117 } else if (t == BPF_READ && value_regno >= 0) { 6118 struct bpf_map *map = reg->map_ptr; 6119 6120 /* 6121 * If map is read-only, track its contents as scalars, 6122 * unless it is an insn array (see the special case below) 6123 */ 6124 if (tnum_is_const(reg->var_off) && 6125 bpf_map_is_rdonly(map) && 6126 map->ops->map_direct_value_addr && 6127 map->map_type != BPF_MAP_TYPE_INSN_ARRAY) { 6128 int map_off = off + reg->var_off.value; 6129 u64 val = 0; 6130 6131 err = bpf_map_direct_read(map, map_off, size, 6132 &val, is_ldsx); 6133 if (err) 6134 return err; 6135 6136 regs[value_regno].type = SCALAR_VALUE; 6137 __mark_reg_known(®s[value_regno], val); 6138 } else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 6139 if (bpf_size != BPF_DW) { 6140 verbose(env, "Invalid read of %d bytes from insn_array\n", 6141 size); 6142 return -EACCES; 6143 } 6144 regs[value_regno] = *reg; 6145 add_scalar_to_reg(®s[value_regno], off); 6146 regs[value_regno].type = PTR_TO_INSN; 6147 } else { 6148 mark_reg_unknown(env, regs, value_regno); 6149 } 6150 } 6151 } else if (base_type(reg->type) == PTR_TO_MEM) { 6152 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6153 bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED); 6154 6155 if (type_may_be_null(reg->type)) { 6156 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6157 reg_type_str(env, reg->type)); 6158 return -EACCES; 6159 } 6160 6161 if (t == BPF_WRITE && rdonly_mem) { 6162 verbose(env, "%s cannot write into %s\n", 6163 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6164 return -EACCES; 6165 } 6166 6167 if (t == BPF_WRITE && value_regno >= 0 && 6168 is_pointer_value(env, value_regno)) { 6169 verbose(env, "R%d leaks addr into mem\n", value_regno); 6170 return -EACCES; 6171 } 6172 6173 /* 6174 * Accesses to untrusted PTR_TO_MEM are done through probe 6175 * instructions, hence no need to check bounds in that case. 6176 */ 6177 if (!rdonly_untrusted) 6178 err = check_mem_region_access(env, reg, argno, off, size, 6179 reg->mem_size, false); 6180 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6181 mark_reg_unknown(env, regs, value_regno); 6182 } else if (reg->type == PTR_TO_CTX) { 6183 struct bpf_insn_access_aux info = { 6184 .reg_type = SCALAR_VALUE, 6185 .is_ldsx = is_ldsx, 6186 .log = &env->log, 6187 }; 6188 struct bpf_retval_range range; 6189 6190 if (t == BPF_WRITE && value_regno >= 0 && 6191 is_pointer_value(env, value_regno)) { 6192 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6193 return -EACCES; 6194 } 6195 6196 err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info); 6197 if (!err && t == BPF_READ && value_regno >= 0) { 6198 /* ctx access returns either a scalar, or a 6199 * PTR_TO_PACKET[_META,_END]. In the latter 6200 * case, we know the offset is zero. 6201 */ 6202 if (info.reg_type == SCALAR_VALUE) { 6203 if (info.is_retval && get_func_retval_range(env->prog, &range)) { 6204 mark_reg_unknown(env, regs, value_regno); 6205 err = __mark_reg_s32_range(env, regs, value_regno, 6206 range.minval, range.maxval); 6207 if (err) 6208 return err; 6209 } else { 6210 mark_reg_unknown(env, regs, value_regno); 6211 } 6212 } else { 6213 mark_reg_known_zero(env, regs, 6214 value_regno); 6215 /* A load of ctx field could have different 6216 * actual load size with the one encoded in the 6217 * insn. When the dst is PTR, it is for sure not 6218 * a sub-register. 6219 */ 6220 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6221 if (base_type(info.reg_type) == PTR_TO_BTF_ID) { 6222 regs[value_regno].btf = info.btf; 6223 regs[value_regno].btf_id = info.btf_id; 6224 regs[value_regno].id = info.ref_id; 6225 } 6226 if (type_may_be_null(info.reg_type) && !regs[value_regno].id) 6227 regs[value_regno].id = ++env->id_gen; 6228 } 6229 regs[value_regno].type = info.reg_type; 6230 } 6231 6232 } else if (reg->type == PTR_TO_STACK) { 6233 /* Basic bounds checks. */ 6234 err = check_stack_access_within_bounds(env, reg, argno, off, size, t); 6235 if (err) 6236 return err; 6237 6238 if (t == BPF_READ) 6239 err = check_stack_read(env, reg, argno, off, size, 6240 value_regno); 6241 else 6242 err = check_stack_write(env, reg, off, size, 6243 value_regno, insn_idx); 6244 } else if (reg_is_pkt_pointer(reg)) { 6245 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6246 verbose(env, "cannot write into packet\n"); 6247 return -EACCES; 6248 } 6249 if (t == BPF_WRITE && value_regno >= 0 && 6250 is_pointer_value(env, value_regno)) { 6251 verbose(env, "R%d leaks addr into packet\n", 6252 value_regno); 6253 return -EACCES; 6254 } 6255 err = check_packet_access(env, reg, argno, off, size, false); 6256 if (!err && t == BPF_READ && value_regno >= 0) 6257 mark_reg_unknown(env, regs, value_regno); 6258 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6259 if (t == BPF_WRITE && value_regno >= 0 && 6260 is_pointer_value(env, value_regno)) { 6261 verbose(env, "R%d leaks addr into flow keys\n", 6262 value_regno); 6263 return -EACCES; 6264 } 6265 6266 err = check_flow_keys_access(env, reg, argno, off, size); 6267 if (!err && t == BPF_READ && value_regno >= 0) 6268 mark_reg_unknown(env, regs, value_regno); 6269 } else if (type_is_sk_pointer(reg->type)) { 6270 if (t == BPF_WRITE) { 6271 verbose(env, "%s cannot write into %s\n", 6272 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6273 return -EACCES; 6274 } 6275 err = check_sock_access(env, insn_idx, reg, argno, off, size, t); 6276 if (!err && value_regno >= 0) 6277 mark_reg_unknown(env, regs, value_regno); 6278 } else if (reg->type == PTR_TO_TP_BUFFER) { 6279 err = check_tp_buffer_access(env, reg, argno, off, size); 6280 if (!err && t == BPF_READ && value_regno >= 0) 6281 mark_reg_unknown(env, regs, value_regno); 6282 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6283 !type_may_be_null(reg->type)) { 6284 err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t, 6285 value_regno); 6286 } else if (reg->type == CONST_PTR_TO_MAP) { 6287 err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t, 6288 value_regno); 6289 } else if (base_type(reg->type) == PTR_TO_BUF && 6290 !type_may_be_null(reg->type)) { 6291 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6292 u32 *max_access; 6293 6294 if (rdonly_mem) { 6295 if (t == BPF_WRITE) { 6296 verbose(env, "%s cannot write into %s\n", 6297 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6298 return -EACCES; 6299 } 6300 max_access = &env->prog->aux->max_rdonly_access; 6301 } else { 6302 max_access = &env->prog->aux->max_rdwr_access; 6303 } 6304 6305 err = check_buffer_access(env, reg, argno, off, size, false, 6306 max_access); 6307 6308 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6309 mark_reg_unknown(env, regs, value_regno); 6310 } else if (reg->type == PTR_TO_ARENA) { 6311 if (t == BPF_READ && value_regno >= 0) 6312 mark_reg_unknown(env, regs, value_regno); 6313 } else { 6314 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6315 reg_type_str(env, reg->type)); 6316 return -EACCES; 6317 } 6318 6319 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6320 regs[value_regno].type == SCALAR_VALUE) { 6321 if (!is_ldsx) 6322 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6323 coerce_reg_to_size(®s[value_regno], size); 6324 else 6325 coerce_reg_to_size_sx(®s[value_regno], size); 6326 } 6327 return err; 6328 } 6329 6330 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 6331 bool allow_trust_mismatch); 6332 6333 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn, 6334 bool strict_alignment_once, bool is_ldsx, 6335 bool allow_trust_mismatch, const char *ctx) 6336 { 6337 struct bpf_verifier_state *vstate = env->cur_state; 6338 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6339 struct bpf_reg_state *regs = cur_regs(env); 6340 enum bpf_reg_type src_reg_type; 6341 int err; 6342 6343 /* Handle stack arg read */ 6344 if (is_stack_arg_ldx(insn)) { 6345 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6346 if (err) 6347 return err; 6348 return check_stack_arg_read(env, state, insn->off, insn->dst_reg); 6349 } 6350 6351 /* check src operand */ 6352 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6353 if (err) 6354 return err; 6355 6356 /* check dst operand */ 6357 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6358 if (err) 6359 return err; 6360 6361 src_reg_type = regs[insn->src_reg].type; 6362 6363 /* Check if (src_reg + off) is readable. The state of dst_reg will be 6364 * updated by this call. 6365 */ 6366 err = check_mem_access(env, env->insn_idx, regs + insn->src_reg, argno_from_reg(insn->src_reg), insn->off, 6367 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg, 6368 strict_alignment_once, is_ldsx); 6369 err = err ?: save_aux_ptr_type(env, src_reg_type, 6370 allow_trust_mismatch); 6371 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx); 6372 6373 return err; 6374 } 6375 6376 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn, 6377 bool strict_alignment_once) 6378 { 6379 struct bpf_verifier_state *vstate = env->cur_state; 6380 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6381 struct bpf_reg_state *regs = cur_regs(env); 6382 enum bpf_reg_type dst_reg_type; 6383 int err; 6384 6385 /* Handle stack arg write */ 6386 if (is_stack_arg_stx(insn)) { 6387 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6388 if (err) 6389 return err; 6390 return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg); 6391 } 6392 6393 /* check src1 operand */ 6394 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6395 if (err) 6396 return err; 6397 6398 /* check src2 operand */ 6399 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6400 if (err) 6401 return err; 6402 6403 dst_reg_type = regs[insn->dst_reg].type; 6404 6405 /* Check if (dst_reg + off) is writeable. */ 6406 err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6407 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg, 6408 strict_alignment_once, false); 6409 err = err ?: save_aux_ptr_type(env, dst_reg_type, false); 6410 6411 return err; 6412 } 6413 6414 static int check_atomic_rmw(struct bpf_verifier_env *env, 6415 struct bpf_insn *insn) 6416 { 6417 struct bpf_reg_state *dst_reg; 6418 int load_reg; 6419 int err; 6420 6421 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6422 verbose(env, "invalid atomic operand size\n"); 6423 return -EINVAL; 6424 } 6425 6426 /* check src1 operand */ 6427 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6428 if (err) 6429 return err; 6430 6431 /* check src2 operand */ 6432 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6433 if (err) 6434 return err; 6435 6436 if (insn->imm == BPF_CMPXCHG) { 6437 /* Check comparison of R0 with memory location */ 6438 const u32 aux_reg = BPF_REG_0; 6439 6440 err = check_reg_arg(env, aux_reg, SRC_OP); 6441 if (err) 6442 return err; 6443 6444 if (is_pointer_value(env, aux_reg)) { 6445 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6446 return -EACCES; 6447 } 6448 } 6449 6450 if (is_pointer_value(env, insn->src_reg)) { 6451 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6452 return -EACCES; 6453 } 6454 6455 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6456 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6457 insn->dst_reg, 6458 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6459 return -EACCES; 6460 } 6461 6462 if (insn->imm & BPF_FETCH) { 6463 if (insn->imm == BPF_CMPXCHG) 6464 load_reg = BPF_REG_0; 6465 else 6466 load_reg = insn->src_reg; 6467 6468 /* check and record load of old value */ 6469 err = check_reg_arg(env, load_reg, DST_OP); 6470 if (err) 6471 return err; 6472 } else { 6473 /* This instruction accesses a memory location but doesn't 6474 * actually load it into a register. 6475 */ 6476 load_reg = -1; 6477 } 6478 6479 dst_reg = cur_regs(env) + insn->dst_reg; 6480 6481 /* Check whether we can read the memory, with second call for fetch 6482 * case to simulate the register fill. 6483 */ 6484 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6485 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6486 if (!err && load_reg >= 0) 6487 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), 6488 insn->off, BPF_SIZE(insn->code), 6489 BPF_READ, load_reg, true, false); 6490 if (err) 6491 return err; 6492 6493 if (is_arena_reg(env, insn->dst_reg)) { 6494 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 6495 if (err) 6496 return err; 6497 } 6498 /* Check whether we can write into the same memory. */ 6499 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6500 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6501 if (err) 6502 return err; 6503 return 0; 6504 } 6505 6506 static int check_atomic_load(struct bpf_verifier_env *env, 6507 struct bpf_insn *insn) 6508 { 6509 int err; 6510 6511 err = check_load_mem(env, insn, true, false, false, "atomic_load"); 6512 if (err) 6513 return err; 6514 6515 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) { 6516 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n", 6517 insn->src_reg, 6518 reg_type_str(env, reg_state(env, insn->src_reg)->type)); 6519 return -EACCES; 6520 } 6521 6522 return 0; 6523 } 6524 6525 static int check_atomic_store(struct bpf_verifier_env *env, 6526 struct bpf_insn *insn) 6527 { 6528 int err; 6529 6530 err = check_store_reg(env, insn, true); 6531 if (err) 6532 return err; 6533 6534 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6535 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6536 insn->dst_reg, 6537 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6538 return -EACCES; 6539 } 6540 6541 return 0; 6542 } 6543 6544 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn) 6545 { 6546 switch (insn->imm) { 6547 case BPF_ADD: 6548 case BPF_ADD | BPF_FETCH: 6549 case BPF_AND: 6550 case BPF_AND | BPF_FETCH: 6551 case BPF_OR: 6552 case BPF_OR | BPF_FETCH: 6553 case BPF_XOR: 6554 case BPF_XOR | BPF_FETCH: 6555 case BPF_XCHG: 6556 case BPF_CMPXCHG: 6557 return check_atomic_rmw(env, insn); 6558 case BPF_LOAD_ACQ: 6559 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6560 verbose(env, 6561 "64-bit load-acquires are only supported on 64-bit arches\n"); 6562 return -EOPNOTSUPP; 6563 } 6564 return check_atomic_load(env, insn); 6565 case BPF_STORE_REL: 6566 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6567 verbose(env, 6568 "64-bit store-releases are only supported on 64-bit arches\n"); 6569 return -EOPNOTSUPP; 6570 } 6571 return check_atomic_store(env, insn); 6572 default: 6573 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", 6574 insn->imm); 6575 return -EINVAL; 6576 } 6577 } 6578 6579 /* When register 'regno' is used to read the stack (either directly or through 6580 * a helper function) make sure that it's within stack boundary and, depending 6581 * on the access type and privileges, that all elements of the stack are 6582 * initialized. 6583 * 6584 * All registers that have been spilled on the stack in the slots within the 6585 * read offsets are marked as read. 6586 */ 6587 static int check_stack_range_initialized( 6588 struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 6589 int access_size, bool zero_size_allowed, 6590 enum bpf_access_type type, struct bpf_call_arg_meta *meta) 6591 { 6592 struct bpf_func_state *state = bpf_func(env, reg); 6593 int err, min_off, max_off, i, j, slot, spi; 6594 /* Some accesses can write anything into the stack, others are 6595 * read-only. 6596 */ 6597 bool clobber = type == BPF_WRITE; 6598 /* 6599 * Negative access_size signals global subprog/kfunc arg check where 6600 * STACK_POISON slots are acceptable. static stack liveness 6601 * might have determined that subprog doesn't read them, 6602 * but BTF based global subprog validation isn't accurate enough. 6603 */ 6604 bool allow_poison = access_size < 0 || clobber; 6605 6606 access_size = abs(access_size); 6607 6608 if (access_size == 0 && !zero_size_allowed) { 6609 verbose(env, "invalid zero-sized read\n"); 6610 return -EACCES; 6611 } 6612 6613 err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type); 6614 if (err) 6615 return err; 6616 6617 6618 if (tnum_is_const(reg->var_off)) { 6619 min_off = max_off = reg->var_off.value + off; 6620 } else { 6621 /* Variable offset is prohibited for unprivileged mode for 6622 * simplicity since it requires corresponding support in 6623 * Spectre masking for stack ALU. 6624 * See also retrieve_ptr_limit(). 6625 */ 6626 if (!env->bypass_spec_v1) { 6627 char tn_buf[48]; 6628 6629 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6630 verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n", 6631 reg_arg_name(env, argno), tn_buf); 6632 return -EACCES; 6633 } 6634 /* Only initialized buffer on stack is allowed to be accessed 6635 * with variable offset. With uninitialized buffer it's hard to 6636 * guarantee that whole memory is marked as initialized on 6637 * helper return since specific bounds are unknown what may 6638 * cause uninitialized stack leaking. 6639 */ 6640 if (meta && meta->raw_mode) 6641 meta = NULL; 6642 6643 min_off = reg_smin(reg) + off; 6644 max_off = reg_smax(reg) + off; 6645 } 6646 6647 if (meta && meta->raw_mode) { 6648 /* Ensure we won't be overwriting dynptrs when simulating byte 6649 * by byte access in check_helper_call using meta.access_size. 6650 * This would be a problem if we have a helper in the future 6651 * which takes: 6652 * 6653 * helper(uninit_mem, len, dynptr) 6654 * 6655 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 6656 * may end up writing to dynptr itself when touching memory from 6657 * arg 1. This can be relaxed on a case by case basis for known 6658 * safe cases, but reject due to the possibilitiy of aliasing by 6659 * default. 6660 */ 6661 for (i = min_off; i < max_off + access_size; i++) { 6662 int stack_off = -i - 1; 6663 6664 spi = bpf_get_spi(i); 6665 /* raw_mode may write past allocated_stack */ 6666 if (state->allocated_stack <= stack_off) 6667 continue; 6668 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 6669 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 6670 return -EACCES; 6671 } 6672 } 6673 meta->access_size = access_size; 6674 meta->regno = reg_from_argno(argno); 6675 return 0; 6676 } 6677 6678 for (i = min_off; i < max_off + access_size; i++) { 6679 u8 *stype; 6680 6681 slot = -i - 1; 6682 spi = slot / BPF_REG_SIZE; 6683 if (state->allocated_stack <= slot) { 6684 verbose(env, "allocated_stack too small\n"); 6685 return -EFAULT; 6686 } 6687 6688 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 6689 if (*stype == STACK_MISC) 6690 goto mark; 6691 if ((*stype == STACK_ZERO) || 6692 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 6693 if (clobber) { 6694 /* helper can write anything into the stack */ 6695 *stype = STACK_MISC; 6696 } 6697 goto mark; 6698 } 6699 6700 if (bpf_is_spilled_reg(&state->stack[spi]) && 6701 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 6702 env->allow_ptr_leaks)) { 6703 if (clobber) { 6704 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 6705 for (j = 0; j < BPF_REG_SIZE; j++) 6706 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 6707 } 6708 goto mark; 6709 } 6710 6711 if (*stype == STACK_POISON) { 6712 if (allow_poison) 6713 goto mark; 6714 verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n", 6715 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6716 } else if (tnum_is_const(reg->var_off)) { 6717 verbose(env, "invalid read from stack %s off %d+%d size %d\n", 6718 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6719 } else { 6720 char tn_buf[48]; 6721 6722 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6723 verbose(env, "invalid read from stack %s var_off %s+%d size %d\n", 6724 reg_arg_name(env, argno), tn_buf, i - min_off, access_size); 6725 } 6726 return -EACCES; 6727 mark: 6728 ; 6729 } 6730 return 0; 6731 } 6732 6733 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 6734 int access_size, enum bpf_access_type access_type, 6735 bool zero_size_allowed, 6736 struct bpf_call_arg_meta *meta) 6737 { 6738 struct bpf_reg_state *regs = cur_regs(env); 6739 u32 *max_access; 6740 6741 switch (base_type(reg->type)) { 6742 case PTR_TO_PACKET: 6743 case PTR_TO_PACKET_META: 6744 return check_packet_access(env, reg, argno, 0, access_size, 6745 zero_size_allowed); 6746 case PTR_TO_MAP_KEY: 6747 if (access_type == BPF_WRITE) { 6748 verbose(env, "%s cannot write into %s\n", 6749 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6750 return -EACCES; 6751 } 6752 return check_mem_region_access(env, reg, argno, 0, access_size, 6753 reg->map_ptr->key_size, false); 6754 case PTR_TO_MAP_VALUE: 6755 if (check_map_access_type(env, reg, 0, access_size, access_type)) 6756 return -EACCES; 6757 return check_map_access(env, reg, argno, 0, access_size, 6758 zero_size_allowed, ACCESS_HELPER); 6759 case PTR_TO_MEM: 6760 if (type_is_rdonly_mem(reg->type)) { 6761 if (access_type == BPF_WRITE) { 6762 verbose(env, "%s cannot write into %s\n", 6763 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6764 return -EACCES; 6765 } 6766 } 6767 return check_mem_region_access(env, reg, argno, 0, 6768 access_size, reg->mem_size, 6769 zero_size_allowed); 6770 case PTR_TO_BUF: 6771 if (type_is_rdonly_mem(reg->type)) { 6772 if (access_type == BPF_WRITE) { 6773 verbose(env, "%s cannot write into %s\n", 6774 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6775 return -EACCES; 6776 } 6777 6778 max_access = &env->prog->aux->max_rdonly_access; 6779 } else { 6780 max_access = &env->prog->aux->max_rdwr_access; 6781 } 6782 return check_buffer_access(env, reg, argno, 0, 6783 access_size, zero_size_allowed, 6784 max_access); 6785 case PTR_TO_STACK: 6786 return check_stack_range_initialized( 6787 env, reg, 6788 argno, 0, access_size, 6789 zero_size_allowed, access_type, meta); 6790 case PTR_TO_BTF_ID: 6791 return check_ptr_to_btf_access(env, regs, reg, argno, 0, 6792 access_size, access_type, -1); 6793 case PTR_TO_CTX: 6794 /* Only permit reading or writing syscall context using helper calls. */ 6795 if (is_var_ctx_off_allowed(env->prog)) { 6796 int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX, 6797 zero_size_allowed); 6798 if (err) 6799 return err; 6800 if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size) 6801 env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size; 6802 return 0; 6803 } 6804 fallthrough; 6805 default: /* scalar_value or invalid ptr */ 6806 /* Allow zero-byte read from NULL, regardless of pointer type */ 6807 if (zero_size_allowed && access_size == 0 && 6808 bpf_register_is_null(reg)) 6809 return 0; 6810 6811 verbose(env, "%s type=%s ", reg_arg_name(env, argno), 6812 reg_type_str(env, reg->type)); 6813 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 6814 return -EACCES; 6815 } 6816 } 6817 6818 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 6819 * size. 6820 * 6821 * @mem_reg contains the pointer, @size_reg contains the access size. 6822 */ 6823 static int check_mem_size_reg(struct bpf_verifier_env *env, 6824 struct bpf_reg_state *mem_reg, 6825 struct bpf_reg_state *size_reg, argno_t mem_argno, 6826 argno_t size_argno, enum bpf_access_type access_type, 6827 bool zero_size_allowed, 6828 struct bpf_call_arg_meta *meta) 6829 { 6830 int err; 6831 6832 /* This is used to refine r0 return value bounds for helpers 6833 * that enforce this value as an upper bound on return values. 6834 * See do_refine_retval_range() for helpers that can refine 6835 * the return value. C type of helper is u32 so we pull register 6836 * bound from umax_value however, if negative verifier errors 6837 * out. Only upper bounds can be learned because retval is an 6838 * int type and negative retvals are allowed. 6839 */ 6840 meta->msize_max_value = reg_umax(size_reg); 6841 6842 /* The register is SCALAR_VALUE; the access check happens using 6843 * its boundaries. For unprivileged variable accesses, disable 6844 * raw mode so that the program is required to initialize all 6845 * the memory that the helper could just partially fill up. 6846 */ 6847 if (!tnum_is_const(size_reg->var_off)) 6848 meta = NULL; 6849 6850 if (reg_smin(size_reg) < 0) { 6851 verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n", 6852 reg_arg_name(env, size_argno)); 6853 return -EACCES; 6854 } 6855 6856 if (reg_umin(size_reg) == 0 && !zero_size_allowed) { 6857 verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n", 6858 reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg)); 6859 return -EACCES; 6860 } 6861 6862 if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) { 6863 verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 6864 reg_arg_name(env, size_argno)); 6865 return -EACCES; 6866 } 6867 err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg), 6868 access_type, zero_size_allowed, meta); 6869 if (!err) { 6870 int regno = reg_from_argno(size_argno); 6871 6872 if (regno >= 0) 6873 err = mark_chain_precision(env, regno); 6874 else 6875 err = mark_stack_arg_precision(env, arg_idx_from_argno(size_argno)); 6876 } 6877 return err; 6878 } 6879 6880 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6881 argno_t argno, u32 mem_size) 6882 { 6883 bool may_be_null = type_may_be_null(reg->type); 6884 struct bpf_reg_state saved_reg; 6885 int err; 6886 6887 if (bpf_register_is_null(reg)) 6888 return 0; 6889 6890 if (mem_size > S32_MAX) { 6891 verbose(env, "%s memory size %u is too large\n", 6892 reg_arg_name(env, argno), mem_size); 6893 return -EACCES; 6894 } 6895 6896 /* Assuming that the register contains a value check if the memory 6897 * access is safe. Temporarily save and restore the register's state as 6898 * the conversion shouldn't be visible to a caller. 6899 */ 6900 if (may_be_null) { 6901 saved_reg = *reg; 6902 mark_ptr_not_null_reg(reg); 6903 } 6904 6905 int size = base_type(reg->type) == PTR_TO_STACK ? -(int)mem_size : mem_size; 6906 6907 err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, NULL); 6908 err = err ?: check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, NULL); 6909 6910 if (may_be_null) 6911 *reg = saved_reg; 6912 6913 return err; 6914 } 6915 6916 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *mem_reg, 6917 struct bpf_reg_state *size_reg, argno_t mem_argno, argno_t size_argno) 6918 { 6919 bool may_be_null = type_may_be_null(mem_reg->type); 6920 struct bpf_reg_state saved_reg; 6921 struct bpf_call_arg_meta meta; 6922 int err; 6923 6924 memset(&meta, 0, sizeof(meta)); 6925 6926 if (may_be_null) { 6927 saved_reg = *mem_reg; 6928 mark_ptr_not_null_reg(mem_reg); 6929 } 6930 6931 err = check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_READ, true, &meta); 6932 err = err ?: check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_WRITE, true, &meta); 6933 6934 if (may_be_null) 6935 *mem_reg = saved_reg; 6936 6937 return err; 6938 } 6939 6940 enum { 6941 PROCESS_SPIN_LOCK = (1 << 0), 6942 PROCESS_RES_LOCK = (1 << 1), 6943 PROCESS_LOCK_IRQ = (1 << 2), 6944 }; 6945 6946 /* Implementation details: 6947 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 6948 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 6949 * Two bpf_map_lookups (even with the same key) will have different reg->id. 6950 * Two separate bpf_obj_new will also have different reg->id. 6951 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 6952 * clears reg->id after value_or_null->value transition, since the verifier only 6953 * cares about the range of access to valid map value pointer and doesn't care 6954 * about actual address of the map element. 6955 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 6956 * reg->id > 0 after value_or_null->value transition. By doing so 6957 * two bpf_map_lookups will be considered two different pointers that 6958 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 6959 * returned from bpf_obj_new. 6960 * The verifier allows taking only one bpf_spin_lock at a time to avoid 6961 * dead-locks. 6962 * Since only one bpf_spin_lock is allowed the checks are simpler than 6963 * reg_is_refcounted() logic. The verifier needs to remember only 6964 * one spin_lock instead of array of acquired_refs. 6965 * env->cur_state->active_locks remembers which map value element or allocated 6966 * object got locked and clears it after bpf_spin_unlock. 6967 */ 6968 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags) 6969 { 6970 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK; 6971 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin"; 6972 struct bpf_verifier_state *cur = env->cur_state; 6973 bool is_const = tnum_is_const(reg->var_off); 6974 bool is_irq = flags & PROCESS_LOCK_IRQ; 6975 u64 val = reg->var_off.value; 6976 struct bpf_map *map = NULL; 6977 struct btf *btf = NULL; 6978 struct btf_record *rec; 6979 u32 spin_lock_off; 6980 int err; 6981 6982 if (!is_const) { 6983 verbose(env, 6984 "%s doesn't have constant offset. %s_lock has to be at the constant offset\n", 6985 reg_arg_name(env, argno), lock_str); 6986 return -EINVAL; 6987 } 6988 if (reg->type == PTR_TO_MAP_VALUE) { 6989 map = reg->map_ptr; 6990 if (!map->btf) { 6991 verbose(env, 6992 "map '%s' has to have BTF in order to use %s_lock\n", 6993 map->name, lock_str); 6994 return -EINVAL; 6995 } 6996 } else { 6997 btf = reg->btf; 6998 } 6999 7000 rec = reg_btf_record(reg); 7001 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) { 7002 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local", 7003 map ? map->name : "kptr", lock_str); 7004 return -EINVAL; 7005 } 7006 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off; 7007 if (spin_lock_off != val) { 7008 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n", 7009 val, lock_str, spin_lock_off); 7010 return -EINVAL; 7011 } 7012 if (is_lock) { 7013 void *ptr; 7014 int type; 7015 7016 if (map) 7017 ptr = map; 7018 else 7019 ptr = btf; 7020 7021 if (!is_res_lock && cur->active_locks) { 7022 if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) { 7023 verbose(env, 7024 "Locking two bpf_spin_locks are not allowed\n"); 7025 return -EINVAL; 7026 } 7027 } else if (is_res_lock && cur->active_locks) { 7028 if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) { 7029 verbose(env, "Acquiring the same lock again, AA deadlock detected\n"); 7030 return -EINVAL; 7031 } 7032 } 7033 7034 if (is_res_lock && is_irq) 7035 type = REF_TYPE_RES_LOCK_IRQ; 7036 else if (is_res_lock) 7037 type = REF_TYPE_RES_LOCK; 7038 else 7039 type = REF_TYPE_LOCK; 7040 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr); 7041 if (err < 0) { 7042 verbose(env, "Failed to acquire lock state\n"); 7043 return err; 7044 } 7045 } else { 7046 void *ptr; 7047 int type; 7048 7049 if (map) 7050 ptr = map; 7051 else 7052 ptr = btf; 7053 7054 if (!cur->active_locks) { 7055 verbose(env, "%s_unlock without taking a lock\n", lock_str); 7056 return -EINVAL; 7057 } 7058 7059 if (is_res_lock && is_irq) 7060 type = REF_TYPE_RES_LOCK_IRQ; 7061 else if (is_res_lock) 7062 type = REF_TYPE_RES_LOCK; 7063 else 7064 type = REF_TYPE_LOCK; 7065 if (!find_lock_state(cur, type, reg->id, ptr)) { 7066 verbose(env, "%s_unlock of different lock\n", lock_str); 7067 return -EINVAL; 7068 } 7069 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) { 7070 verbose(env, "%s_unlock cannot be out of order\n", lock_str); 7071 return -EINVAL; 7072 } 7073 if (release_lock_state(cur, type, reg->id, ptr)) { 7074 verbose(env, "%s_unlock of different lock\n", lock_str); 7075 return -EINVAL; 7076 } 7077 7078 invalidate_non_owning_refs(env); 7079 } 7080 return 0; 7081 } 7082 7083 /* Check if @regno is a pointer to a specific field in a map value */ 7084 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7085 enum btf_field_type field_type, 7086 struct bpf_map_desc *map_desc) 7087 { 7088 bool is_const = tnum_is_const(reg->var_off); 7089 struct bpf_map *map = reg->map_ptr; 7090 u64 val = reg->var_off.value; 7091 const char *struct_name = btf_field_type_name(field_type); 7092 int field_off = -1; 7093 7094 if (!is_const) { 7095 verbose(env, 7096 "%s doesn't have constant offset. %s has to be at the constant offset\n", 7097 reg_arg_name(env, argno), struct_name); 7098 return -EINVAL; 7099 } 7100 if (!map->btf) { 7101 verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name, 7102 struct_name); 7103 return -EINVAL; 7104 } 7105 if (!btf_record_has_field(map->record, field_type)) { 7106 verbose(env, "map '%s' has no valid %s\n", map->name, struct_name); 7107 return -EINVAL; 7108 } 7109 switch (field_type) { 7110 case BPF_TIMER: 7111 field_off = map->record->timer_off; 7112 break; 7113 case BPF_TASK_WORK: 7114 field_off = map->record->task_work_off; 7115 break; 7116 case BPF_WORKQUEUE: 7117 field_off = map->record->wq_off; 7118 break; 7119 default: 7120 verifier_bug(env, "unsupported BTF field type: %s\n", struct_name); 7121 return -EINVAL; 7122 } 7123 if (field_off != val) { 7124 verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n", 7125 val, struct_name, field_off); 7126 return -EINVAL; 7127 } 7128 if (map_desc->ptr) { 7129 verifier_bug(env, "Two map pointers in a %s helper", struct_name); 7130 return -EFAULT; 7131 } 7132 map_desc->uid = reg->map_uid; 7133 map_desc->ptr = map; 7134 return 0; 7135 } 7136 7137 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7138 struct bpf_map_desc *map) 7139 { 7140 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 7141 verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n"); 7142 return -EOPNOTSUPP; 7143 } 7144 return check_map_field_pointer(env, reg, argno, BPF_TIMER, map); 7145 } 7146 7147 static int process_timer_helper(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7148 struct bpf_call_arg_meta *meta) 7149 { 7150 return process_timer_func(env, reg, argno, &meta->map); 7151 } 7152 7153 static int process_timer_kfunc(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7154 struct bpf_kfunc_call_arg_meta *meta) 7155 { 7156 return process_timer_func(env, reg, argno, &meta->map); 7157 } 7158 7159 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7160 struct bpf_call_arg_meta *meta) 7161 { 7162 struct bpf_reg_state *reg = reg_state(env, regno); 7163 struct btf_field *kptr_field; 7164 struct bpf_map *map_ptr; 7165 struct btf_record *rec; 7166 u32 kptr_off; 7167 7168 if (type_is_ptr_alloc_obj(reg->type)) { 7169 rec = reg_btf_record(reg); 7170 } else { /* PTR_TO_MAP_VALUE */ 7171 map_ptr = reg->map_ptr; 7172 if (!map_ptr->btf) { 7173 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7174 map_ptr->name); 7175 return -EINVAL; 7176 } 7177 rec = map_ptr->record; 7178 meta->map.ptr = map_ptr; 7179 } 7180 7181 if (!tnum_is_const(reg->var_off)) { 7182 verbose(env, 7183 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7184 regno); 7185 return -EINVAL; 7186 } 7187 7188 if (!btf_record_has_field(rec, BPF_KPTR)) { 7189 verbose(env, "R%d has no valid kptr\n", regno); 7190 return -EINVAL; 7191 } 7192 7193 kptr_off = reg->var_off.value; 7194 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 7195 if (!kptr_field) { 7196 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7197 return -EACCES; 7198 } 7199 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7200 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7201 return -EACCES; 7202 } 7203 meta->kptr_field = kptr_field; 7204 return 0; 7205 } 7206 7207 /* 7208 * Validate dynptr arguments for helper, kfunc and subprog. 7209 * 7210 * @dynptr is both input and output. It is populated when the argument is 7211 * tagged with MEM_UNINIT (i.e., the dynptr argument that will be constructed) 7212 * and consumed when the argument is expecting to be an initialized dynptr. 7213 * @parent_id is used to track the referenced parent object (e.g., file or skb in 7214 * qdisc program) when constructing a dynptr. 7215 * 7216 * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7217 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7218 * 7219 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7220 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7221 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7222 * 7223 * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the 7224 * dynptr points to. At the first level, the verifier will make sure a 7225 * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of 7226 * a dynptr's view (i.e., start and offset) is not tracked as there is not such 7227 * use case. The second level is tracked using the upper bit of bpf_dynptr->size 7228 * and checked dynamically during runtime. 7229 */ 7230 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7231 argno_t argno, int insn_idx, enum bpf_arg_type arg_type, 7232 struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr) 7233 { 7234 int spi, err = 0; 7235 7236 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 7237 verbose(env, 7238 "%s expected pointer to stack or const struct bpf_dynptr\n", 7239 reg_arg_name(env, argno)); 7240 return -EINVAL; 7241 } 7242 7243 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7244 * constructing a mutable bpf_dynptr object. 7245 * 7246 * Currently, this is only possible with PTR_TO_STACK 7247 * pointing to a region of at least 16 bytes which doesn't 7248 * contain an existing bpf_dynptr. 7249 * 7250 * OBJ_RELEASE - Points to a initialized bpf_dynptr that will be 7251 * destroyed. 7252 * 7253 * None - Points to a initialized dynptr that cannot be 7254 * reinitialized or destroyed. However, the view of the 7255 * dynptr and the memory it points to may be mutated. 7256 */ 7257 if (arg_type & MEM_UNINIT) { 7258 int i; 7259 7260 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7261 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7262 return -EINVAL; 7263 } 7264 7265 /* we write BPF_DW bits (8 bytes) at a time */ 7266 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7267 err = check_mem_access(env, insn_idx, reg, argno, 7268 i, BPF_DW, BPF_WRITE, -1, false, false); 7269 if (err) 7270 return err; 7271 } 7272 7273 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, ref_obj, dynptr); 7274 } else /* OBJ_RELEASE and None case from above */ { 7275 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7276 if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) { 7277 verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n"); 7278 return -EINVAL; 7279 } 7280 7281 if (!is_dynptr_reg_valid_init(env, reg)) { 7282 verbose(env, "Expected an initialized dynptr as %s\n", 7283 reg_arg_name(env, argno)); 7284 return -EINVAL; 7285 } 7286 7287 /* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */ 7288 if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) { 7289 verbose(env, 7290 "Expected a dynptr of type %s as %s\n", 7291 dynptr_type_str(arg_to_dynptr_type(arg_type)), 7292 reg_arg_name(env, argno)); 7293 return -EINVAL; 7294 } 7295 7296 if (reg->type != CONST_PTR_TO_DYNPTR) { 7297 struct bpf_func_state *state = bpf_func(env, reg); 7298 7299 spi = dynptr_get_spi(env, reg); 7300 if (spi < 0) 7301 return spi; 7302 7303 /* 7304 * For CONST_PTR_TO_DYNPTR, reg is already scratched by check_reg_arg 7305 * in check_helper_call and mark_btf_func_reg_size in check_kfunc_call. 7306 */ 7307 mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS); 7308 7309 reg = &state->stack[spi].spilled_ptr; 7310 } 7311 7312 if (dynptr) { 7313 dynptr->type = reg->dynptr.type; 7314 dynptr->id = reg->id; 7315 dynptr->parent_id = reg->parent_id; 7316 } 7317 } 7318 return err; 7319 } 7320 7321 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7322 { 7323 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7324 } 7325 7326 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7327 { 7328 return meta->kfunc_flags & KF_ITER_NEW; 7329 } 7330 7331 7332 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7333 { 7334 return meta->kfunc_flags & KF_ITER_DESTROY; 7335 } 7336 7337 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 7338 const struct btf_param *arg) 7339 { 7340 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7341 * kfunc is iter state pointer 7342 */ 7343 if (is_iter_kfunc(meta)) 7344 return arg_idx == 0; 7345 7346 /* iter passed as an argument to a generic kfunc */ 7347 return btf_param_match_suffix(meta->btf, arg, "__iter"); 7348 } 7349 7350 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx, 7351 struct bpf_kfunc_call_arg_meta *meta) 7352 { 7353 struct bpf_func_state *state = bpf_func(env, reg); 7354 const struct btf_type *t; 7355 u32 arg_idx = arg_idx_from_argno(argno); 7356 int spi, err, i, nr_slots, btf_id; 7357 7358 if (reg->type != PTR_TO_STACK) { 7359 verbose(env, "%s expected pointer to an iterator on stack\n", 7360 reg_arg_name(env, argno)); 7361 return -EINVAL; 7362 } 7363 7364 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 7365 * ensures struct convention, so we wouldn't need to do any BTF 7366 * validation here. But given iter state can be passed as a parameter 7367 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 7368 * conservative here. 7369 */ 7370 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg_idx); 7371 if (btf_id < 0) { 7372 verbose(env, "expected valid iter pointer as %s\n", 7373 reg_arg_name(env, argno)); 7374 return -EINVAL; 7375 } 7376 t = btf_type_by_id(meta->btf, btf_id); 7377 nr_slots = t->size / BPF_REG_SIZE; 7378 7379 if (is_iter_new_kfunc(meta)) { 7380 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7381 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7382 verbose(env, "expected uninitialized iter_%s as %s\n", 7383 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7384 return -EINVAL; 7385 } 7386 7387 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7388 err = check_mem_access(env, insn_idx, reg, argno, 7389 i, BPF_DW, BPF_WRITE, -1, false, false); 7390 if (err) 7391 return err; 7392 } 7393 7394 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7395 if (err) 7396 return err; 7397 } else { 7398 /* iter_next() or iter_destroy(), as well as any kfunc 7399 * accepting iter argument, expect initialized iter state 7400 */ 7401 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7402 switch (err) { 7403 case 0: 7404 break; 7405 case -EINVAL: 7406 verbose(env, "expected an initialized iter_%s as %s\n", 7407 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7408 return err; 7409 case -EPROTO: 7410 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7411 return err; 7412 default: 7413 return err; 7414 } 7415 7416 spi = iter_get_spi(env, reg, nr_slots); 7417 if (spi < 0) 7418 return spi; 7419 7420 mark_stack_slots_scratched(env, spi, nr_slots); 7421 7422 /* remember meta->iter info for process_iter_next_call() */ 7423 meta->iter.spi = spi; 7424 meta->iter.frameno = reg->frameno; 7425 update_ref_obj(&meta->ref_obj, &state->stack[spi].spilled_ptr); 7426 7427 if (is_iter_destroy_kfunc(meta)) { 7428 err = unmark_stack_slots_iter(env, reg, nr_slots); 7429 if (err) 7430 return err; 7431 } 7432 } 7433 7434 return 0; 7435 } 7436 7437 /* Look for a previous loop entry at insn_idx: nearest parent state 7438 * stopped at insn_idx with callsites matching those in cur->frame. 7439 */ 7440 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7441 struct bpf_verifier_state *cur, 7442 int insn_idx) 7443 { 7444 struct bpf_verifier_state_list *sl; 7445 struct bpf_verifier_state *st; 7446 struct list_head *pos, *head; 7447 7448 /* Explored states are pushed in stack order, most recent states come first */ 7449 head = bpf_explored_state(env, insn_idx); 7450 list_for_each(pos, head) { 7451 sl = container_of(pos, struct bpf_verifier_state_list, node); 7452 /* If st->branches != 0 state is a part of current DFS verification path, 7453 * hence cur & st for a loop. 7454 */ 7455 st = &sl->state; 7456 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7457 st->dfs_depth < cur->dfs_depth) 7458 return st; 7459 } 7460 7461 return NULL; 7462 } 7463 7464 /* 7465 * Check if scalar registers are exact for the purpose of not widening. 7466 * More lenient than regs_exact() 7467 */ 7468 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold, 7469 const struct bpf_reg_state *rcur) 7470 { 7471 return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)); 7472 } 7473 7474 static void maybe_widen_reg(struct bpf_verifier_env *env, 7475 struct bpf_reg_state *rold, struct bpf_reg_state *rcur) 7476 { 7477 if (rold->type != SCALAR_VALUE) 7478 return; 7479 if (rold->type != rcur->type) 7480 return; 7481 if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur)) 7482 return; 7483 __mark_reg_unknown(env, rcur); 7484 } 7485 7486 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7487 struct bpf_verifier_state *old, 7488 struct bpf_verifier_state *cur) 7489 { 7490 struct bpf_func_state *fold, *fcur; 7491 int i, fr, num_slots; 7492 7493 for (fr = old->curframe; fr >= 0; fr--) { 7494 fold = old->frame[fr]; 7495 fcur = cur->frame[fr]; 7496 7497 for (i = 0; i < MAX_BPF_REG; i++) 7498 maybe_widen_reg(env, 7499 &fold->regs[i], 7500 &fcur->regs[i]); 7501 7502 num_slots = min(fold->allocated_stack / BPF_REG_SIZE, 7503 fcur->allocated_stack / BPF_REG_SIZE); 7504 for (i = 0; i < num_slots; i++) { 7505 if (!bpf_is_spilled_reg(&fold->stack[i]) || 7506 !bpf_is_spilled_reg(&fcur->stack[i])) 7507 continue; 7508 7509 maybe_widen_reg(env, 7510 &fold->stack[i].spilled_ptr, 7511 &fcur->stack[i].spilled_ptr); 7512 } 7513 } 7514 return 0; 7515 } 7516 7517 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 7518 struct bpf_kfunc_call_arg_meta *meta) 7519 { 7520 int iter_frameno = meta->iter.frameno; 7521 int iter_spi = meta->iter.spi; 7522 7523 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7524 } 7525 7526 /* process_iter_next_call() is called when verifier gets to iterator's next 7527 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7528 * to it as just "iter_next()" in comments below. 7529 * 7530 * BPF verifier relies on a crucial contract for any iter_next() 7531 * implementation: it should *eventually* return NULL, and once that happens 7532 * it should keep returning NULL. That is, once iterator exhausts elements to 7533 * iterate, it should never reset or spuriously return new elements. 7534 * 7535 * With the assumption of such contract, process_iter_next_call() simulates 7536 * a fork in the verifier state to validate loop logic correctness and safety 7537 * without having to simulate infinite amount of iterations. 7538 * 7539 * In current state, we first assume that iter_next() returned NULL and 7540 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7541 * conditions we should not form an infinite loop and should eventually reach 7542 * exit. 7543 * 7544 * Besides that, we also fork current state and enqueue it for later 7545 * verification. In a forked state we keep iterator state as ACTIVE 7546 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7547 * also bump iteration depth to prevent erroneous infinite loop detection 7548 * later on (see iter_active_depths_differ() comment for details). In this 7549 * state we assume that we'll eventually loop back to another iter_next() 7550 * calls (it could be in exactly same location or in some other instruction, 7551 * it doesn't matter, we don't make any unnecessary assumptions about this, 7552 * everything revolves around iterator state in a stack slot, not which 7553 * instruction is calling iter_next()). When that happens, we either will come 7554 * to iter_next() with equivalent state and can conclude that next iteration 7555 * will proceed in exactly the same way as we just verified, so it's safe to 7556 * assume that loop converges. If not, we'll go on another iteration 7557 * simulation with a different input state, until all possible starting states 7558 * are validated or we reach maximum number of instructions limit. 7559 * 7560 * This way, we will either exhaustively discover all possible input states 7561 * that iterator loop can start with and eventually will converge, or we'll 7562 * effectively regress into bounded loop simulation logic and either reach 7563 * maximum number of instructions if loop is not provably convergent, or there 7564 * is some statically known limit on number of iterations (e.g., if there is 7565 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7566 * 7567 * Iteration convergence logic in is_state_visited() relies on exact 7568 * states comparison, which ignores read and precision marks. 7569 * This is necessary because read and precision marks are not finalized 7570 * while in the loop. Exact comparison might preclude convergence for 7571 * simple programs like below: 7572 * 7573 * i = 0; 7574 * while(iter_next(&it)) 7575 * i++; 7576 * 7577 * At each iteration step i++ would produce a new distinct state and 7578 * eventually instruction processing limit would be reached. 7579 * 7580 * To avoid such behavior speculatively forget (widen) range for 7581 * imprecise scalar registers, if those registers were not precise at the 7582 * end of the previous iteration and do not match exactly. 7583 * 7584 * This is a conservative heuristic that allows to verify wide range of programs, 7585 * however it precludes verification of programs that conjure an 7586 * imprecise value on the first loop iteration and use it as precise on a second. 7587 * For example, the following safe program would fail to verify: 7588 * 7589 * struct bpf_num_iter it; 7590 * int arr[10]; 7591 * int i = 0, a = 0; 7592 * bpf_iter_num_new(&it, 0, 10); 7593 * while (bpf_iter_num_next(&it)) { 7594 * if (a == 0) { 7595 * a = 1; 7596 * i = 7; // Because i changed verifier would forget 7597 * // it's range on second loop entry. 7598 * } else { 7599 * arr[i] = 42; // This would fail to verify. 7600 * } 7601 * } 7602 * bpf_iter_num_destroy(&it); 7603 */ 7604 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7605 struct bpf_kfunc_call_arg_meta *meta) 7606 { 7607 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7608 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7609 struct bpf_reg_state *cur_iter, *queued_iter; 7610 7611 BTF_TYPE_EMIT(struct bpf_iter); 7612 7613 cur_iter = get_iter_from_state(cur_st, meta); 7614 7615 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7616 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7617 verifier_bug(env, "unexpected iterator state %d (%s)", 7618 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7619 return -EFAULT; 7620 } 7621 7622 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7623 /* Because iter_next() call is a checkpoint is_state_visitied() 7624 * should guarantee parent state with same call sites and insn_idx. 7625 */ 7626 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7627 !same_callsites(cur_st->parent, cur_st)) { 7628 verifier_bug(env, "bad parent state for iter next call"); 7629 return -EFAULT; 7630 } 7631 /* Note cur_st->parent in the call below, it is necessary to skip 7632 * checkpoint created for cur_st by is_state_visited() 7633 * right at this instruction. 7634 */ 7635 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7636 /* branch out active iter state */ 7637 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7638 if (IS_ERR(queued_st)) 7639 return PTR_ERR(queued_st); 7640 7641 queued_iter = get_iter_from_state(queued_st, meta); 7642 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7643 queued_iter->iter.depth++; 7644 if (prev_st) 7645 widen_imprecise_scalars(env, prev_st, queued_st); 7646 7647 queued_fr = queued_st->frame[queued_st->curframe]; 7648 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7649 } 7650 7651 /* switch to DRAINED state, but keep the depth unchanged */ 7652 /* mark current iter state as drained and assume returned NULL */ 7653 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7654 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7655 7656 return 0; 7657 } 7658 7659 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7660 { 7661 return type == ARG_CONST_SIZE || 7662 type == ARG_CONST_SIZE_OR_ZERO; 7663 } 7664 7665 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 7666 { 7667 return base_type(type) == ARG_PTR_TO_MEM && 7668 type & MEM_UNINIT; 7669 } 7670 7671 static bool arg_type_is_release(enum bpf_arg_type type) 7672 { 7673 return type & OBJ_RELEASE; 7674 } 7675 7676 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7677 { 7678 return base_type(type) == ARG_PTR_TO_DYNPTR; 7679 } 7680 7681 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7682 const struct bpf_call_arg_meta *meta, 7683 enum bpf_arg_type *arg_type) 7684 { 7685 if (!meta->map.ptr) { 7686 /* kernel subsystem misconfigured verifier */ 7687 verifier_bug(env, "invalid map_ptr to access map->type"); 7688 return -EFAULT; 7689 } 7690 7691 switch (meta->map.ptr->map_type) { 7692 case BPF_MAP_TYPE_SOCKMAP: 7693 case BPF_MAP_TYPE_SOCKHASH: 7694 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7695 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7696 } else { 7697 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7698 return -EINVAL; 7699 } 7700 break; 7701 case BPF_MAP_TYPE_BLOOM_FILTER: 7702 if (meta->func_id == BPF_FUNC_map_peek_elem) 7703 *arg_type = ARG_PTR_TO_MAP_VALUE; 7704 break; 7705 default: 7706 break; 7707 } 7708 return 0; 7709 } 7710 7711 struct bpf_reg_types { 7712 const enum bpf_reg_type types[10]; 7713 u32 *btf_id; 7714 }; 7715 7716 static const struct bpf_reg_types sock_types = { 7717 .types = { 7718 PTR_TO_SOCK_COMMON, 7719 PTR_TO_SOCKET, 7720 PTR_TO_TCP_SOCK, 7721 PTR_TO_XDP_SOCK, 7722 }, 7723 }; 7724 7725 #ifdef CONFIG_NET 7726 static const struct bpf_reg_types btf_id_sock_common_types = { 7727 .types = { 7728 PTR_TO_SOCK_COMMON, 7729 PTR_TO_SOCKET, 7730 PTR_TO_TCP_SOCK, 7731 PTR_TO_XDP_SOCK, 7732 PTR_TO_BTF_ID, 7733 PTR_TO_BTF_ID | PTR_TRUSTED, 7734 }, 7735 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7736 }; 7737 #endif 7738 7739 static const struct bpf_reg_types mem_types = { 7740 .types = { 7741 PTR_TO_STACK, 7742 PTR_TO_PACKET, 7743 PTR_TO_PACKET_META, 7744 PTR_TO_MAP_KEY, 7745 PTR_TO_MAP_VALUE, 7746 PTR_TO_MEM, 7747 PTR_TO_MEM | MEM_RINGBUF, 7748 PTR_TO_BUF, 7749 PTR_TO_BTF_ID | PTR_TRUSTED, 7750 PTR_TO_CTX, 7751 }, 7752 }; 7753 7754 static const struct bpf_reg_types spin_lock_types = { 7755 .types = { 7756 PTR_TO_MAP_VALUE, 7757 PTR_TO_BTF_ID | MEM_ALLOC, 7758 } 7759 }; 7760 7761 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7762 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7763 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7764 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7765 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7766 static const struct bpf_reg_types btf_ptr_types = { 7767 .types = { 7768 PTR_TO_BTF_ID, 7769 PTR_TO_BTF_ID | PTR_TRUSTED, 7770 PTR_TO_BTF_ID | MEM_RCU, 7771 }, 7772 }; 7773 static const struct bpf_reg_types percpu_btf_ptr_types = { 7774 .types = { 7775 PTR_TO_BTF_ID | MEM_PERCPU, 7776 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 7777 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7778 } 7779 }; 7780 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7781 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7782 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7783 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7784 static const struct bpf_reg_types kptr_xchg_dest_types = { 7785 .types = { 7786 PTR_TO_MAP_VALUE, 7787 PTR_TO_BTF_ID | MEM_ALLOC, 7788 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF, 7789 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU, 7790 } 7791 }; 7792 static const struct bpf_reg_types dynptr_types = { 7793 .types = { 7794 PTR_TO_STACK, 7795 CONST_PTR_TO_DYNPTR, 7796 } 7797 }; 7798 7799 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7800 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7801 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7802 [ARG_CONST_SIZE] = &scalar_types, 7803 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7804 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7805 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7806 [ARG_PTR_TO_CTX] = &context_types, 7807 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7808 #ifdef CONFIG_NET 7809 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7810 #endif 7811 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7812 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7813 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7814 [ARG_PTR_TO_MEM] = &mem_types, 7815 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7816 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7817 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7818 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7819 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7820 [ARG_PTR_TO_TIMER] = &timer_types, 7821 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 7822 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7823 }; 7824 7825 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7826 enum bpf_arg_type arg_type, 7827 const u32 *arg_btf_id, 7828 struct bpf_call_arg_meta *meta) 7829 { 7830 enum bpf_reg_type expected, type = reg->type; 7831 const struct bpf_reg_types *compatible; 7832 int i, j, err; 7833 7834 compatible = compatible_reg_types[base_type(arg_type)]; 7835 if (!compatible) { 7836 verifier_bug(env, "unsupported arg type %d", arg_type); 7837 return -EFAULT; 7838 } 7839 7840 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7841 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7842 * 7843 * Same for MAYBE_NULL: 7844 * 7845 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7846 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7847 * 7848 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 7849 * 7850 * Therefore we fold these flags depending on the arg_type before comparison. 7851 */ 7852 if (arg_type & MEM_RDONLY) 7853 type &= ~MEM_RDONLY; 7854 if (arg_type & PTR_MAYBE_NULL) 7855 type &= ~PTR_MAYBE_NULL; 7856 if (base_type(arg_type) == ARG_PTR_TO_MEM) 7857 type &= ~DYNPTR_TYPE_FLAG_MASK; 7858 7859 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 7860 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && reg_from_argno(argno) == BPF_REG_2) { 7861 type &= ~MEM_ALLOC; 7862 type &= ~MEM_PERCPU; 7863 } 7864 7865 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7866 expected = compatible->types[i]; 7867 if (expected == NOT_INIT) 7868 break; 7869 7870 if (type == expected) 7871 goto found; 7872 } 7873 7874 verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7875 for (j = 0; j + 1 < i; j++) 7876 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7877 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7878 return -EACCES; 7879 7880 found: 7881 if (base_type(reg->type) != PTR_TO_BTF_ID) 7882 return 0; 7883 7884 if (compatible == &mem_types) { 7885 if (!(arg_type & MEM_RDONLY)) { 7886 verbose(env, 7887 "%s() may write into memory pointed by %s type=%s\n", 7888 func_id_name(meta->func_id), 7889 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7890 return -EACCES; 7891 } 7892 return 0; 7893 } 7894 7895 switch ((int)reg->type) { 7896 case PTR_TO_BTF_ID: 7897 case PTR_TO_BTF_ID | PTR_TRUSTED: 7898 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 7899 case PTR_TO_BTF_ID | MEM_RCU: 7900 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 7901 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 7902 { 7903 /* For bpf_sk_release, it needs to match against first member 7904 * 'struct sock_common', hence make an exception for it. This 7905 * allows bpf_sk_release to work for multiple socket types. 7906 */ 7907 bool strict_type_match = arg_type_is_release(arg_type) && 7908 meta->func_id != BPF_FUNC_sk_release; 7909 7910 if (type_may_be_null(reg->type) && 7911 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 7912 verbose(env, "Possibly NULL pointer passed to helper %s\n", 7913 reg_arg_name(env, argno)); 7914 return -EACCES; 7915 } 7916 7917 if (!arg_btf_id) { 7918 if (!compatible->btf_id) { 7919 verifier_bug(env, "missing arg compatible BTF ID"); 7920 return -EFAULT; 7921 } 7922 arg_btf_id = compatible->btf_id; 7923 } 7924 7925 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7926 if (map_kptr_match_type(env, meta->kptr_field, reg, reg_from_argno(argno))) 7927 return -EACCES; 7928 } else { 7929 if (arg_btf_id == BPF_PTR_POISON) { 7930 verbose(env, "verifier internal error:"); 7931 verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n", 7932 reg_arg_name(env, argno)); 7933 return -EACCES; 7934 } 7935 7936 err = __check_ptr_off_reg(env, reg, argno, true); 7937 if (err) 7938 return err; 7939 7940 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 7941 reg->var_off.value, btf_vmlinux, *arg_btf_id, 7942 strict_type_match)) { 7943 verbose(env, "%s is of type %s but %s is expected\n", 7944 reg_arg_name(env, argno), 7945 btf_type_name(reg->btf, reg->btf_id), 7946 btf_type_name(btf_vmlinux, *arg_btf_id)); 7947 return -EACCES; 7948 } 7949 } 7950 break; 7951 } 7952 case PTR_TO_BTF_ID | MEM_ALLOC: 7953 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 7954 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 7955 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 7956 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 7957 meta->func_id != BPF_FUNC_kptr_xchg) { 7958 verifier_bug(env, "unimplemented handling of MEM_ALLOC"); 7959 return -EFAULT; 7960 } 7961 /* Check if local kptr in src arg matches kptr in dst arg */ 7962 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7963 int regno = reg_from_argno(argno); 7964 7965 if (regno == BPF_REG_2 && 7966 map_kptr_match_type(env, meta->kptr_field, reg, regno)) 7967 return -EACCES; 7968 } 7969 break; 7970 case PTR_TO_BTF_ID | MEM_PERCPU: 7971 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 7972 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 7973 /* Handled by helper specific checks */ 7974 break; 7975 default: 7976 verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match"); 7977 return -EFAULT; 7978 } 7979 return 0; 7980 } 7981 7982 static struct btf_field * 7983 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 7984 { 7985 struct btf_field *field; 7986 struct btf_record *rec; 7987 7988 rec = reg_btf_record(reg); 7989 if (!rec) 7990 return NULL; 7991 7992 field = btf_record_find(rec, off, fields); 7993 if (!field) 7994 return NULL; 7995 7996 return field; 7997 } 7998 7999 static int __check_func_arg_reg_off(struct bpf_verifier_env *env, 8000 const struct bpf_reg_state *reg, argno_t argno, 8001 enum bpf_arg_type arg_type, 8002 bool btf_id_fixed_off_ok) 8003 { 8004 u32 type = reg->type; 8005 8006 /* When referenced register is passed to release function, its fixed 8007 * offset must be 0. 8008 * 8009 * We will check arg_type_is_release reg has id when storing 8010 * meta->release_regno. 8011 */ 8012 if (arg_type_is_release(arg_type)) { 8013 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8014 * may not directly point to the object being released, but to 8015 * dynptr pointing to such object, which might be at some offset 8016 * on the stack. In that case, we simply to fallback to the 8017 * default handling. 8018 */ 8019 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8020 return 0; 8021 8022 /* Doing check_ptr_off_reg check for the offset will catch this 8023 * because fixed_off_ok is false, but checking here allows us 8024 * to give the user a better error message. 8025 */ 8026 if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) { 8027 verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n", 8028 reg_arg_name(env, argno)); 8029 return -EINVAL; 8030 } 8031 } 8032 8033 switch (type) { 8034 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8035 case PTR_TO_STACK: 8036 case PTR_TO_PACKET: 8037 case PTR_TO_PACKET_META: 8038 case PTR_TO_MAP_KEY: 8039 case PTR_TO_MAP_VALUE: 8040 case PTR_TO_MEM: 8041 case PTR_TO_MEM | MEM_RDONLY: 8042 case PTR_TO_MEM | MEM_RINGBUF: 8043 case PTR_TO_BUF: 8044 case PTR_TO_BUF | MEM_RDONLY: 8045 case PTR_TO_ARENA: 8046 case SCALAR_VALUE: 8047 return 0; 8048 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8049 * fixed offset. 8050 */ 8051 case PTR_TO_BTF_ID: 8052 case PTR_TO_BTF_ID | MEM_ALLOC: 8053 case PTR_TO_BTF_ID | PTR_TRUSTED: 8054 case PTR_TO_BTF_ID | MEM_RCU: 8055 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8056 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8057 /* When referenced PTR_TO_BTF_ID is passed to release function, 8058 * its fixed offset must be 0. In the other cases, fixed offset 8059 * can be non-zero unless the caller requires otherwise. 8060 * var_off always must be 0 for PTR_TO_BTF_ID, hence we still 8061 * need to do checks instead of returning. 8062 */ 8063 return __check_ptr_off_reg(env, reg, argno, btf_id_fixed_off_ok); 8064 case PTR_TO_CTX: 8065 /* 8066 * Allow fixed and variable offsets for syscall context, but 8067 * only when the argument is passed as memory, not ctx, 8068 * otherwise we may get modified ctx in tail called programs and 8069 * global subprogs (that may act as extension prog hooks). 8070 */ 8071 if (arg_type != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog)) 8072 return 0; 8073 fallthrough; 8074 default: 8075 return __check_ptr_off_reg(env, reg, argno, false); 8076 } 8077 } 8078 8079 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8080 const struct bpf_reg_state *reg, argno_t argno, 8081 enum bpf_arg_type arg_type) 8082 { 8083 return __check_func_arg_reg_off(env, reg, argno, arg_type, true); 8084 } 8085 8086 static int check_arg_const_str(struct bpf_verifier_env *env, 8087 struct bpf_reg_state *reg, argno_t argno) 8088 { 8089 struct bpf_map *map = reg->map_ptr; 8090 int err; 8091 int map_off; 8092 u64 map_addr; 8093 char *str_ptr; 8094 8095 if (reg->type != PTR_TO_MAP_VALUE) 8096 return -EINVAL; 8097 8098 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 8099 verbose(env, "%s points to insn_array map which cannot be used as const string\n", 8100 reg_arg_name(env, argno)); 8101 return -EACCES; 8102 } 8103 8104 if (!bpf_map_is_rdonly(map)) { 8105 verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno)); 8106 return -EACCES; 8107 } 8108 8109 if (!tnum_is_const(reg->var_off)) { 8110 verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno)); 8111 return -EACCES; 8112 } 8113 8114 if (!map->ops->map_direct_value_addr) { 8115 verbose(env, "no direct value access support for this map type\n"); 8116 return -EACCES; 8117 } 8118 8119 err = check_map_access(env, reg, argno, 0, 8120 map->value_size - reg->var_off.value, false, 8121 ACCESS_HELPER); 8122 if (err) 8123 return err; 8124 8125 map_off = reg->var_off.value; 8126 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8127 if (err) { 8128 verbose(env, "direct value access on string failed\n"); 8129 return err; 8130 } 8131 8132 str_ptr = (char *)(long)(map_addr); 8133 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8134 verbose(env, "string is not zero-terminated\n"); 8135 return -EINVAL; 8136 } 8137 return 0; 8138 } 8139 8140 /* Returns constant key value in `value` if possible, else negative error */ 8141 static int get_constant_map_key(struct bpf_verifier_env *env, 8142 struct bpf_reg_state *key, 8143 u32 key_size, 8144 s64 *value) 8145 { 8146 struct bpf_func_state *state = bpf_func(env, key); 8147 struct bpf_reg_state *reg; 8148 int slot, spi, off; 8149 int spill_size = 0; 8150 int zero_size = 0; 8151 int stack_off; 8152 int i, err; 8153 u8 *stype; 8154 8155 if (!env->bpf_capable) 8156 return -EOPNOTSUPP; 8157 if (key->type != PTR_TO_STACK) 8158 return -EOPNOTSUPP; 8159 if (!tnum_is_const(key->var_off)) 8160 return -EOPNOTSUPP; 8161 8162 stack_off = key->var_off.value; 8163 slot = -stack_off - 1; 8164 spi = slot / BPF_REG_SIZE; 8165 off = slot % BPF_REG_SIZE; 8166 stype = state->stack[spi].slot_type; 8167 8168 /* First handle precisely tracked STACK_ZERO */ 8169 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) 8170 zero_size++; 8171 if (zero_size >= key_size) { 8172 *value = 0; 8173 return 0; 8174 } 8175 8176 /* Check that stack contains a scalar spill of expected size */ 8177 if (!bpf_is_spilled_scalar_reg(&state->stack[spi])) 8178 return -EOPNOTSUPP; 8179 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) 8180 spill_size++; 8181 if (spill_size != key_size) 8182 return -EOPNOTSUPP; 8183 8184 reg = &state->stack[spi].spilled_ptr; 8185 if (!tnum_is_const(reg->var_off)) 8186 /* Stack value not statically known */ 8187 return -EOPNOTSUPP; 8188 8189 /* We are relying on a constant value. So mark as precise 8190 * to prevent pruning on it. 8191 */ 8192 bpf_bt_set_frame_slot(&env->bt, key->frameno, spi); 8193 err = mark_chain_precision_batch(env, env->cur_state); 8194 if (err < 0) 8195 return err; 8196 8197 *value = reg->var_off.value; 8198 return 0; 8199 } 8200 8201 static bool can_elide_value_nullness(const struct bpf_map *map); 8202 8203 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8204 struct bpf_call_arg_meta *meta, 8205 const struct bpf_func_proto *fn, 8206 int insn_idx) 8207 { 8208 u32 regno = BPF_REG_1 + arg; 8209 struct bpf_reg_state *reg = reg_state(env, regno); 8210 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8211 argno_t argno = argno_from_arg(arg + 1); 8212 enum bpf_reg_type type = reg->type; 8213 u32 *arg_btf_id = NULL; 8214 u32 key_size; 8215 int err = 0; 8216 8217 if (arg_type == ARG_DONTCARE) 8218 return 0; 8219 8220 err = check_reg_arg(env, regno, SRC_OP); 8221 if (err) 8222 return err; 8223 8224 if (arg_type == ARG_ANYTHING) { 8225 if (is_pointer_value(env, regno)) { 8226 verbose(env, "R%d leaks addr into helper function\n", 8227 regno); 8228 return -EACCES; 8229 } 8230 return 0; 8231 } 8232 8233 if (type_is_pkt_pointer(type) && 8234 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8235 verbose(env, "helper access to the packet is not allowed\n"); 8236 return -EACCES; 8237 } 8238 8239 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8240 err = resolve_map_arg_type(env, meta, &arg_type); 8241 if (err) 8242 return err; 8243 } 8244 8245 if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) 8246 /* A NULL register has a SCALAR_VALUE type, so skip 8247 * type checking. 8248 */ 8249 goto skip_type_check; 8250 8251 /* arg_btf_id and arg_size are in a union. */ 8252 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8253 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8254 arg_btf_id = fn->arg_btf_id[arg]; 8255 8256 err = check_reg_type(env, reg, argno_from_reg(regno), arg_type, arg_btf_id, meta); 8257 if (err) 8258 return err; 8259 8260 err = check_func_arg_reg_off(env, reg, argno_from_reg(regno), arg_type); 8261 if (err) 8262 return err; 8263 8264 skip_type_check: 8265 if (arg_type_is_release(arg_type) && !arg_type_is_dynptr(arg_type) && 8266 !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) { 8267 verbose(env, "release helper %s expects referenced PTR_TO_BTF_ID passed to %s\n", 8268 func_id_name(meta->func_id), reg_arg_name(env, argno)); 8269 return -EINVAL; 8270 } 8271 8272 if (reg_is_referenced(env, reg)) 8273 update_ref_obj(&meta->ref_obj, reg); 8274 8275 switch (base_type(arg_type)) { 8276 case ARG_CONST_MAP_PTR: 8277 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8278 if (meta->map.ptr) { 8279 /* Use map_uid (which is unique id of inner map) to reject: 8280 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8281 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8282 * if (inner_map1 && inner_map2) { 8283 * timer = bpf_map_lookup_elem(inner_map1); 8284 * if (timer) 8285 * // mismatch would have been allowed 8286 * bpf_timer_init(timer, inner_map2); 8287 * } 8288 * 8289 * Comparing map_ptr is enough to distinguish normal and outer maps. 8290 */ 8291 if (meta->map.ptr != reg->map_ptr || 8292 meta->map.uid != reg->map_uid) { 8293 verbose(env, 8294 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8295 meta->map.uid, reg->map_uid); 8296 return -EINVAL; 8297 } 8298 } 8299 meta->map.ptr = reg->map_ptr; 8300 meta->map.uid = reg->map_uid; 8301 break; 8302 case ARG_PTR_TO_MAP_KEY: 8303 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8304 * check that [key, key + map->key_size) are within 8305 * stack limits and initialized 8306 */ 8307 if (!meta->map.ptr) { 8308 /* in function declaration map_ptr must come before 8309 * map_key, so that it's verified and known before 8310 * we have to check map_key here. Otherwise it means 8311 * that kernel subsystem misconfigured verifier 8312 */ 8313 verifier_bug(env, "invalid map_ptr to access map->key"); 8314 return -EFAULT; 8315 } 8316 key_size = meta->map.ptr->key_size; 8317 err = check_helper_mem_access(env, reg, argno_from_reg(regno), key_size, BPF_READ, false, NULL); 8318 if (err) 8319 return err; 8320 if (can_elide_value_nullness(meta->map.ptr)) { 8321 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key); 8322 if (err < 0) { 8323 meta->const_map_key = -1; 8324 if (err == -EOPNOTSUPP) 8325 err = 0; 8326 else 8327 return err; 8328 } 8329 } 8330 break; 8331 case ARG_PTR_TO_MAP_VALUE: 8332 if (type_may_be_null(arg_type) && bpf_register_is_null(reg)) 8333 return 0; 8334 8335 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8336 * check [value, value + map->value_size) validity 8337 */ 8338 if (!meta->map.ptr) { 8339 /* kernel subsystem misconfigured verifier */ 8340 verifier_bug(env, "invalid map_ptr to access map->value"); 8341 return -EFAULT; 8342 } 8343 meta->raw_mode = arg_type & MEM_UNINIT; 8344 err = check_helper_mem_access(env, reg, argno_from_reg(regno), meta->map.ptr->value_size, 8345 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8346 false, meta); 8347 break; 8348 case ARG_PTR_TO_PERCPU_BTF_ID: 8349 if (!reg->btf_id) { 8350 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8351 return -EACCES; 8352 } 8353 meta->ret_btf = reg->btf; 8354 meta->ret_btf_id = reg->btf_id; 8355 break; 8356 case ARG_PTR_TO_SPIN_LOCK: 8357 if (in_rbtree_lock_required_cb(env)) { 8358 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8359 return -EACCES; 8360 } 8361 if (meta->func_id == BPF_FUNC_spin_lock) { 8362 err = process_spin_lock(env, reg, argno_from_reg(regno), PROCESS_SPIN_LOCK); 8363 if (err) 8364 return err; 8365 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8366 err = process_spin_lock(env, reg, argno_from_reg(regno), 0); 8367 if (err) 8368 return err; 8369 } else { 8370 verifier_bug(env, "spin lock arg on unexpected helper"); 8371 return -EFAULT; 8372 } 8373 break; 8374 case ARG_PTR_TO_TIMER: 8375 err = process_timer_helper(env, reg, argno_from_reg(regno), meta); 8376 if (err) 8377 return err; 8378 break; 8379 case ARG_PTR_TO_FUNC: 8380 meta->subprogno = reg->subprogno; 8381 break; 8382 case ARG_PTR_TO_MEM: 8383 /* The access to this pointer is only checked when we hit the 8384 * next is_mem_size argument below. 8385 */ 8386 meta->raw_mode = arg_type & MEM_UNINIT; 8387 if (arg_type & MEM_FIXED_SIZE) { 8388 err = check_helper_mem_access(env, reg, argno_from_reg(regno), fn->arg_size[arg], 8389 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8390 false, meta); 8391 if (err) 8392 return err; 8393 if (arg_type & MEM_ALIGNED) 8394 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 8395 } 8396 break; 8397 case ARG_CONST_SIZE: 8398 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1), 8399 argno_from_reg(regno), 8400 fn->arg_type[arg - 1] & MEM_WRITE ? 8401 BPF_WRITE : BPF_READ, 8402 false, meta); 8403 break; 8404 case ARG_CONST_SIZE_OR_ZERO: 8405 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1), 8406 argno_from_reg(regno), 8407 fn->arg_type[arg - 1] & MEM_WRITE ? 8408 BPF_WRITE : BPF_READ, 8409 true, meta); 8410 break; 8411 case ARG_PTR_TO_DYNPTR: 8412 err = process_dynptr_func(env, reg, argno_from_reg(regno), insn_idx, arg_type, &meta->ref_obj, 8413 &meta->dynptr); 8414 if (err) 8415 return err; 8416 break; 8417 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8418 if (!tnum_is_const(reg->var_off)) { 8419 verbose(env, "R%d is not a known constant'\n", 8420 regno); 8421 return -EACCES; 8422 } 8423 meta->mem_size = reg->var_off.value; 8424 err = mark_chain_precision(env, regno); 8425 if (err) 8426 return err; 8427 break; 8428 case ARG_PTR_TO_CONST_STR: 8429 { 8430 err = check_arg_const_str(env, reg, argno_from_reg(regno)); 8431 if (err) 8432 return err; 8433 break; 8434 } 8435 case ARG_KPTR_XCHG_DEST: 8436 err = process_kptr_func(env, regno, meta); 8437 if (err) 8438 return err; 8439 break; 8440 } 8441 8442 return err; 8443 } 8444 8445 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8446 { 8447 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8448 enum bpf_prog_type type = resolve_prog_type(env->prog); 8449 8450 if (func_id != BPF_FUNC_map_update_elem && 8451 func_id != BPF_FUNC_map_delete_elem) 8452 return false; 8453 8454 /* It's not possible to get access to a locked struct sock in these 8455 * contexts, so updating is safe. 8456 */ 8457 switch (type) { 8458 case BPF_PROG_TYPE_TRACING: 8459 if (eatype == BPF_TRACE_ITER) 8460 return true; 8461 break; 8462 case BPF_PROG_TYPE_SOCK_OPS: 8463 /* map_update allowed only via dedicated helpers with event type checks */ 8464 if (func_id == BPF_FUNC_map_delete_elem) 8465 return true; 8466 break; 8467 case BPF_PROG_TYPE_SOCKET_FILTER: 8468 case BPF_PROG_TYPE_SCHED_CLS: 8469 case BPF_PROG_TYPE_SCHED_ACT: 8470 case BPF_PROG_TYPE_XDP: 8471 case BPF_PROG_TYPE_SK_REUSEPORT: 8472 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8473 case BPF_PROG_TYPE_SK_LOOKUP: 8474 return true; 8475 default: 8476 break; 8477 } 8478 8479 verbose(env, "cannot update sockmap in this context\n"); 8480 return false; 8481 } 8482 8483 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8484 { 8485 return env->prog->jit_requested && 8486 bpf_jit_supports_subprog_tailcalls(); 8487 } 8488 8489 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8490 struct bpf_map *map, int func_id) 8491 { 8492 if (!map) 8493 return 0; 8494 8495 /* We need a two way check, first is from map perspective ... */ 8496 switch (map->map_type) { 8497 case BPF_MAP_TYPE_PROG_ARRAY: 8498 if (func_id != BPF_FUNC_tail_call) 8499 goto error; 8500 break; 8501 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8502 if (func_id != BPF_FUNC_perf_event_read && 8503 func_id != BPF_FUNC_perf_event_output && 8504 func_id != BPF_FUNC_skb_output && 8505 func_id != BPF_FUNC_perf_event_read_value && 8506 func_id != BPF_FUNC_xdp_output) 8507 goto error; 8508 break; 8509 case BPF_MAP_TYPE_RINGBUF: 8510 if (func_id != BPF_FUNC_ringbuf_output && 8511 func_id != BPF_FUNC_ringbuf_reserve && 8512 func_id != BPF_FUNC_ringbuf_query && 8513 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8514 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8515 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8516 goto error; 8517 break; 8518 case BPF_MAP_TYPE_USER_RINGBUF: 8519 if (func_id != BPF_FUNC_user_ringbuf_drain) 8520 goto error; 8521 break; 8522 case BPF_MAP_TYPE_STACK_TRACE: 8523 if (func_id != BPF_FUNC_get_stackid) 8524 goto error; 8525 break; 8526 case BPF_MAP_TYPE_CGROUP_ARRAY: 8527 if (func_id != BPF_FUNC_skb_under_cgroup && 8528 func_id != BPF_FUNC_current_task_under_cgroup) 8529 goto error; 8530 break; 8531 case BPF_MAP_TYPE_CGROUP_STORAGE: 8532 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8533 if (func_id != BPF_FUNC_get_local_storage) 8534 goto error; 8535 break; 8536 case BPF_MAP_TYPE_DEVMAP: 8537 case BPF_MAP_TYPE_DEVMAP_HASH: 8538 if (func_id != BPF_FUNC_redirect_map && 8539 func_id != BPF_FUNC_map_lookup_elem) 8540 goto error; 8541 break; 8542 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8543 * appear. 8544 */ 8545 case BPF_MAP_TYPE_CPUMAP: 8546 if (func_id != BPF_FUNC_redirect_map) 8547 goto error; 8548 break; 8549 case BPF_MAP_TYPE_XSKMAP: 8550 if (func_id != BPF_FUNC_redirect_map && 8551 func_id != BPF_FUNC_map_lookup_elem) 8552 goto error; 8553 break; 8554 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8555 case BPF_MAP_TYPE_HASH_OF_MAPS: 8556 if (func_id != BPF_FUNC_map_lookup_elem) 8557 goto error; 8558 break; 8559 case BPF_MAP_TYPE_SOCKMAP: 8560 if (func_id != BPF_FUNC_sk_redirect_map && 8561 func_id != BPF_FUNC_sock_map_update && 8562 func_id != BPF_FUNC_msg_redirect_map && 8563 func_id != BPF_FUNC_sk_select_reuseport && 8564 func_id != BPF_FUNC_map_lookup_elem && 8565 !may_update_sockmap(env, func_id)) 8566 goto error; 8567 break; 8568 case BPF_MAP_TYPE_SOCKHASH: 8569 if (func_id != BPF_FUNC_sk_redirect_hash && 8570 func_id != BPF_FUNC_sock_hash_update && 8571 func_id != BPF_FUNC_msg_redirect_hash && 8572 func_id != BPF_FUNC_sk_select_reuseport && 8573 func_id != BPF_FUNC_map_lookup_elem && 8574 !may_update_sockmap(env, func_id)) 8575 goto error; 8576 break; 8577 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8578 if (func_id != BPF_FUNC_sk_select_reuseport) 8579 goto error; 8580 break; 8581 case BPF_MAP_TYPE_QUEUE: 8582 case BPF_MAP_TYPE_STACK: 8583 if (func_id != BPF_FUNC_map_peek_elem && 8584 func_id != BPF_FUNC_map_pop_elem && 8585 func_id != BPF_FUNC_map_push_elem) 8586 goto error; 8587 break; 8588 case BPF_MAP_TYPE_SK_STORAGE: 8589 if (func_id != BPF_FUNC_sk_storage_get && 8590 func_id != BPF_FUNC_sk_storage_delete && 8591 func_id != BPF_FUNC_kptr_xchg) 8592 goto error; 8593 break; 8594 case BPF_MAP_TYPE_INODE_STORAGE: 8595 if (func_id != BPF_FUNC_inode_storage_get && 8596 func_id != BPF_FUNC_inode_storage_delete && 8597 func_id != BPF_FUNC_kptr_xchg) 8598 goto error; 8599 break; 8600 case BPF_MAP_TYPE_TASK_STORAGE: 8601 if (func_id != BPF_FUNC_task_storage_get && 8602 func_id != BPF_FUNC_task_storage_delete && 8603 func_id != BPF_FUNC_kptr_xchg) 8604 goto error; 8605 break; 8606 case BPF_MAP_TYPE_CGRP_STORAGE: 8607 if (func_id != BPF_FUNC_cgrp_storage_get && 8608 func_id != BPF_FUNC_cgrp_storage_delete && 8609 func_id != BPF_FUNC_kptr_xchg) 8610 goto error; 8611 break; 8612 case BPF_MAP_TYPE_BLOOM_FILTER: 8613 if (func_id != BPF_FUNC_map_peek_elem && 8614 func_id != BPF_FUNC_map_push_elem) 8615 goto error; 8616 break; 8617 case BPF_MAP_TYPE_INSN_ARRAY: 8618 goto error; 8619 default: 8620 break; 8621 } 8622 8623 /* ... and second from the function itself. */ 8624 switch (func_id) { 8625 case BPF_FUNC_tail_call: 8626 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8627 goto error; 8628 if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) { 8629 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n"); 8630 return -EINVAL; 8631 } 8632 break; 8633 case BPF_FUNC_perf_event_read: 8634 case BPF_FUNC_perf_event_output: 8635 case BPF_FUNC_perf_event_read_value: 8636 case BPF_FUNC_skb_output: 8637 case BPF_FUNC_xdp_output: 8638 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8639 goto error; 8640 break; 8641 case BPF_FUNC_ringbuf_output: 8642 case BPF_FUNC_ringbuf_reserve: 8643 case BPF_FUNC_ringbuf_query: 8644 case BPF_FUNC_ringbuf_reserve_dynptr: 8645 case BPF_FUNC_ringbuf_submit_dynptr: 8646 case BPF_FUNC_ringbuf_discard_dynptr: 8647 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8648 goto error; 8649 break; 8650 case BPF_FUNC_user_ringbuf_drain: 8651 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8652 goto error; 8653 break; 8654 case BPF_FUNC_get_stackid: 8655 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8656 goto error; 8657 break; 8658 case BPF_FUNC_current_task_under_cgroup: 8659 case BPF_FUNC_skb_under_cgroup: 8660 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8661 goto error; 8662 break; 8663 case BPF_FUNC_redirect_map: 8664 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8665 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8666 map->map_type != BPF_MAP_TYPE_CPUMAP && 8667 map->map_type != BPF_MAP_TYPE_XSKMAP) 8668 goto error; 8669 break; 8670 case BPF_FUNC_sk_redirect_map: 8671 case BPF_FUNC_msg_redirect_map: 8672 case BPF_FUNC_sock_map_update: 8673 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8674 goto error; 8675 break; 8676 case BPF_FUNC_sk_redirect_hash: 8677 case BPF_FUNC_msg_redirect_hash: 8678 case BPF_FUNC_sock_hash_update: 8679 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8680 goto error; 8681 break; 8682 case BPF_FUNC_get_local_storage: 8683 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8684 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8685 goto error; 8686 break; 8687 case BPF_FUNC_sk_select_reuseport: 8688 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8689 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8690 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8691 goto error; 8692 break; 8693 case BPF_FUNC_map_pop_elem: 8694 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8695 map->map_type != BPF_MAP_TYPE_STACK) 8696 goto error; 8697 break; 8698 case BPF_FUNC_map_peek_elem: 8699 case BPF_FUNC_map_push_elem: 8700 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8701 map->map_type != BPF_MAP_TYPE_STACK && 8702 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8703 goto error; 8704 break; 8705 case BPF_FUNC_map_lookup_percpu_elem: 8706 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8707 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8708 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8709 goto error; 8710 break; 8711 case BPF_FUNC_sk_storage_get: 8712 case BPF_FUNC_sk_storage_delete: 8713 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8714 goto error; 8715 break; 8716 case BPF_FUNC_inode_storage_get: 8717 case BPF_FUNC_inode_storage_delete: 8718 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8719 goto error; 8720 break; 8721 case BPF_FUNC_task_storage_get: 8722 case BPF_FUNC_task_storage_delete: 8723 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8724 goto error; 8725 break; 8726 case BPF_FUNC_cgrp_storage_get: 8727 case BPF_FUNC_cgrp_storage_delete: 8728 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8729 goto error; 8730 break; 8731 default: 8732 break; 8733 } 8734 8735 return 0; 8736 error: 8737 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8738 map->map_type, func_id_name(func_id), func_id); 8739 return -EINVAL; 8740 } 8741 8742 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 8743 { 8744 int count = 0; 8745 8746 if (arg_type_is_raw_mem(fn->arg1_type)) 8747 count++; 8748 if (arg_type_is_raw_mem(fn->arg2_type)) 8749 count++; 8750 if (arg_type_is_raw_mem(fn->arg3_type)) 8751 count++; 8752 if (arg_type_is_raw_mem(fn->arg4_type)) 8753 count++; 8754 if (arg_type_is_raw_mem(fn->arg5_type)) 8755 count++; 8756 8757 /* We only support one arg being in raw mode at the moment, 8758 * which is sufficient for the helper functions we have 8759 * right now. 8760 */ 8761 return count <= 1; 8762 } 8763 8764 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8765 { 8766 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8767 bool has_size = fn->arg_size[arg] != 0; 8768 bool is_next_size = false; 8769 8770 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8771 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8772 8773 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8774 return is_next_size; 8775 8776 return has_size == is_next_size || is_next_size == is_fixed; 8777 } 8778 8779 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8780 { 8781 /* bpf_xxx(..., buf, len) call will access 'len' 8782 * bytes from memory 'buf'. Both arg types need 8783 * to be paired, so make sure there's no buggy 8784 * helper function specification. 8785 */ 8786 if (arg_type_is_mem_size(fn->arg1_type) || 8787 check_args_pair_invalid(fn, 0) || 8788 check_args_pair_invalid(fn, 1) || 8789 check_args_pair_invalid(fn, 2) || 8790 check_args_pair_invalid(fn, 3) || 8791 check_args_pair_invalid(fn, 4)) 8792 return false; 8793 8794 return true; 8795 } 8796 8797 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8798 { 8799 int i; 8800 8801 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8802 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8803 return !!fn->arg_btf_id[i]; 8804 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8805 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8806 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8807 /* arg_btf_id and arg_size are in a union. */ 8808 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8809 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8810 return false; 8811 } 8812 8813 return true; 8814 } 8815 8816 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn) 8817 { 8818 int i; 8819 8820 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8821 enum bpf_arg_type arg_type = fn->arg_type[i]; 8822 8823 if (base_type(arg_type) != ARG_PTR_TO_MEM) 8824 continue; 8825 if (!(arg_type & (MEM_WRITE | MEM_RDONLY))) 8826 return false; 8827 } 8828 8829 return true; 8830 } 8831 8832 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8833 { 8834 int i; 8835 8836 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8837 enum bpf_arg_type arg_type = fn->arg_type[i]; 8838 8839 if (arg_type_is_release(arg_type)) { 8840 if (meta->release_regno) 8841 return false; 8842 meta->release_regno = i + 1; 8843 } 8844 } 8845 8846 return true; 8847 } 8848 8849 static int check_func_proto(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8850 { 8851 return check_raw_mode_ok(fn) && 8852 check_arg_pair_ok(fn) && 8853 check_mem_arg_rw_flag_ok(fn) && 8854 check_proto_release_reg(fn, meta) && 8855 check_btf_id_ok(fn) ? 0 : -EINVAL; 8856 } 8857 8858 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8859 * are now invalid, so turn them into unknown SCALAR_VALUE. 8860 * 8861 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8862 * since these slices point to packet data. 8863 */ 8864 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8865 { 8866 struct bpf_func_state *state; 8867 struct bpf_reg_state *reg; 8868 8869 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8870 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8871 mark_reg_invalid(env, reg); 8872 })); 8873 } 8874 8875 enum { 8876 AT_PKT_END = -1, 8877 BEYOND_PKT_END = -2, 8878 }; 8879 8880 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8881 { 8882 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8883 struct bpf_reg_state *reg = &state->regs[regn]; 8884 8885 if (reg->type != PTR_TO_PACKET) 8886 /* PTR_TO_PACKET_META is not supported yet */ 8887 return; 8888 8889 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8890 * How far beyond pkt_end it goes is unknown. 8891 * if (!range_open) it's the case of pkt >= pkt_end 8892 * if (range_open) it's the case of pkt > pkt_end 8893 * hence this pointer is at least 1 byte bigger than pkt_end 8894 */ 8895 if (range_open) 8896 reg->range = BEYOND_PKT_END; 8897 else 8898 reg->range = AT_PKT_END; 8899 } 8900 8901 static int release_reference_nomark(struct bpf_verifier_state *state, int id) 8902 { 8903 int i; 8904 8905 for (i = 0; i < state->acquired_refs; i++) { 8906 if (state->refs[i].type != REF_TYPE_PTR) 8907 continue; 8908 if (state->refs[i].id == id) { 8909 release_reference_state(state, i); 8910 return 0; 8911 } 8912 } 8913 return -EINVAL; 8914 } 8915 8916 static int idstack_push(struct bpf_idmap *idmap, u32 id) 8917 { 8918 int i; 8919 8920 if (!id) 8921 return 0; 8922 8923 for (i = 0; i < idmap->cnt; i++) 8924 if (idmap->map[i].old == id) 8925 return 0; 8926 8927 if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE)) 8928 return -EFAULT; 8929 8930 idmap->map[idmap->cnt++].old = id; 8931 return 0; 8932 } 8933 8934 static int idstack_pop(struct bpf_idmap *idmap) 8935 { 8936 if (!idmap->cnt) 8937 return 0; 8938 8939 return idmap->map[--idmap->cnt].old; 8940 } 8941 8942 /* Release id and objects derived from it iteratively in a DFS manner */ 8943 static int release_reference(struct bpf_verifier_env *env, int id) 8944 { 8945 u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR); 8946 struct bpf_verifier_state *vstate = env->cur_state; 8947 struct bpf_idmap *idstack = &env->idmap_scratch; 8948 struct bpf_stack_state *stack; 8949 struct bpf_func_state *state; 8950 struct bpf_reg_state *reg; 8951 int i, err; 8952 8953 idstack->cnt = 0; 8954 err = idstack_push(idstack, id); 8955 if (err) 8956 return err; 8957 8958 if (find_reference_state(vstate, id)) 8959 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 8960 8961 while ((id = idstack_pop(idstack))) { 8962 /* 8963 * Child references are inaccessible after parent is released, 8964 * any child references that exist at this point are a leak. 8965 */ 8966 for (i = 0; i < vstate->acquired_refs; i++) { 8967 if (vstate->refs[i].type != REF_TYPE_PTR) 8968 continue; 8969 if (vstate->refs[i].parent_id != id) 8970 continue; 8971 verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n", 8972 vstate->refs[i].id, vstate->refs[i].insn_idx); 8973 return -EINVAL; 8974 } 8975 8976 bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({ 8977 if (reg->id != id && reg->parent_id != id) 8978 continue; 8979 8980 /* Free objects derived from the current object */ 8981 if (reg->parent_id == id) { 8982 err = idstack_push(idstack, reg->id); 8983 if (err) 8984 return err; 8985 } 8986 8987 if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL) 8988 mark_reg_invalid(env, reg); 8989 else if (stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR) 8990 invalidate_dynptr(env, stack); 8991 })); 8992 } 8993 8994 return 0; 8995 } 8996 8997 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 8998 { 8999 struct bpf_func_state *unused; 9000 struct bpf_reg_state *reg; 9001 9002 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9003 if (type_is_non_owning_ref(reg->type)) 9004 mark_reg_invalid(env, reg); 9005 })); 9006 } 9007 9008 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env) 9009 { 9010 struct bpf_stack_state *stack; 9011 struct bpf_func_state *state; 9012 struct bpf_reg_state *reg; 9013 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 9014 9015 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({ 9016 if (reg->type & MEM_RCU) { 9017 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 9018 reg->type |= PTR_UNTRUSTED; 9019 } 9020 })); 9021 } 9022 9023 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id) 9024 { 9025 struct bpf_func_state *state; 9026 struct bpf_reg_state *reg; 9027 int err; 9028 9029 err = release_reference_nomark(env->cur_state, id); 9030 9031 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9032 if (reg->id != id) 9033 continue; 9034 if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 9035 reg->id = 0; 9036 reg->type &= ~MEM_ALLOC; 9037 reg->type |= MEM_RCU; 9038 } 9039 })); 9040 9041 return err; 9042 } 9043 9044 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9045 struct bpf_reg_state *regs) 9046 { 9047 int i; 9048 9049 /* after the call registers r0 - r5 were scratched */ 9050 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9051 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 9052 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9053 } 9054 } 9055 9056 static void invalidate_outgoing_stack_args(const struct bpf_verifier_env *env, 9057 struct bpf_func_state *state) 9058 { 9059 int i, nslots = state->out_stack_arg_cnt; 9060 9061 for (i = 0; i < nslots; i++) 9062 bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]); 9063 } 9064 9065 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9066 struct bpf_func_state *caller, 9067 struct bpf_func_state *callee, 9068 int insn_idx); 9069 9070 static int set_callee_state(struct bpf_verifier_env *env, 9071 struct bpf_func_state *caller, 9072 struct bpf_func_state *callee, int insn_idx); 9073 9074 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9075 set_callee_state_fn set_callee_state_cb, 9076 struct bpf_verifier_state *state) 9077 { 9078 struct bpf_func_state *caller, *callee; 9079 int err; 9080 9081 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9082 verbose(env, "the call stack of %d frames is too deep\n", 9083 state->curframe + 2); 9084 return -E2BIG; 9085 } 9086 9087 if (state->frame[state->curframe + 1]) { 9088 verifier_bug(env, "Frame %d already allocated", state->curframe + 1); 9089 return -EFAULT; 9090 } 9091 9092 caller = state->frame[state->curframe]; 9093 callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT); 9094 if (!callee) 9095 return -ENOMEM; 9096 state->frame[state->curframe + 1] = callee; 9097 9098 /* callee cannot access r0, r6 - r9 for reading and has to write 9099 * into its own stack before reading from it. 9100 * callee can read/write into caller's stack 9101 */ 9102 init_func_state(env, callee, 9103 /* remember the callsite, it will be used by bpf_exit */ 9104 callsite, 9105 state->curframe + 1 /* frameno within this callchain */, 9106 subprog /* subprog number within this prog */); 9107 err = set_callee_state_cb(env, caller, callee, callsite); 9108 if (err) 9109 goto err_out; 9110 9111 /* only increment it after check_reg_arg() finished */ 9112 state->curframe++; 9113 9114 return 0; 9115 9116 err_out: 9117 free_func_state(callee); 9118 state->frame[state->curframe + 1] = NULL; 9119 return err; 9120 } 9121 9122 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9123 const struct btf *btf, 9124 struct bpf_reg_state *regs) 9125 { 9126 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9127 struct bpf_func_state *caller = cur_func(env); 9128 struct bpf_verifier_log *log = &env->log; 9129 struct ref_obj_desc ref_obj = {}; 9130 u32 i; 9131 int ret, err; 9132 9133 ret = btf_prepare_func_args(env, subprog); 9134 if (ret) { 9135 if (bpf_in_stack_arg_cnt(sub) > 0) { 9136 err = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9137 if (err) 9138 return err; 9139 } 9140 return ret; 9141 } 9142 9143 ret = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9144 if (ret) 9145 return ret; 9146 9147 /* check that BTF function arguments match actual types that the 9148 * verifier sees. 9149 */ 9150 for (i = 0; i < sub->arg_cnt; i++) { 9151 argno_t argno = argno_from_arg(i + 1); 9152 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 9153 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9154 9155 if (arg->arg_type == ARG_ANYTHING) { 9156 if (reg->type != SCALAR_VALUE) { 9157 bpf_log(log, "%s is not a scalar\n", reg_arg_name(env, argno)); 9158 return -EINVAL; 9159 } 9160 } else if (arg->arg_type & PTR_UNTRUSTED) { 9161 /* 9162 * Anything is allowed for untrusted arguments, as these are 9163 * read-only and probe read instructions would protect against 9164 * invalid memory access. 9165 */ 9166 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9167 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_CTX); 9168 if (ret < 0) 9169 return ret; 9170 /* If function expects ctx type in BTF check that caller 9171 * is passing PTR_TO_CTX. 9172 */ 9173 if (reg->type != PTR_TO_CTX) { 9174 bpf_log(log, "%s expects pointer to ctx\n", 9175 reg_arg_name(env, argno)); 9176 return -EINVAL; 9177 } 9178 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9179 ret = check_func_arg_reg_off(env, reg, argno, ARG_DONTCARE); 9180 if (ret < 0) 9181 return ret; 9182 if (check_mem_reg(env, reg, argno, arg->mem_size)) 9183 return -EINVAL; 9184 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9185 bpf_log(log, "%s is expected to be non-NULL\n", 9186 reg_arg_name(env, argno)); 9187 return -EINVAL; 9188 } 9189 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9190 /* 9191 * Can pass any value and the kernel won't crash, but 9192 * only PTR_TO_ARENA or SCALAR make sense. Everything 9193 * else is a bug in the bpf program. Point it out to 9194 * the user at the verification time instead of 9195 * run-time debug nightmare. 9196 */ 9197 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9198 bpf_log(log, "%s is not a pointer to arena or scalar.\n", 9199 reg_arg_name(env, argno)); 9200 return -EINVAL; 9201 } 9202 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 9203 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_DYNPTR); 9204 if (ret) 9205 return ret; 9206 9207 ret = process_dynptr_func(env, reg, argno, -1, arg->arg_type, &ref_obj, NULL); 9208 if (ret) 9209 return ret; 9210 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9211 struct bpf_call_arg_meta meta; 9212 int err; 9213 9214 if (bpf_register_is_null(reg) && type_may_be_null(arg->arg_type)) 9215 continue; 9216 9217 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9218 err = check_reg_type(env, reg, argno, arg->arg_type, &arg->btf_id, &meta); 9219 err = err ?: check_func_arg_reg_off(env, reg, argno, arg->arg_type); 9220 if (err) 9221 return err; 9222 } else { 9223 verifier_bug(env, "unrecognized %s type %d", 9224 reg_arg_name(env, argno), arg->arg_type); 9225 return -EFAULT; 9226 } 9227 } 9228 9229 return 0; 9230 } 9231 9232 /* Compare BTF of a function call with given bpf_reg_state. 9233 * Returns: 9234 * EFAULT - there is a verifier bug. Abort verification. 9235 * EINVAL - there is a type mismatch or BTF is not available. 9236 * 0 - BTF matches with what bpf_reg_state expects. 9237 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9238 */ 9239 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9240 struct bpf_reg_state *regs) 9241 { 9242 struct bpf_prog *prog = env->prog; 9243 struct btf *btf = prog->aux->btf; 9244 u32 btf_id; 9245 int err; 9246 9247 if (!prog->aux->func_info) 9248 return -EINVAL; 9249 9250 btf_id = prog->aux->func_info[subprog].type_id; 9251 if (!btf_id) 9252 return -EFAULT; 9253 9254 if (prog->aux->func_info_aux[subprog].unreliable) 9255 return -EINVAL; 9256 9257 err = btf_check_func_arg_match(env, subprog, btf, regs); 9258 /* Compiler optimizations can remove arguments from static functions 9259 * or mismatched type can be passed into a global function. 9260 * In such cases mark the function as unreliable from BTF point of view. 9261 */ 9262 if (err) 9263 prog->aux->func_info_aux[subprog].unreliable = true; 9264 return err; 9265 } 9266 9267 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9268 int insn_idx, int subprog, 9269 set_callee_state_fn set_callee_state_cb) 9270 { 9271 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9272 struct bpf_func_state *caller, *callee; 9273 int err; 9274 9275 caller = state->frame[state->curframe]; 9276 err = btf_check_subprog_call(env, subprog, caller->regs); 9277 if (err == -EFAULT) 9278 return err; 9279 9280 /* set_callee_state is used for direct subprog calls, but we are 9281 * interested in validating only BPF helpers that can call subprogs as 9282 * callbacks 9283 */ 9284 env->subprog_info[subprog].is_cb = true; 9285 if (bpf_pseudo_kfunc_call(insn) && 9286 !is_callback_calling_kfunc(insn->imm)) { 9287 verifier_bug(env, "kfunc %s#%d not marked as callback-calling", 9288 func_id_name(insn->imm), insn->imm); 9289 return -EFAULT; 9290 } else if (!bpf_pseudo_kfunc_call(insn) && 9291 !is_callback_calling_function(insn->imm)) { /* helper */ 9292 verifier_bug(env, "helper %s#%d not marked as callback-calling", 9293 func_id_name(insn->imm), insn->imm); 9294 return -EFAULT; 9295 } 9296 9297 if (bpf_is_async_callback_calling_insn(insn)) { 9298 struct bpf_verifier_state *async_cb; 9299 9300 /* there is no real recursion here. timer and workqueue callbacks are async */ 9301 env->subprog_info[subprog].is_async_cb = true; 9302 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9303 insn_idx, subprog, 9304 is_async_cb_sleepable(env, insn)); 9305 if (IS_ERR(async_cb)) 9306 return PTR_ERR(async_cb); 9307 callee = async_cb->frame[0]; 9308 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9309 9310 /* Convert bpf_timer_set_callback() args into timer callback args */ 9311 err = set_callee_state_cb(env, caller, callee, insn_idx); 9312 if (err) 9313 return err; 9314 9315 return 0; 9316 } 9317 9318 /* for callback functions enqueue entry to callback and 9319 * proceed with next instruction within current frame. 9320 */ 9321 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9322 if (IS_ERR(callback_state)) 9323 return PTR_ERR(callback_state); 9324 9325 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9326 callback_state); 9327 if (err) 9328 return err; 9329 9330 callback_state->callback_unroll_depth++; 9331 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9332 caller->callback_depth = 0; 9333 return 0; 9334 } 9335 9336 static int process_bpf_exit_full(struct bpf_verifier_env *env, 9337 bool *do_print_state, bool exception_exit); 9338 9339 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9340 int *insn_idx) 9341 { 9342 struct bpf_verifier_state *state = env->cur_state; 9343 struct bpf_subprog_info *caller_info; 9344 u16 callee_incoming, stack_arg_cnt; 9345 struct bpf_func_state *caller; 9346 int err, subprog, target_insn; 9347 9348 target_insn = *insn_idx + insn->imm + 1; 9349 subprog = bpf_find_subprog(env, target_insn); 9350 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program", 9351 target_insn)) 9352 return -EFAULT; 9353 9354 caller = state->frame[state->curframe]; 9355 err = btf_check_subprog_call(env, subprog, caller->regs); 9356 if (err == -EFAULT) 9357 return err; 9358 if (bpf_subprog_is_global(env, subprog)) { 9359 const char *sub_name = subprog_name(env, subprog); 9360 9361 if (env->cur_state->active_locks) { 9362 verbose(env, "global function calls are not allowed while holding a lock,\n" 9363 "use static function instead\n"); 9364 return -EINVAL; 9365 } 9366 9367 if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) { 9368 verbose(env, "sleepable global function %s() called in %s\n", 9369 sub_name, non_sleepable_context_description(env)); 9370 return -EINVAL; 9371 } 9372 9373 if (err) { 9374 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9375 subprog, sub_name); 9376 return err; 9377 } 9378 9379 if (env->log.level & BPF_LOG_LEVEL) 9380 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9381 subprog, sub_name); 9382 if (env->subprog_info[subprog].changes_pkt_data) 9383 clear_all_pkt_pointers(env); 9384 /* mark global subprog for verifying after main prog */ 9385 subprog_aux(env, subprog)->called = true; 9386 clear_caller_saved_regs(env, caller->regs); 9387 invalidate_outgoing_stack_args(env, cur_func(env)); 9388 9389 /* All non-void global functions return a 64-bit SCALAR_VALUE. */ 9390 if (!subprog_returns_void(env, subprog)) { 9391 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9392 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9393 } 9394 9395 if (env->subprog_info[subprog].might_throw) { 9396 struct bpf_verifier_state *branch; 9397 9398 branch = push_stack(env, *insn_idx + 1, *insn_idx, false); 9399 if (IS_ERR(branch)) { 9400 verbose(env, "failed to push state for global subprog exception path\n"); 9401 return PTR_ERR(branch); 9402 } 9403 return process_bpf_exit_full(env, NULL, true); 9404 } 9405 9406 /* continue with next insn after call */ 9407 return 0; 9408 } 9409 9410 /* 9411 * Track caller's total stack arg count (incoming + max outgoing). 9412 * This is needed so the JIT knows how much stack arg space to allocate. 9413 */ 9414 caller_info = &env->subprog_info[caller->subprogno]; 9415 callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]); 9416 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming; 9417 if (stack_arg_cnt > caller_info->stack_arg_cnt) 9418 caller_info->stack_arg_cnt = stack_arg_cnt; 9419 9420 /* for regular function entry setup new frame and continue 9421 * from that frame. 9422 */ 9423 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9424 if (err) 9425 return err; 9426 9427 clear_caller_saved_regs(env, caller->regs); 9428 9429 /* and go analyze first insn of the callee */ 9430 *insn_idx = env->subprog_info[subprog].start - 1; 9431 9432 if (env->log.level & BPF_LOG_LEVEL) { 9433 verbose(env, "caller:\n"); 9434 print_verifier_state(env, state, caller->frameno, true); 9435 verbose(env, "callee:\n"); 9436 print_verifier_state(env, state, state->curframe, true); 9437 } 9438 9439 return 0; 9440 } 9441 9442 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9443 struct bpf_func_state *caller, 9444 struct bpf_func_state *callee) 9445 { 9446 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9447 * void *callback_ctx, u64 flags); 9448 * callback_fn(struct bpf_map *map, void *key, void *value, 9449 * void *callback_ctx); 9450 */ 9451 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9452 9453 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9454 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9455 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9456 9457 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9458 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9459 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9460 9461 /* pointer to stack or null */ 9462 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9463 9464 /* unused */ 9465 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9466 return 0; 9467 } 9468 9469 static int set_callee_state(struct bpf_verifier_env *env, 9470 struct bpf_func_state *caller, 9471 struct bpf_func_state *callee, int insn_idx) 9472 { 9473 int i; 9474 9475 /* copy r1 - r5 args that callee can access. The copy includes parent 9476 * pointers, which connects us up to the liveness chain 9477 */ 9478 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9479 callee->regs[i] = caller->regs[i]; 9480 return 0; 9481 } 9482 9483 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9484 struct bpf_func_state *caller, 9485 struct bpf_func_state *callee, 9486 int insn_idx) 9487 { 9488 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9489 struct bpf_map *map; 9490 int err; 9491 9492 /* valid map_ptr and poison value does not matter */ 9493 map = insn_aux->map_ptr_state.map_ptr; 9494 if (!map->ops->map_set_for_each_callback_args || 9495 !map->ops->map_for_each_callback) { 9496 verbose(env, "callback function not allowed for map\n"); 9497 return -ENOTSUPP; 9498 } 9499 9500 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9501 if (err) 9502 return err; 9503 9504 callee->in_callback_fn = true; 9505 callee->callback_ret_range = retval_range(0, 1); 9506 return 0; 9507 } 9508 9509 static int set_loop_callback_state(struct bpf_verifier_env *env, 9510 struct bpf_func_state *caller, 9511 struct bpf_func_state *callee, 9512 int insn_idx) 9513 { 9514 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9515 * u64 flags); 9516 * callback_fn(u64 index, void *callback_ctx); 9517 */ 9518 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9519 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9520 9521 /* unused */ 9522 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9523 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9524 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9525 9526 callee->in_callback_fn = true; 9527 callee->callback_ret_range = retval_range(0, 1); 9528 return 0; 9529 } 9530 9531 static int set_timer_callback_state(struct bpf_verifier_env *env, 9532 struct bpf_func_state *caller, 9533 struct bpf_func_state *callee, 9534 int insn_idx) 9535 { 9536 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9537 9538 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9539 * callback_fn(struct bpf_map *map, void *key, void *value); 9540 */ 9541 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9542 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9543 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9544 9545 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9546 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9547 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9548 9549 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9550 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9551 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9552 9553 /* unused */ 9554 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9555 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9556 callee->in_async_callback_fn = true; 9557 callee->callback_ret_range = retval_range(0, 0); 9558 return 0; 9559 } 9560 9561 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9562 struct bpf_func_state *caller, 9563 struct bpf_func_state *callee, 9564 int insn_idx) 9565 { 9566 /* bpf_find_vma(struct task_struct *task, u64 addr, 9567 * void *callback_fn, void *callback_ctx, u64 flags) 9568 * (callback_fn)(struct task_struct *task, 9569 * struct vm_area_struct *vma, void *callback_ctx); 9570 */ 9571 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9572 9573 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9574 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9575 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9576 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9577 9578 /* pointer to stack or null */ 9579 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9580 9581 /* unused */ 9582 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9583 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9584 callee->in_callback_fn = true; 9585 callee->callback_ret_range = retval_range(0, 1); 9586 return 0; 9587 } 9588 9589 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9590 struct bpf_func_state *caller, 9591 struct bpf_func_state *callee, 9592 int insn_idx) 9593 { 9594 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9595 * callback_ctx, u64 flags); 9596 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9597 */ 9598 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9599 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9600 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9601 9602 /* unused */ 9603 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9604 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9605 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9606 9607 callee->in_callback_fn = true; 9608 callee->callback_ret_range = retval_range(0, 1); 9609 return 0; 9610 } 9611 9612 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9613 struct bpf_func_state *caller, 9614 struct bpf_func_state *callee, 9615 int insn_idx) 9616 { 9617 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9618 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9619 * 9620 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9621 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9622 * by this point, so look at 'root' 9623 */ 9624 struct btf_field *field; 9625 9626 field = reg_find_field_offset(&caller->regs[BPF_REG_1], 9627 caller->regs[BPF_REG_1].var_off.value, 9628 BPF_RB_ROOT); 9629 if (!field || !field->graph_root.value_btf_id) 9630 return -EFAULT; 9631 9632 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9633 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9634 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9635 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9636 9637 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9638 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9639 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9640 callee->in_callback_fn = true; 9641 callee->callback_ret_range = retval_range(0, 1); 9642 return 0; 9643 } 9644 9645 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env, 9646 struct bpf_func_state *caller, 9647 struct bpf_func_state *callee, 9648 int insn_idx) 9649 { 9650 struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr; 9651 9652 /* 9653 * callback_fn(struct bpf_map *map, void *key, void *value); 9654 */ 9655 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9656 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9657 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9658 9659 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9660 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9661 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9662 9663 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9664 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9665 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9666 9667 /* unused */ 9668 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9669 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9670 callee->in_async_callback_fn = true; 9671 callee->callback_ret_range = retval_range(S32_MIN, S32_MAX); 9672 return 0; 9673 } 9674 9675 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9676 9677 /* Are we currently verifying the callback for a rbtree helper that must 9678 * be called with lock held? If so, no need to complain about unreleased 9679 * lock 9680 */ 9681 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9682 { 9683 struct bpf_verifier_state *state = env->cur_state; 9684 struct bpf_insn *insn = env->prog->insnsi; 9685 struct bpf_func_state *callee; 9686 int kfunc_btf_id; 9687 9688 if (!state->curframe) 9689 return false; 9690 9691 callee = state->frame[state->curframe]; 9692 9693 if (!callee->in_callback_fn) 9694 return false; 9695 9696 kfunc_btf_id = insn[callee->callsite].imm; 9697 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9698 } 9699 9700 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9701 { 9702 if (range.return_32bit) 9703 return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval; 9704 else 9705 return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval; 9706 } 9707 9708 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9709 { 9710 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9711 struct bpf_func_state *caller, *callee; 9712 struct bpf_reg_state *r0; 9713 bool in_callback_fn; 9714 int err; 9715 9716 callee = state->frame[state->curframe]; 9717 r0 = &callee->regs[BPF_REG_0]; 9718 if (r0->type == PTR_TO_STACK) { 9719 /* technically it's ok to return caller's stack pointer 9720 * (or caller's caller's pointer) back to the caller, 9721 * since these pointers are valid. Only current stack 9722 * pointer will be invalid as soon as function exits, 9723 * but let's be conservative 9724 */ 9725 verbose(env, "cannot return stack pointer to the caller\n"); 9726 return -EINVAL; 9727 } 9728 9729 caller = state->frame[state->curframe - 1]; 9730 if (callee->in_callback_fn) { 9731 if (r0->type != SCALAR_VALUE) { 9732 verbose(env, "R0 not a scalar value\n"); 9733 return -EACCES; 9734 } 9735 9736 /* we are going to rely on register's precise value */ 9737 err = mark_chain_precision(env, BPF_REG_0); 9738 if (err) 9739 return err; 9740 9741 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 9742 if (!retval_range_within(callee->callback_ret_range, r0)) { 9743 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9744 "At callback return", "R0"); 9745 return -EINVAL; 9746 } 9747 if (!bpf_calls_callback(env, callee->callsite)) { 9748 verifier_bug(env, "in callback at %d, callsite %d !calls_callback", 9749 *insn_idx, callee->callsite); 9750 return -EFAULT; 9751 } 9752 } else { 9753 /* return to the caller whatever r0 had in the callee */ 9754 caller->regs[BPF_REG_0] = *r0; 9755 } 9756 9757 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9758 * there function call logic would reschedule callback visit. If iteration 9759 * converges is_state_visited() would prune that visit eventually. 9760 */ 9761 in_callback_fn = callee->in_callback_fn; 9762 if (in_callback_fn) 9763 *insn_idx = callee->callsite; 9764 else 9765 *insn_idx = callee->callsite + 1; 9766 9767 if (env->log.level & BPF_LOG_LEVEL) { 9768 verbose(env, "returning from callee:\n"); 9769 print_verifier_state(env, state, callee->frameno, true); 9770 verbose(env, "to caller at %d:\n", *insn_idx); 9771 print_verifier_state(env, state, caller->frameno, true); 9772 } 9773 /* clear everything in the callee. In case of exceptional exits using 9774 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9775 free_func_state(callee); 9776 state->frame[state->curframe--] = NULL; 9777 invalidate_outgoing_stack_args(env, caller); 9778 9779 /* for callbacks widen imprecise scalars to make programs like below verify: 9780 * 9781 * struct ctx { int i; } 9782 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9783 * ... 9784 * struct ctx = { .i = 0; } 9785 * bpf_loop(100, cb, &ctx, 0); 9786 * 9787 * This is similar to what is done in process_iter_next_call() for open 9788 * coded iterators. 9789 */ 9790 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9791 if (prev_st) { 9792 err = widen_imprecise_scalars(env, prev_st, state); 9793 if (err) 9794 return err; 9795 } 9796 return 0; 9797 } 9798 9799 static int do_refine_retval_range(struct bpf_verifier_env *env, 9800 struct bpf_reg_state *regs, int ret_type, 9801 int func_id, 9802 struct bpf_call_arg_meta *meta) 9803 { 9804 struct bpf_retval_range range; 9805 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9806 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9807 9808 if (ret_type != RET_INTEGER) 9809 return 0; 9810 9811 switch (func_id) { 9812 case BPF_FUNC_get_stack: 9813 case BPF_FUNC_get_task_stack: 9814 case BPF_FUNC_probe_read_str: 9815 case BPF_FUNC_probe_read_kernel_str: 9816 case BPF_FUNC_probe_read_user_str: 9817 reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9818 reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9819 reg_bounds_sync(ret_reg); 9820 break; 9821 case BPF_FUNC_get_smp_processor_id: 9822 reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1); 9823 reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1); 9824 reg_bounds_sync(ret_reg); 9825 break; 9826 case BPF_FUNC_get_retval: 9827 /* 9828 * bpf_get_retval may see arbitrary value passed by bpf_prog_run_array_cg for 9829 * CGROUP_GETSOCKOPT type. 9830 */ 9831 if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT && 9832 env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) 9833 break; 9834 9835 if (prog_type == BPF_PROG_TYPE_LSM && 9836 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 9837 if (!env->prog->aux->attach_func_proto->type) 9838 break; 9839 bpf_lsm_get_retval_range(env->prog, &range); 9840 } else { 9841 range.minval = -MAX_ERRNO; 9842 range.maxval = 0; 9843 } 9844 9845 reg_set_srange64(ret_reg, range.minval, range.maxval); 9846 reg_set_srange32(ret_reg, range.minval, range.maxval); 9847 reg_bounds_sync(ret_reg); 9848 break; 9849 } 9850 9851 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9852 } 9853 9854 static int 9855 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9856 int func_id, int insn_idx) 9857 { 9858 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9859 struct bpf_map *map = meta->map.ptr; 9860 9861 if (func_id != BPF_FUNC_tail_call && 9862 func_id != BPF_FUNC_map_lookup_elem && 9863 func_id != BPF_FUNC_map_update_elem && 9864 func_id != BPF_FUNC_map_delete_elem && 9865 func_id != BPF_FUNC_map_push_elem && 9866 func_id != BPF_FUNC_map_pop_elem && 9867 func_id != BPF_FUNC_map_peek_elem && 9868 func_id != BPF_FUNC_for_each_map_elem && 9869 func_id != BPF_FUNC_redirect_map && 9870 func_id != BPF_FUNC_map_lookup_percpu_elem) 9871 return 0; 9872 9873 if (map == NULL) { 9874 verifier_bug(env, "expected map for helper call"); 9875 return -EFAULT; 9876 } 9877 9878 /* In case of read-only, some additional restrictions 9879 * need to be applied in order to prevent altering the 9880 * state of the map from program side. 9881 */ 9882 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9883 (func_id == BPF_FUNC_map_delete_elem || 9884 func_id == BPF_FUNC_map_update_elem || 9885 func_id == BPF_FUNC_map_push_elem || 9886 func_id == BPF_FUNC_map_pop_elem)) { 9887 verbose(env, "write into map forbidden\n"); 9888 return -EACCES; 9889 } 9890 9891 if (!aux->map_ptr_state.map_ptr) 9892 bpf_map_ptr_store(aux, meta->map.ptr, 9893 !meta->map.ptr->bypass_spec_v1, false); 9894 else if (aux->map_ptr_state.map_ptr != meta->map.ptr) 9895 bpf_map_ptr_store(aux, meta->map.ptr, 9896 !meta->map.ptr->bypass_spec_v1, true); 9897 return 0; 9898 } 9899 9900 static int 9901 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9902 int func_id, int insn_idx) 9903 { 9904 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9905 struct bpf_reg_state *reg; 9906 struct bpf_map *map = meta->map.ptr; 9907 u64 val, max; 9908 int err; 9909 9910 if (func_id != BPF_FUNC_tail_call) 9911 return 0; 9912 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9913 verbose(env, "expected prog array map for tail call"); 9914 return -EINVAL; 9915 } 9916 9917 reg = reg_state(env, BPF_REG_3); 9918 val = reg->var_off.value; 9919 max = map->max_entries; 9920 9921 if (!(is_reg_const(reg, false) && val < max)) { 9922 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9923 return 0; 9924 } 9925 9926 err = mark_chain_precision(env, BPF_REG_3); 9927 if (err) 9928 return err; 9929 if (bpf_map_key_unseen(aux)) 9930 bpf_map_key_store(aux, val); 9931 else if (!bpf_map_key_poisoned(aux) && 9932 bpf_map_key_immediate(aux) != val) 9933 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9934 return 0; 9935 } 9936 9937 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9938 { 9939 struct bpf_verifier_state *state = env->cur_state; 9940 enum bpf_prog_type type = resolve_prog_type(env->prog); 9941 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 9942 bool refs_lingering = false; 9943 int i; 9944 9945 if (!exception_exit && cur_func(env)->frameno) 9946 return 0; 9947 9948 for (i = 0; i < state->acquired_refs; i++) { 9949 if (state->refs[i].type != REF_TYPE_PTR) 9950 continue; 9951 /* Allow struct_ops programs to return a referenced kptr back to 9952 * kernel. Type checks are performed later in check_return_code. 9953 */ 9954 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && 9955 reg->id == state->refs[i].id) 9956 continue; 9957 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9958 state->refs[i].id, state->refs[i].insn_idx); 9959 refs_lingering = true; 9960 } 9961 return refs_lingering ? -EINVAL : 0; 9962 } 9963 9964 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 9965 { 9966 int err; 9967 9968 if (check_lock && env->cur_state->active_locks) { 9969 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 9970 return -EINVAL; 9971 } 9972 9973 err = check_reference_leak(env, exception_exit); 9974 if (err) { 9975 verbose(env, "%s would lead to reference leak\n", prefix); 9976 return err; 9977 } 9978 9979 if (check_lock && env->cur_state->active_irq_id) { 9980 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix); 9981 return -EINVAL; 9982 } 9983 9984 if (check_lock && env->cur_state->active_rcu_locks) { 9985 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 9986 return -EINVAL; 9987 } 9988 9989 if (check_lock && env->cur_state->active_preempt_locks) { 9990 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 9991 return -EINVAL; 9992 } 9993 9994 return 0; 9995 } 9996 9997 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9998 struct bpf_reg_state *regs) 9999 { 10000 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10001 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10002 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10003 struct bpf_bprintf_data data = {}; 10004 int err, fmt_map_off, num_args; 10005 u64 fmt_addr; 10006 char *fmt; 10007 10008 /* data must be an array of u64 */ 10009 if (data_len_reg->var_off.value % 8) 10010 return -EINVAL; 10011 num_args = data_len_reg->var_off.value / 8; 10012 10013 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10014 * and map_direct_value_addr is set. 10015 */ 10016 fmt_map_off = fmt_reg->var_off.value; 10017 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10018 fmt_map_off); 10019 if (err) { 10020 verbose(env, "failed to retrieve map value address\n"); 10021 return -EFAULT; 10022 } 10023 fmt = (char *)(long)fmt_addr + fmt_map_off; 10024 10025 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10026 * can focus on validating the format specifiers. 10027 */ 10028 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10029 if (err < 0) 10030 verbose(env, "Invalid format string\n"); 10031 10032 return err; 10033 } 10034 10035 static int check_get_func_ip(struct bpf_verifier_env *env) 10036 { 10037 enum bpf_prog_type type = resolve_prog_type(env->prog); 10038 int func_id = BPF_FUNC_get_func_ip; 10039 10040 if (type == BPF_PROG_TYPE_TRACING) { 10041 if (!bpf_prog_has_trampoline(env->prog)) { 10042 verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n", 10043 func_id_name(func_id), func_id); 10044 return -ENOTSUPP; 10045 } 10046 return 0; 10047 } else if (type == BPF_PROG_TYPE_KPROBE) { 10048 return 0; 10049 } 10050 10051 verbose(env, "func %s#%d not supported for program type %d\n", 10052 func_id_name(func_id), func_id, type); 10053 return -ENOTSUPP; 10054 } 10055 10056 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env) 10057 { 10058 return &env->insn_aux_data[env->insn_idx]; 10059 } 10060 10061 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10062 { 10063 struct bpf_reg_state *reg = reg_state(env, BPF_REG_4); 10064 bool reg_is_null = bpf_register_is_null(reg); 10065 10066 if (reg_is_null) 10067 mark_chain_precision(env, BPF_REG_4); 10068 10069 return reg_is_null; 10070 } 10071 10072 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10073 { 10074 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10075 10076 if (!state->initialized) { 10077 state->initialized = 1; 10078 state->fit_for_inline = loop_flag_is_zero(env); 10079 state->callback_subprogno = subprogno; 10080 return; 10081 } 10082 10083 if (!state->fit_for_inline) 10084 return; 10085 10086 state->fit_for_inline = (loop_flag_is_zero(env) && 10087 state->callback_subprogno == subprogno); 10088 } 10089 10090 /* Returns whether or not the given map can potentially elide 10091 * lookup return value nullness check. This is possible if the key 10092 * is statically known. 10093 */ 10094 static bool can_elide_value_nullness(const struct bpf_map *map) 10095 { 10096 if (map->map_flags & BPF_F_INNER_MAP) 10097 return false; 10098 10099 switch (map->map_type) { 10100 case BPF_MAP_TYPE_ARRAY: 10101 case BPF_MAP_TYPE_PERCPU_ARRAY: 10102 return true; 10103 default: 10104 return false; 10105 } 10106 } 10107 10108 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id, 10109 const struct bpf_func_proto **ptr) 10110 { 10111 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 10112 return -ERANGE; 10113 10114 if (!env->ops->get_func_proto) 10115 return -EINVAL; 10116 10117 *ptr = env->ops->get_func_proto(func_id, env->prog); 10118 return *ptr && (*ptr)->func ? 0 : -EINVAL; 10119 } 10120 10121 /* Check if we're in a sleepable context. */ 10122 static inline bool in_sleepable_context(struct bpf_verifier_env *env) 10123 { 10124 return !env->cur_state->active_rcu_locks && 10125 !env->cur_state->active_preempt_locks && 10126 !env->cur_state->active_locks && 10127 !env->cur_state->active_irq_id && 10128 in_sleepable(env); 10129 } 10130 10131 static const char *non_sleepable_context_description(struct bpf_verifier_env *env) 10132 { 10133 if (env->cur_state->active_rcu_locks) 10134 return "rcu_read_lock region"; 10135 if (env->cur_state->active_preempt_locks) 10136 return "non-preemptible region"; 10137 if (env->cur_state->active_irq_id) 10138 return "IRQ-disabled region"; 10139 if (env->cur_state->active_locks) 10140 return "lock region"; 10141 return "non-sleepable prog"; 10142 } 10143 10144 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 10145 bool convert_rcu, bool release_dynptr) 10146 { 10147 int err = -EINVAL; 10148 10149 if (bpf_register_is_null(reg)) 10150 return 0; 10151 10152 if (release_dynptr) 10153 err = unmark_stack_slots_dynptr(env, reg); 10154 else if (convert_rcu) 10155 err = ref_convert_alloc_rcu_protected(env, reg->id); 10156 else if (reg_is_referenced(env, reg)) 10157 err = release_reference(env, reg->id); 10158 10159 return err; 10160 } 10161 10162 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10163 int *insn_idx_p) 10164 { 10165 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10166 bool returns_cpu_specific_alloc_ptr = false; 10167 const struct bpf_func_proto *fn = NULL; 10168 enum bpf_return_type ret_type; 10169 enum bpf_type_flag ret_flag; 10170 struct bpf_reg_state *regs; 10171 struct bpf_call_arg_meta meta; 10172 int insn_idx = *insn_idx_p; 10173 bool changes_data; 10174 int i, err, func_id; 10175 10176 /* find function prototype */ 10177 func_id = insn->imm; 10178 err = bpf_get_helper_proto(env, insn->imm, &fn); 10179 if (err == -ERANGE) { 10180 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 10181 return -EINVAL; 10182 } 10183 10184 if (err) { 10185 verbose(env, "program of this type cannot use helper %s#%d\n", 10186 func_id_name(func_id), func_id); 10187 return err; 10188 } 10189 10190 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10191 if (!env->prog->gpl_compatible && fn->gpl_only) { 10192 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10193 return -EINVAL; 10194 } 10195 10196 if (fn->allowed && !fn->allowed(env->prog)) { 10197 verbose(env, "helper call is not allowed in probe\n"); 10198 return -EINVAL; 10199 } 10200 10201 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10202 changes_data = bpf_helper_changes_pkt_data(func_id); 10203 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10204 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id); 10205 return -EFAULT; 10206 } 10207 10208 memset(&meta, 0, sizeof(meta)); 10209 meta.pkt_access = fn->pkt_access; 10210 10211 err = check_func_proto(fn, &meta); 10212 if (err) { 10213 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id); 10214 return err; 10215 } 10216 10217 if (fn->might_sleep && !in_sleepable_context(env)) { 10218 verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id, 10219 non_sleepable_context_description(env)); 10220 return -EINVAL; 10221 } 10222 10223 /* Track non-sleepable context for helpers. */ 10224 if (!in_sleepable_context(env)) 10225 env->insn_aux_data[insn_idx].non_sleepable = true; 10226 10227 meta.func_id = func_id; 10228 /* check args */ 10229 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10230 err = check_func_arg(env, i, &meta, fn, insn_idx); 10231 if (err) 10232 return err; 10233 } 10234 10235 err = record_func_map(env, &meta, func_id, insn_idx); 10236 if (err) 10237 return err; 10238 10239 err = record_func_key(env, &meta, func_id, insn_idx); 10240 if (err) 10241 return err; 10242 10243 regs = cur_regs(env); 10244 10245 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10246 * is inferred from register state. 10247 */ 10248 for (i = 0; i < meta.access_size; i++) { 10249 err = check_mem_access(env, insn_idx, regs + meta.regno, argno_from_reg(meta.regno), i, BPF_B, 10250 BPF_WRITE, -1, false, false); 10251 if (err) 10252 return err; 10253 } 10254 10255 if (meta.release_regno) { 10256 struct bpf_reg_state *reg = ®s[meta.release_regno]; 10257 bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) && 10258 (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU); 10259 10260 err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id); 10261 if (err) 10262 return err; 10263 } 10264 10265 switch (func_id) { 10266 case BPF_FUNC_tail_call: 10267 err = check_resource_leak(env, false, true, "tail_call"); 10268 if (err) 10269 return err; 10270 break; 10271 case BPF_FUNC_get_local_storage: 10272 /* check that flags argument in get_local_storage(map, flags) is 0, 10273 * this is required because get_local_storage() can't return an error. 10274 */ 10275 if (!bpf_register_is_null(®s[BPF_REG_2])) { 10276 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10277 return -EINVAL; 10278 } 10279 break; 10280 case BPF_FUNC_for_each_map_elem: 10281 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10282 set_map_elem_callback_state); 10283 break; 10284 case BPF_FUNC_timer_set_callback: 10285 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10286 set_timer_callback_state); 10287 break; 10288 case BPF_FUNC_find_vma: 10289 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10290 set_find_vma_callback_state); 10291 break; 10292 case BPF_FUNC_snprintf: 10293 err = check_bpf_snprintf_call(env, regs); 10294 break; 10295 case BPF_FUNC_loop: 10296 update_loop_inline_state(env, meta.subprogno); 10297 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10298 * is finished, thus mark it precise. 10299 */ 10300 err = mark_chain_precision(env, BPF_REG_1); 10301 if (err) 10302 return err; 10303 if (cur_func(env)->callback_depth < reg_umax(®s[BPF_REG_1])) { 10304 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10305 set_loop_callback_state); 10306 } else { 10307 cur_func(env)->callback_depth = 0; 10308 if (env->log.level & BPF_LOG_LEVEL2) 10309 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10310 env->cur_state->curframe); 10311 } 10312 break; 10313 case BPF_FUNC_dynptr_from_mem: 10314 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10315 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10316 reg_type_str(env, regs[BPF_REG_1].type)); 10317 return -EACCES; 10318 } 10319 break; 10320 case BPF_FUNC_set_retval: 10321 { 10322 struct bpf_retval_range range = { 10323 .minval = -MAX_ERRNO, 10324 .maxval = 0, 10325 .return_32bit = true 10326 }; 10327 struct bpf_reg_state *r1 = ®s[BPF_REG_1]; 10328 10329 if (r1->type != SCALAR_VALUE) { 10330 verbose(env, "R1 is not a scalar\n"); 10331 return -EINVAL; 10332 } 10333 10334 /* CGROUP_GETSOCKOPT is allowed to return arbitrary value */ 10335 if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT && 10336 env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) 10337 break; 10338 10339 if (prog_type == BPF_PROG_TYPE_LSM && 10340 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10341 if (!env->prog->aux->attach_func_proto->type) { 10342 /* Make sure programs that attach to void 10343 * hooks don't try to modify return value. 10344 */ 10345 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10346 return -EINVAL; 10347 } 10348 bpf_lsm_get_retval_range(env->prog, &range); 10349 } 10350 10351 err = mark_chain_precision(env, BPF_REG_1); 10352 if (err) 10353 return err; 10354 10355 if (!retval_range_within(range, r1)) { 10356 verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1"); 10357 return -EINVAL; 10358 } 10359 10360 break; 10361 } 10362 case BPF_FUNC_dynptr_write: 10363 { 10364 enum bpf_dynptr_type dynptr_type = meta.dynptr.type; 10365 10366 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10367 return -EFAULT; 10368 10369 if (dynptr_type == BPF_DYNPTR_TYPE_SKB || 10370 dynptr_type == BPF_DYNPTR_TYPE_SKB_META) 10371 /* this will trigger clear_all_pkt_pointers(), which will 10372 * invalidate all dynptr slices associated with the skb 10373 */ 10374 changes_data = true; 10375 10376 break; 10377 } 10378 case BPF_FUNC_per_cpu_ptr: 10379 case BPF_FUNC_this_cpu_ptr: 10380 { 10381 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10382 const struct btf_type *type; 10383 10384 if (reg->type & MEM_RCU) { 10385 type = btf_type_by_id(reg->btf, reg->btf_id); 10386 if (!type || !btf_type_is_struct(type)) { 10387 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10388 return -EFAULT; 10389 } 10390 returns_cpu_specific_alloc_ptr = true; 10391 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10392 } 10393 break; 10394 } 10395 case BPF_FUNC_user_ringbuf_drain: 10396 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10397 set_user_ringbuf_callback_state); 10398 break; 10399 } 10400 10401 if (err) 10402 return err; 10403 10404 /* reset caller saved regs */ 10405 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10406 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 10407 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10408 } 10409 invalidate_outgoing_stack_args(env, cur_func(env)); 10410 10411 /* helper call returns 64-bit value. */ 10412 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10413 10414 /* update return register (already marked as written above) */ 10415 ret_type = fn->ret_type; 10416 ret_flag = type_flag(ret_type); 10417 10418 switch (base_type(ret_type)) { 10419 case RET_INTEGER: 10420 /* sets type to SCALAR_VALUE */ 10421 mark_reg_unknown(env, regs, BPF_REG_0); 10422 break; 10423 case RET_VOID: 10424 regs[BPF_REG_0].type = NOT_INIT; 10425 break; 10426 case RET_PTR_TO_MAP_VALUE: 10427 /* There is no offset yet applied, variable or fixed */ 10428 mark_reg_known_zero(env, regs, BPF_REG_0); 10429 /* remember map_ptr, so that check_map_access() 10430 * can check 'value_size' boundary of memory access 10431 * to map element returned from bpf_map_lookup_elem() 10432 */ 10433 if (meta.map.ptr == NULL) { 10434 verifier_bug(env, "unexpected null map_ptr"); 10435 return -EFAULT; 10436 } 10437 10438 if (func_id == BPF_FUNC_map_lookup_elem && 10439 can_elide_value_nullness(meta.map.ptr) && 10440 meta.const_map_key >= 0 && 10441 meta.const_map_key < meta.map.ptr->max_entries) 10442 ret_flag &= ~PTR_MAYBE_NULL; 10443 10444 regs[BPF_REG_0].map_ptr = meta.map.ptr; 10445 regs[BPF_REG_0].map_uid = meta.map.uid; 10446 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10447 if (!type_may_be_null(ret_flag) && 10448 btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 10449 regs[BPF_REG_0].id = ++env->id_gen; 10450 } 10451 break; 10452 case RET_PTR_TO_SOCKET: 10453 mark_reg_known_zero(env, regs, BPF_REG_0); 10454 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10455 break; 10456 case RET_PTR_TO_SOCK_COMMON: 10457 mark_reg_known_zero(env, regs, BPF_REG_0); 10458 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10459 break; 10460 case RET_PTR_TO_TCP_SOCK: 10461 mark_reg_known_zero(env, regs, BPF_REG_0); 10462 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10463 break; 10464 case RET_PTR_TO_MEM: 10465 mark_reg_known_zero(env, regs, BPF_REG_0); 10466 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10467 regs[BPF_REG_0].mem_size = meta.mem_size; 10468 break; 10469 case RET_PTR_TO_MEM_OR_BTF_ID: 10470 { 10471 const struct btf_type *t; 10472 10473 mark_reg_known_zero(env, regs, BPF_REG_0); 10474 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10475 if (!btf_type_is_struct(t)) { 10476 u32 tsize; 10477 const struct btf_type *ret; 10478 const char *tname; 10479 10480 /* resolve the type size of ksym. */ 10481 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10482 if (IS_ERR(ret)) { 10483 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10484 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10485 tname, PTR_ERR(ret)); 10486 return -EINVAL; 10487 } 10488 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10489 regs[BPF_REG_0].mem_size = tsize; 10490 } else { 10491 if (returns_cpu_specific_alloc_ptr) { 10492 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10493 } else { 10494 /* MEM_RDONLY may be carried from ret_flag, but it 10495 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10496 * it will confuse the check of PTR_TO_BTF_ID in 10497 * check_mem_access(). 10498 */ 10499 ret_flag &= ~MEM_RDONLY; 10500 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10501 } 10502 10503 regs[BPF_REG_0].btf = meta.ret_btf; 10504 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10505 } 10506 break; 10507 } 10508 case RET_PTR_TO_BTF_ID: 10509 { 10510 struct btf *ret_btf; 10511 int ret_btf_id; 10512 10513 mark_reg_known_zero(env, regs, BPF_REG_0); 10514 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10515 if (func_id == BPF_FUNC_kptr_xchg) { 10516 ret_btf = meta.kptr_field->kptr.btf; 10517 ret_btf_id = meta.kptr_field->kptr.btf_id; 10518 if (!btf_is_kernel(ret_btf)) { 10519 regs[BPF_REG_0].type |= MEM_ALLOC; 10520 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10521 regs[BPF_REG_0].type |= MEM_PERCPU; 10522 } 10523 } else { 10524 if (fn->ret_btf_id == BPF_PTR_POISON) { 10525 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type", 10526 func_id_name(func_id)); 10527 return -EFAULT; 10528 } 10529 ret_btf = btf_vmlinux; 10530 ret_btf_id = *fn->ret_btf_id; 10531 } 10532 if (ret_btf_id == 0) { 10533 verbose(env, "invalid return type %u of func %s#%d\n", 10534 base_type(ret_type), func_id_name(func_id), 10535 func_id); 10536 return -EINVAL; 10537 } 10538 regs[BPF_REG_0].btf = ret_btf; 10539 regs[BPF_REG_0].btf_id = ret_btf_id; 10540 break; 10541 } 10542 default: 10543 verbose(env, "unknown return type %u of func %s#%d\n", 10544 base_type(ret_type), func_id_name(func_id), func_id); 10545 return -EINVAL; 10546 } 10547 10548 if (type_may_be_null(regs[BPF_REG_0].type)) 10549 regs[BPF_REG_0].id = ++env->id_gen; 10550 10551 if (is_ptr_cast_function(func_id) && 10552 find_reference_state(env->cur_state, meta.ref_obj.id)) { 10553 struct bpf_verifier_state *branch; 10554 struct bpf_reg_state *r0; 10555 10556 err = validate_ref_obj(env, &meta.ref_obj); 10557 if (err) 10558 return err; 10559 10560 /* 10561 * In order for a release of any of the original or cast pointers 10562 * to invalidate all other pointers, reuse the same reference id for 10563 * the cast result. 10564 * This reference id can't be used for nullness propagation, 10565 * as cast might return NULL for a non-NULL input. 10566 * Hence, explore the NULL case as a separate branch. 10567 */ 10568 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10569 if (IS_ERR(branch)) 10570 return PTR_ERR(branch); 10571 10572 r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0]; 10573 __mark_reg_known_zero(r0); 10574 r0->type = SCALAR_VALUE; 10575 10576 regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL; 10577 regs[BPF_REG_0].id = meta.ref_obj.id; 10578 } else if (is_acquire_function(func_id, meta.map.ptr)) { 10579 int id = acquire_reference(env, insn_idx, 0); 10580 10581 if (id < 0) 10582 return id; 10583 10584 regs[BPF_REG_0].id = id; 10585 } 10586 10587 if (func_id == BPF_FUNC_dynptr_data) 10588 regs[BPF_REG_0].parent_id = meta.dynptr.id; 10589 10590 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10591 if (err) 10592 return err; 10593 10594 err = check_map_func_compatibility(env, meta.map.ptr, func_id); 10595 if (err) 10596 return err; 10597 10598 if ((func_id == BPF_FUNC_get_stack || 10599 func_id == BPF_FUNC_get_task_stack) && 10600 !env->prog->has_callchain_buf) { 10601 const char *err_str; 10602 10603 #ifdef CONFIG_PERF_EVENTS 10604 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10605 err_str = "cannot get callchain buffer for func %s#%d\n"; 10606 #else 10607 err = -ENOTSUPP; 10608 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10609 #endif 10610 if (err) { 10611 verbose(env, err_str, func_id_name(func_id), func_id); 10612 return err; 10613 } 10614 10615 env->prog->has_callchain_buf = true; 10616 } 10617 10618 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10619 env->prog->call_get_stack = true; 10620 10621 if (func_id == BPF_FUNC_get_func_ip) { 10622 if (check_get_func_ip(env)) 10623 return -ENOTSUPP; 10624 env->prog->call_get_func_ip = true; 10625 } 10626 10627 if (func_id == BPF_FUNC_tail_call) { 10628 if (env->cur_state->curframe) { 10629 struct bpf_verifier_state *branch; 10630 10631 mark_reg_scratched(env, BPF_REG_0); 10632 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10633 if (IS_ERR(branch)) 10634 return PTR_ERR(branch); 10635 clear_all_pkt_pointers(env); 10636 mark_reg_unknown(env, regs, BPF_REG_0); 10637 err = prepare_func_exit(env, &env->insn_idx); 10638 if (err) 10639 return err; 10640 env->insn_idx--; 10641 } else { 10642 changes_data = false; 10643 } 10644 } 10645 10646 if (changes_data) 10647 clear_all_pkt_pointers(env); 10648 return 0; 10649 } 10650 10651 /* mark_btf_func_reg_size() is used when the reg size is determined by 10652 * the BTF func_proto's return value size and argument. 10653 */ 10654 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs, 10655 u32 regno, size_t reg_size) 10656 { 10657 struct bpf_reg_state *reg = ®s[regno]; 10658 10659 if (regno == BPF_REG_0) { 10660 /* Function return value */ 10661 reg->subreg_def = reg_size == sizeof(u64) ? 10662 DEF_NOT_SUBREG : env->insn_idx + 1; 10663 } else if (reg_size == sizeof(u64)) { 10664 /* Function argument */ 10665 mark_insn_zext(env, reg); 10666 } 10667 } 10668 10669 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10670 size_t reg_size) 10671 { 10672 return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size); 10673 } 10674 10675 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10676 { 10677 return meta->kfunc_flags & KF_ACQUIRE; 10678 } 10679 10680 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10681 { 10682 return meta->kfunc_flags & KF_RELEASE; 10683 } 10684 10685 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10686 { 10687 return meta->kfunc_flags & KF_DESTRUCTIVE; 10688 } 10689 10690 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10691 { 10692 return meta->kfunc_flags & KF_RCU; 10693 } 10694 10695 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10696 { 10697 return meta->kfunc_flags & KF_RCU_PROTECTED; 10698 } 10699 10700 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10701 const struct btf_param *arg, 10702 const struct bpf_reg_state *reg) 10703 { 10704 const struct btf_type *t; 10705 10706 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10707 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10708 return false; 10709 10710 return btf_param_match_suffix(btf, arg, "__sz"); 10711 } 10712 10713 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10714 const struct btf_param *arg, 10715 const struct bpf_reg_state *reg) 10716 { 10717 const struct btf_type *t; 10718 10719 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10720 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10721 return false; 10722 10723 return btf_param_match_suffix(btf, arg, "__szk"); 10724 } 10725 10726 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10727 { 10728 return btf_param_match_suffix(btf, arg, "__k"); 10729 } 10730 10731 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10732 { 10733 return btf_param_match_suffix(btf, arg, "__ign"); 10734 } 10735 10736 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 10737 { 10738 return btf_param_match_suffix(btf, arg, "__map"); 10739 } 10740 10741 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10742 { 10743 return btf_param_match_suffix(btf, arg, "__alloc"); 10744 } 10745 10746 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10747 { 10748 return btf_param_match_suffix(btf, arg, "__uninit"); 10749 } 10750 10751 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10752 { 10753 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 10754 } 10755 10756 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10757 { 10758 return btf_param_match_suffix(btf, arg, "__nullable"); 10759 } 10760 10761 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg) 10762 { 10763 return btf_param_match_suffix(btf, arg, "__nonown_allowed"); 10764 } 10765 10766 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10767 { 10768 return btf_param_match_suffix(btf, arg, "__str"); 10769 } 10770 10771 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg) 10772 { 10773 return btf_param_match_suffix(btf, arg, "__irq_flag"); 10774 } 10775 10776 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10777 const struct btf_param *arg, 10778 const char *name) 10779 { 10780 int len, target_len = strlen(name); 10781 const char *param_name; 10782 10783 param_name = btf_name_by_offset(btf, arg->name_off); 10784 if (str_is_empty(param_name)) 10785 return false; 10786 len = strlen(param_name); 10787 if (len != target_len) 10788 return false; 10789 if (strcmp(param_name, name)) 10790 return false; 10791 10792 return true; 10793 } 10794 10795 enum { 10796 KF_ARG_DYNPTR_ID, 10797 KF_ARG_LIST_HEAD_ID, 10798 KF_ARG_LIST_NODE_ID, 10799 KF_ARG_RB_ROOT_ID, 10800 KF_ARG_RB_NODE_ID, 10801 KF_ARG_WORKQUEUE_ID, 10802 KF_ARG_RES_SPIN_LOCK_ID, 10803 KF_ARG_TASK_WORK_ID, 10804 KF_ARG_PROG_AUX_ID, 10805 KF_ARG_TIMER_ID 10806 }; 10807 10808 BTF_ID_LIST(kf_arg_btf_ids) 10809 BTF_ID(struct, bpf_dynptr) 10810 BTF_ID(struct, bpf_list_head) 10811 BTF_ID(struct, bpf_list_node) 10812 BTF_ID(struct, bpf_rb_root) 10813 BTF_ID(struct, bpf_rb_node) 10814 BTF_ID(struct, bpf_wq) 10815 BTF_ID(struct, bpf_res_spin_lock) 10816 BTF_ID(struct, bpf_task_work) 10817 BTF_ID(struct, bpf_prog_aux) 10818 BTF_ID(struct, bpf_timer) 10819 10820 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10821 const struct btf_param *arg, int type) 10822 { 10823 const struct btf_type *t; 10824 u32 res_id; 10825 10826 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10827 if (!t) 10828 return false; 10829 if (!btf_type_is_ptr(t)) 10830 return false; 10831 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10832 if (!t) 10833 return false; 10834 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10835 } 10836 10837 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10838 { 10839 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10840 } 10841 10842 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10843 { 10844 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10845 } 10846 10847 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10848 { 10849 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10850 } 10851 10852 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10853 { 10854 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10855 } 10856 10857 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10858 { 10859 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10860 } 10861 10862 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg) 10863 { 10864 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID); 10865 } 10866 10867 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 10868 { 10869 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 10870 } 10871 10872 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg) 10873 { 10874 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID); 10875 } 10876 10877 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg) 10878 { 10879 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID); 10880 } 10881 10882 static bool is_rbtree_node_type(const struct btf_type *t) 10883 { 10884 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]); 10885 } 10886 10887 static bool is_list_node_type(const struct btf_type *t) 10888 { 10889 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]); 10890 } 10891 10892 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10893 const struct btf_param *arg) 10894 { 10895 const struct btf_type *t; 10896 10897 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10898 if (!t) 10899 return false; 10900 10901 return true; 10902 } 10903 10904 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg) 10905 { 10906 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID); 10907 } 10908 10909 /* 10910 * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF: 10911 * - the _impl prototype with full arg list (meta->func_proto) 10912 * - the BPF API prototype w/o implicit args (func->type in BTF) 10913 * To determine whether an argument is implicit, we compare its position 10914 * against the number of arguments in the prototype w/o implicit args. 10915 */ 10916 static bool is_kfunc_arg_implicit(const struct bpf_kfunc_call_arg_meta *meta, u32 arg_idx) 10917 { 10918 const struct btf_type *func, *func_proto; 10919 u32 argn; 10920 10921 if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS)) 10922 return false; 10923 10924 func = btf_type_by_id(meta->btf, meta->func_id); 10925 func_proto = btf_type_by_id(meta->btf, func->type); 10926 argn = btf_type_vlen(func_proto); 10927 10928 return argn <= arg_idx; 10929 } 10930 10931 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10932 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10933 const struct btf *btf, 10934 const struct btf_type *t, int rec) 10935 { 10936 const struct btf_type *member_type; 10937 const struct btf_member *member; 10938 u32 i; 10939 10940 if (!btf_type_is_struct(t)) 10941 return false; 10942 10943 for_each_member(i, t, member) { 10944 const struct btf_array *array; 10945 10946 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10947 if (btf_type_is_struct(member_type)) { 10948 if (rec >= 3) { 10949 verbose(env, "max struct nesting depth exceeded\n"); 10950 return false; 10951 } 10952 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10953 return false; 10954 continue; 10955 } 10956 if (btf_type_is_array(member_type)) { 10957 array = btf_array(member_type); 10958 if (!array->nelems) 10959 return false; 10960 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10961 if (!btf_type_is_scalar(member_type)) 10962 return false; 10963 continue; 10964 } 10965 if (!btf_type_is_scalar(member_type)) 10966 return false; 10967 } 10968 return true; 10969 } 10970 10971 enum kfunc_ptr_arg_type { 10972 KF_ARG_PTR_TO_CTX, 10973 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10974 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10975 KF_ARG_PTR_TO_DYNPTR, 10976 KF_ARG_PTR_TO_ITER, 10977 KF_ARG_PTR_TO_LIST_HEAD, 10978 KF_ARG_PTR_TO_LIST_NODE, 10979 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10980 KF_ARG_PTR_TO_MEM, 10981 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10982 KF_ARG_PTR_TO_CALLBACK, 10983 KF_ARG_PTR_TO_RB_ROOT, 10984 KF_ARG_PTR_TO_RB_NODE, 10985 KF_ARG_PTR_TO_NULL, 10986 KF_ARG_PTR_TO_CONST_STR, 10987 KF_ARG_PTR_TO_MAP, 10988 KF_ARG_PTR_TO_TIMER, 10989 KF_ARG_PTR_TO_WORKQUEUE, 10990 KF_ARG_PTR_TO_IRQ_FLAG, 10991 KF_ARG_PTR_TO_RES_SPIN_LOCK, 10992 KF_ARG_PTR_TO_TASK_WORK, 10993 }; 10994 10995 enum special_kfunc_type { 10996 KF_bpf_obj_new_impl, 10997 KF_bpf_obj_new, 10998 KF_bpf_obj_drop_impl, 10999 KF_bpf_obj_drop, 11000 KF_bpf_refcount_acquire_impl, 11001 KF_bpf_refcount_acquire, 11002 KF_bpf_list_push_front_impl, 11003 KF_bpf_list_push_front, 11004 KF_bpf_list_push_back_impl, 11005 KF_bpf_list_push_back, 11006 KF_bpf_list_add, 11007 KF_bpf_list_pop_front, 11008 KF_bpf_list_pop_back, 11009 KF_bpf_list_del, 11010 KF_bpf_list_front, 11011 KF_bpf_list_back, 11012 KF_bpf_list_is_first, 11013 KF_bpf_list_is_last, 11014 KF_bpf_list_empty, 11015 KF_bpf_cast_to_kern_ctx, 11016 KF_bpf_rdonly_cast, 11017 KF_bpf_rcu_read_lock, 11018 KF_bpf_rcu_read_unlock, 11019 KF_bpf_rbtree_remove, 11020 KF_bpf_rbtree_add_impl, 11021 KF_bpf_rbtree_add, 11022 KF_bpf_rbtree_first, 11023 KF_bpf_rbtree_root, 11024 KF_bpf_rbtree_left, 11025 KF_bpf_rbtree_right, 11026 KF_bpf_dynptr_from_skb, 11027 KF_bpf_dynptr_from_xdp, 11028 KF_bpf_dynptr_from_skb_meta, 11029 KF_bpf_xdp_pull_data, 11030 KF_bpf_dynptr_slice, 11031 KF_bpf_dynptr_slice_rdwr, 11032 KF_bpf_dynptr_clone, 11033 KF_bpf_percpu_obj_new_impl, 11034 KF_bpf_percpu_obj_new, 11035 KF_bpf_percpu_obj_drop_impl, 11036 KF_bpf_percpu_obj_drop, 11037 KF_bpf_throw, 11038 KF_bpf_wq_set_callback, 11039 KF_bpf_preempt_disable, 11040 KF_bpf_preempt_enable, 11041 KF_bpf_iter_css_task_new, 11042 KF_bpf_session_cookie, 11043 KF_bpf_get_kmem_cache, 11044 KF_bpf_local_irq_save, 11045 KF_bpf_local_irq_restore, 11046 KF_bpf_iter_num_new, 11047 KF_bpf_iter_num_next, 11048 KF_bpf_iter_num_destroy, 11049 KF_bpf_set_dentry_xattr, 11050 KF_bpf_remove_dentry_xattr, 11051 KF_bpf_res_spin_lock, 11052 KF_bpf_res_spin_unlock, 11053 KF_bpf_res_spin_lock_irqsave, 11054 KF_bpf_res_spin_unlock_irqrestore, 11055 KF_bpf_dynptr_from_file, 11056 KF_bpf_dynptr_file_discard, 11057 KF___bpf_trap, 11058 KF_bpf_task_work_schedule_signal, 11059 KF_bpf_task_work_schedule_resume, 11060 KF_bpf_arena_alloc_pages, 11061 KF_bpf_arena_free_pages, 11062 KF_bpf_arena_reserve_pages, 11063 KF_bpf_session_is_return, 11064 KF_bpf_stream_vprintk, 11065 KF_bpf_stream_print_stack, 11066 }; 11067 11068 BTF_ID_LIST(special_kfunc_list) 11069 BTF_ID(func, bpf_obj_new_impl) 11070 BTF_ID(func, bpf_obj_new) 11071 BTF_ID(func, bpf_obj_drop_impl) 11072 BTF_ID(func, bpf_obj_drop) 11073 BTF_ID(func, bpf_refcount_acquire_impl) 11074 BTF_ID(func, bpf_refcount_acquire) 11075 BTF_ID(func, bpf_list_push_front_impl) 11076 BTF_ID(func, bpf_list_push_front) 11077 BTF_ID(func, bpf_list_push_back_impl) 11078 BTF_ID(func, bpf_list_push_back) 11079 BTF_ID(func, bpf_list_add) 11080 BTF_ID(func, bpf_list_pop_front) 11081 BTF_ID(func, bpf_list_pop_back) 11082 BTF_ID(func, bpf_list_del) 11083 BTF_ID(func, bpf_list_front) 11084 BTF_ID(func, bpf_list_back) 11085 BTF_ID(func, bpf_list_is_first) 11086 BTF_ID(func, bpf_list_is_last) 11087 BTF_ID(func, bpf_list_empty) 11088 BTF_ID(func, bpf_cast_to_kern_ctx) 11089 BTF_ID(func, bpf_rdonly_cast) 11090 BTF_ID(func, bpf_rcu_read_lock) 11091 BTF_ID(func, bpf_rcu_read_unlock) 11092 BTF_ID(func, bpf_rbtree_remove) 11093 BTF_ID(func, bpf_rbtree_add_impl) 11094 BTF_ID(func, bpf_rbtree_add) 11095 BTF_ID(func, bpf_rbtree_first) 11096 BTF_ID(func, bpf_rbtree_root) 11097 BTF_ID(func, bpf_rbtree_left) 11098 BTF_ID(func, bpf_rbtree_right) 11099 #ifdef CONFIG_NET 11100 BTF_ID(func, bpf_dynptr_from_skb) 11101 BTF_ID(func, bpf_dynptr_from_xdp) 11102 BTF_ID(func, bpf_dynptr_from_skb_meta) 11103 BTF_ID(func, bpf_xdp_pull_data) 11104 #else 11105 BTF_ID_UNUSED 11106 BTF_ID_UNUSED 11107 BTF_ID_UNUSED 11108 BTF_ID_UNUSED 11109 #endif 11110 BTF_ID(func, bpf_dynptr_slice) 11111 BTF_ID(func, bpf_dynptr_slice_rdwr) 11112 BTF_ID(func, bpf_dynptr_clone) 11113 BTF_ID(func, bpf_percpu_obj_new_impl) 11114 BTF_ID(func, bpf_percpu_obj_new) 11115 BTF_ID(func, bpf_percpu_obj_drop_impl) 11116 BTF_ID(func, bpf_percpu_obj_drop) 11117 BTF_ID(func, bpf_throw) 11118 BTF_ID(func, bpf_wq_set_callback) 11119 BTF_ID(func, bpf_preempt_disable) 11120 BTF_ID(func, bpf_preempt_enable) 11121 #ifdef CONFIG_CGROUPS 11122 BTF_ID(func, bpf_iter_css_task_new) 11123 #else 11124 BTF_ID_UNUSED 11125 #endif 11126 #ifdef CONFIG_BPF_EVENTS 11127 BTF_ID(func, bpf_session_cookie) 11128 #else 11129 BTF_ID_UNUSED 11130 #endif 11131 BTF_ID(func, bpf_get_kmem_cache) 11132 BTF_ID(func, bpf_local_irq_save) 11133 BTF_ID(func, bpf_local_irq_restore) 11134 BTF_ID(func, bpf_iter_num_new) 11135 BTF_ID(func, bpf_iter_num_next) 11136 BTF_ID(func, bpf_iter_num_destroy) 11137 #ifdef CONFIG_BPF_LSM 11138 BTF_ID(func, bpf_set_dentry_xattr) 11139 BTF_ID(func, bpf_remove_dentry_xattr) 11140 #else 11141 BTF_ID_UNUSED 11142 BTF_ID_UNUSED 11143 #endif 11144 BTF_ID(func, bpf_res_spin_lock) 11145 BTF_ID(func, bpf_res_spin_unlock) 11146 BTF_ID(func, bpf_res_spin_lock_irqsave) 11147 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 11148 BTF_ID(func, bpf_dynptr_from_file) 11149 BTF_ID(func, bpf_dynptr_file_discard) 11150 BTF_ID(func, __bpf_trap) 11151 BTF_ID(func, bpf_task_work_schedule_signal) 11152 BTF_ID(func, bpf_task_work_schedule_resume) 11153 BTF_ID(func, bpf_arena_alloc_pages) 11154 BTF_ID(func, bpf_arena_free_pages) 11155 BTF_ID(func, bpf_arena_reserve_pages) 11156 #ifdef CONFIG_BPF_EVENTS 11157 BTF_ID(func, bpf_session_is_return) 11158 #else 11159 BTF_ID_UNUSED 11160 #endif 11161 BTF_ID(func, bpf_stream_vprintk) 11162 BTF_ID(func, bpf_stream_print_stack) 11163 11164 static bool is_bpf_obj_new_kfunc(u32 func_id) 11165 { 11166 return func_id == special_kfunc_list[KF_bpf_obj_new] || 11167 func_id == special_kfunc_list[KF_bpf_obj_new_impl]; 11168 } 11169 11170 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id) 11171 { 11172 return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] || 11173 func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]; 11174 } 11175 11176 static bool is_bpf_obj_drop_kfunc(u32 func_id) 11177 { 11178 return func_id == special_kfunc_list[KF_bpf_obj_drop] || 11179 func_id == special_kfunc_list[KF_bpf_obj_drop_impl]; 11180 } 11181 11182 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id) 11183 { 11184 return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] || 11185 func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]; 11186 } 11187 11188 static bool is_bpf_refcount_acquire_kfunc(u32 func_id) 11189 { 11190 return func_id == special_kfunc_list[KF_bpf_refcount_acquire] || 11191 func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11192 } 11193 11194 static bool is_bpf_list_push_kfunc(u32 func_id) 11195 { 11196 return func_id == special_kfunc_list[KF_bpf_list_push_front] || 11197 func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11198 func_id == special_kfunc_list[KF_bpf_list_push_back] || 11199 func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11200 func_id == special_kfunc_list[KF_bpf_list_add]; 11201 } 11202 11203 static bool is_bpf_rbtree_add_kfunc(u32 func_id) 11204 { 11205 return func_id == special_kfunc_list[KF_bpf_rbtree_add] || 11206 func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11207 } 11208 11209 static bool is_task_work_add_kfunc(u32 func_id) 11210 { 11211 return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] || 11212 func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume]; 11213 } 11214 11215 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11216 { 11217 if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref) 11218 return false; 11219 11220 return meta->kfunc_flags & KF_RET_NULL; 11221 } 11222 11223 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11224 { 11225 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11226 } 11227 11228 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11229 { 11230 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11231 } 11232 11233 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11234 { 11235 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11236 } 11237 11238 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11239 { 11240 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11241 } 11242 11243 bool bpf_is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta) 11244 { 11245 return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data]; 11246 } 11247 11248 static enum kfunc_ptr_arg_type 11249 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, struct bpf_func_state *caller, 11250 struct bpf_reg_state *regs, struct bpf_kfunc_call_arg_meta *meta, 11251 const struct btf_type *t, const struct btf_type *ref_t, 11252 const char *ref_tname, const struct btf_param *args, 11253 int arg, int nargs, argno_t argno, struct bpf_reg_state *reg) 11254 { 11255 bool arg_mem_size = false; 11256 11257 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 11258 meta->func_id == special_kfunc_list[KF_bpf_session_is_return] || 11259 meta->func_id == special_kfunc_list[KF_bpf_session_cookie]) 11260 return KF_ARG_PTR_TO_CTX; 11261 11262 if (arg + 1 < nargs && 11263 (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)) || 11264 is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)))) 11265 arg_mem_size = true; 11266 11267 /* In this function, we verify the kfunc's BTF as per the argument type, 11268 * leaving the rest of the verification with respect to the register 11269 * type to our caller. When a set of conditions hold in the BTF type of 11270 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11271 */ 11272 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg)) 11273 return KF_ARG_PTR_TO_CTX; 11274 11275 if (is_kfunc_arg_nullable(meta->btf, &args[arg]) && bpf_register_is_null(reg) && 11276 !arg_mem_size) 11277 return KF_ARG_PTR_TO_NULL; 11278 11279 if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg])) 11280 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11281 11282 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg])) 11283 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11284 11285 if (is_kfunc_arg_dynptr(meta->btf, &args[arg])) 11286 return KF_ARG_PTR_TO_DYNPTR; 11287 11288 if (is_kfunc_arg_iter(meta, arg, &args[arg])) 11289 return KF_ARG_PTR_TO_ITER; 11290 11291 if (is_kfunc_arg_list_head(meta->btf, &args[arg])) 11292 return KF_ARG_PTR_TO_LIST_HEAD; 11293 11294 if (is_kfunc_arg_list_node(meta->btf, &args[arg])) 11295 return KF_ARG_PTR_TO_LIST_NODE; 11296 11297 if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg])) 11298 return KF_ARG_PTR_TO_RB_ROOT; 11299 11300 if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg])) 11301 return KF_ARG_PTR_TO_RB_NODE; 11302 11303 if (is_kfunc_arg_const_str(meta->btf, &args[arg])) 11304 return KF_ARG_PTR_TO_CONST_STR; 11305 11306 if (is_kfunc_arg_map(meta->btf, &args[arg])) 11307 return KF_ARG_PTR_TO_MAP; 11308 11309 if (is_kfunc_arg_wq(meta->btf, &args[arg])) 11310 return KF_ARG_PTR_TO_WORKQUEUE; 11311 11312 if (is_kfunc_arg_timer(meta->btf, &args[arg])) 11313 return KF_ARG_PTR_TO_TIMER; 11314 11315 if (is_kfunc_arg_task_work(meta->btf, &args[arg])) 11316 return KF_ARG_PTR_TO_TASK_WORK; 11317 11318 if (is_kfunc_arg_irq_flag(meta->btf, &args[arg])) 11319 return KF_ARG_PTR_TO_IRQ_FLAG; 11320 11321 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg])) 11322 return KF_ARG_PTR_TO_RES_SPIN_LOCK; 11323 11324 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11325 if (!btf_type_is_struct(ref_t)) { 11326 verbose(env, "kernel function %s %s pointer type %s %s is not supported\n", 11327 meta->func_name, reg_arg_name(env, argno), 11328 btf_type_str(ref_t), ref_tname); 11329 return -EINVAL; 11330 } 11331 return KF_ARG_PTR_TO_BTF_ID; 11332 } 11333 11334 if (is_kfunc_arg_callback(env, meta->btf, &args[arg])) 11335 return KF_ARG_PTR_TO_CALLBACK; 11336 11337 /* This is the catch all argument type of register types supported by 11338 * check_helper_mem_access. However, we only allow when argument type is 11339 * pointer to scalar, or struct composed (recursively) of scalars. When 11340 * arg_mem_size is true, the pointer can be void *. 11341 */ 11342 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11343 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11344 verbose(env, "%s pointer type %s %s must point to %sscalar, or struct with scalar\n", 11345 reg_arg_name(env, argno), 11346 btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11347 return -EINVAL; 11348 } 11349 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11350 } 11351 11352 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11353 struct bpf_reg_state *reg, 11354 const struct btf_type *ref_t, 11355 const char *ref_tname, u32 ref_id, 11356 struct bpf_kfunc_call_arg_meta *meta, 11357 int arg, argno_t argno) 11358 { 11359 const struct btf_type *reg_ref_t; 11360 bool strict_type_match = false; 11361 const struct btf *reg_btf; 11362 const char *reg_ref_tname; 11363 bool taking_projection; 11364 bool struct_same; 11365 u32 reg_ref_id; 11366 11367 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11368 reg_btf = reg->btf; 11369 reg_ref_id = reg->btf_id; 11370 } else { 11371 reg_btf = btf_vmlinux; 11372 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11373 } 11374 11375 /* Enforce strict type matching for calls to kfuncs that are acquiring 11376 * or releasing a reference, or are no-cast aliases. We do _not_ 11377 * enforce strict matching for kfuncs by default, 11378 * as we want to enable BPF programs to pass types that are bitwise 11379 * equivalent without forcing them to explicitly cast with something 11380 * like bpf_cast_to_kern_ctx(). 11381 * 11382 * For example, say we had a type like the following: 11383 * 11384 * struct bpf_cpumask { 11385 * cpumask_t cpumask; 11386 * refcount_t usage; 11387 * }; 11388 * 11389 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11390 * to a struct cpumask, so it would be safe to pass a struct 11391 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11392 * 11393 * The philosophy here is similar to how we allow scalars of different 11394 * types to be passed to kfuncs as long as the size is the same. The 11395 * only difference here is that we're simply allowing 11396 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11397 * resolve types. 11398 */ 11399 if ((is_kfunc_release(meta) && reg_is_referenced(env, reg)) || 11400 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11401 strict_type_match = true; 11402 11403 WARN_ON_ONCE(is_kfunc_release(meta) && !tnum_is_const(reg->var_off)); 11404 11405 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11406 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11407 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->var_off.value, 11408 meta->btf, ref_id, strict_type_match); 11409 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11410 * actually use it -- it must cast to the underlying type. So we allow 11411 * caller to pass in the underlying type. 11412 */ 11413 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11414 if (!taking_projection && !struct_same) { 11415 verbose(env, "kernel function %s %s expected pointer to %s %s but %s has a pointer to %s %s\n", 11416 meta->func_name, reg_arg_name(env, argno), 11417 btf_type_str(ref_t), ref_tname, reg_arg_name(env, argno), 11418 btf_type_str(reg_ref_t), reg_ref_tname); 11419 return -EINVAL; 11420 } 11421 return 0; 11422 } 11423 11424 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 11425 struct bpf_kfunc_call_arg_meta *meta) 11426 { 11427 int err, spi, kfunc_class = IRQ_NATIVE_KFUNC; 11428 bool irq_save; 11429 11430 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] || 11431 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) { 11432 irq_save = true; 11433 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 11434 kfunc_class = IRQ_LOCK_KFUNC; 11435 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] || 11436 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) { 11437 irq_save = false; 11438 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 11439 kfunc_class = IRQ_LOCK_KFUNC; 11440 } else { 11441 verifier_bug(env, "unknown irq flags kfunc"); 11442 return -EFAULT; 11443 } 11444 11445 if (irq_save) { 11446 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 11447 verbose(env, "expected uninitialized irq flag as %s\n", 11448 reg_arg_name(env, argno)); 11449 return -EINVAL; 11450 } 11451 11452 err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW, 11453 BPF_WRITE, -1, false, false); 11454 if (err) 11455 return err; 11456 11457 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 11458 if (err) 11459 return err; 11460 } else { 11461 err = is_irq_flag_reg_valid_init(env, reg); 11462 if (err) { 11463 verbose(env, "expected an initialized irq flag as %s\n", 11464 reg_arg_name(env, argno)); 11465 return err; 11466 } 11467 11468 spi = irq_flag_get_spi(env, reg); 11469 if (spi < 0) 11470 return spi; 11471 11472 mark_stack_slots_scratched(env, spi, 1); 11473 11474 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 11475 if (err) 11476 return err; 11477 } 11478 return 0; 11479 } 11480 11481 11482 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11483 { 11484 struct btf_record *rec = reg_btf_record(reg); 11485 11486 if (!env->cur_state->active_locks) { 11487 verifier_bug(env, "%s w/o active lock", __func__); 11488 return -EFAULT; 11489 } 11490 11491 if (type_flag(reg->type) & NON_OWN_REF) { 11492 verifier_bug(env, "NON_OWN_REF already set"); 11493 return -EFAULT; 11494 } 11495 11496 reg->type |= NON_OWN_REF; 11497 if (rec->refcount_off >= 0) 11498 reg->type |= MEM_RCU; 11499 11500 return 0; 11501 } 11502 11503 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id) 11504 { 11505 struct bpf_func_state *unused; 11506 struct bpf_reg_state *reg; 11507 11508 WARN_ON_ONCE(release_reference_nomark(env->cur_state, id)); 11509 11510 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11511 if (reg->id == id) { 11512 reg->id = 0; 11513 ref_set_non_owning(env, reg); 11514 } 11515 })); 11516 11517 return; 11518 } 11519 11520 /* Implementation details: 11521 * 11522 * Each register points to some region of memory, which we define as an 11523 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11524 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11525 * allocation. The lock and the data it protects are colocated in the same 11526 * memory region. 11527 * 11528 * Hence, everytime a register holds a pointer value pointing to such 11529 * allocation, the verifier preserves a unique reg->id for it. 11530 * 11531 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11532 * bpf_spin_lock is called. 11533 * 11534 * To enable this, lock state in the verifier captures two values: 11535 * active_lock.ptr = Register's type specific pointer 11536 * active_lock.id = A unique ID for each register pointer value 11537 * 11538 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11539 * supported register types. 11540 * 11541 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11542 * allocated objects is the reg->btf pointer. 11543 * 11544 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11545 * can establish the provenance of the map value statically for each distinct 11546 * lookup into such maps. They always contain a single map value hence unique 11547 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11548 * 11549 * So, in case of global variables, they use array maps with max_entries = 1, 11550 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11551 * into the same map value as max_entries is 1, as described above). 11552 * 11553 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11554 * outer map pointer (in verifier context), but each lookup into an inner map 11555 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11556 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11557 * will get different reg->id assigned to each lookup, hence different 11558 * active_lock.id. 11559 * 11560 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11561 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11562 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11563 */ 11564 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11565 { 11566 struct bpf_reference_state *s; 11567 void *ptr; 11568 u32 id; 11569 11570 switch ((int)reg->type) { 11571 case PTR_TO_MAP_VALUE: 11572 ptr = reg->map_ptr; 11573 break; 11574 case PTR_TO_BTF_ID | MEM_ALLOC: 11575 ptr = reg->btf; 11576 break; 11577 default: 11578 verifier_bug(env, "unknown reg type for lock check"); 11579 return -EFAULT; 11580 } 11581 id = reg->id; 11582 11583 if (!env->cur_state->active_locks) 11584 return -EINVAL; 11585 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 11586 if (!s) { 11587 verbose(env, "held lock and object are not in the same allocation\n"); 11588 return -EINVAL; 11589 } 11590 return 0; 11591 } 11592 11593 static bool is_bpf_list_api_kfunc(u32 btf_id) 11594 { 11595 return is_bpf_list_push_kfunc(btf_id) || 11596 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11597 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 11598 btf_id == special_kfunc_list[KF_bpf_list_del] || 11599 btf_id == special_kfunc_list[KF_bpf_list_front] || 11600 btf_id == special_kfunc_list[KF_bpf_list_back] || 11601 btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11602 btf_id == special_kfunc_list[KF_bpf_list_is_last] || 11603 btf_id == special_kfunc_list[KF_bpf_list_empty]; 11604 } 11605 11606 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11607 { 11608 return is_bpf_rbtree_add_kfunc(btf_id) || 11609 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11610 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 11611 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 11612 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11613 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 11614 } 11615 11616 static bool is_bpf_iter_num_api_kfunc(u32 btf_id) 11617 { 11618 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] || 11619 btf_id == special_kfunc_list[KF_bpf_iter_num_next] || 11620 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy]; 11621 } 11622 11623 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11624 { 11625 return is_bpf_list_api_kfunc(btf_id) || 11626 is_bpf_rbtree_api_kfunc(btf_id) || 11627 is_bpf_refcount_acquire_kfunc(btf_id); 11628 } 11629 11630 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id) 11631 { 11632 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 11633 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 11634 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 11635 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]; 11636 } 11637 11638 static bool is_bpf_arena_kfunc(u32 btf_id) 11639 { 11640 return btf_id == special_kfunc_list[KF_bpf_arena_alloc_pages] || 11641 btf_id == special_kfunc_list[KF_bpf_arena_free_pages] || 11642 btf_id == special_kfunc_list[KF_bpf_arena_reserve_pages]; 11643 } 11644 11645 static bool is_bpf_stream_kfunc(u32 btf_id) 11646 { 11647 return btf_id == special_kfunc_list[KF_bpf_stream_vprintk] || 11648 btf_id == special_kfunc_list[KF_bpf_stream_print_stack]; 11649 } 11650 11651 static bool kfunc_spin_allowed(u32 btf_id) 11652 { 11653 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) || 11654 is_bpf_res_spin_lock_kfunc(btf_id) || is_bpf_arena_kfunc(btf_id) || 11655 is_bpf_stream_kfunc(btf_id); 11656 } 11657 11658 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11659 { 11660 return is_bpf_rbtree_add_kfunc(btf_id); 11661 } 11662 11663 static bool is_async_callback_calling_kfunc(u32 btf_id) 11664 { 11665 return is_bpf_wq_set_callback_kfunc(btf_id) || 11666 is_task_work_add_kfunc(btf_id); 11667 } 11668 11669 bool bpf_is_throw_kfunc(struct bpf_insn *insn) 11670 { 11671 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11672 insn->imm == special_kfunc_list[KF_bpf_throw]; 11673 } 11674 11675 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id) 11676 { 11677 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback]; 11678 } 11679 11680 static bool is_callback_calling_kfunc(u32 btf_id) 11681 { 11682 return is_sync_callback_calling_kfunc(btf_id) || 11683 is_async_callback_calling_kfunc(btf_id); 11684 } 11685 11686 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11687 { 11688 return is_bpf_rbtree_api_kfunc(btf_id); 11689 } 11690 11691 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11692 enum btf_field_type head_field_type, 11693 u32 kfunc_btf_id) 11694 { 11695 bool ret; 11696 11697 switch (head_field_type) { 11698 case BPF_LIST_HEAD: 11699 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11700 break; 11701 case BPF_RB_ROOT: 11702 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11703 break; 11704 default: 11705 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11706 btf_field_type_name(head_field_type)); 11707 return false; 11708 } 11709 11710 if (!ret) 11711 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11712 btf_field_type_name(head_field_type)); 11713 return ret; 11714 } 11715 11716 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11717 enum btf_field_type node_field_type, 11718 u32 kfunc_btf_id) 11719 { 11720 bool ret; 11721 11722 switch (node_field_type) { 11723 case BPF_LIST_NODE: 11724 ret = is_bpf_list_push_kfunc(kfunc_btf_id) || 11725 kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] || 11726 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11727 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last]; 11728 break; 11729 case BPF_RB_NODE: 11730 ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) || 11731 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11732 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11733 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 11734 break; 11735 default: 11736 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11737 btf_field_type_name(node_field_type)); 11738 return false; 11739 } 11740 11741 if (!ret) 11742 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11743 btf_field_type_name(node_field_type)); 11744 return ret; 11745 } 11746 11747 static int 11748 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11749 struct bpf_reg_state *reg, argno_t argno, 11750 struct bpf_kfunc_call_arg_meta *meta, 11751 enum btf_field_type head_field_type, 11752 struct btf_field **head_field) 11753 { 11754 const char *head_type_name; 11755 struct btf_field *field; 11756 struct btf_record *rec; 11757 u32 head_off; 11758 11759 if (meta->btf != btf_vmlinux) { 11760 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11761 return -EFAULT; 11762 } 11763 11764 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11765 return -EFAULT; 11766 11767 head_type_name = btf_field_type_name(head_field_type); 11768 if (!tnum_is_const(reg->var_off)) { 11769 verbose(env, 11770 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11771 reg_arg_name(env, argno), head_type_name); 11772 return -EINVAL; 11773 } 11774 11775 rec = reg_btf_record(reg); 11776 head_off = reg->var_off.value; 11777 field = btf_record_find(rec, head_off, head_field_type); 11778 if (!field) { 11779 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11780 return -EINVAL; 11781 } 11782 11783 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11784 if (check_reg_allocation_locked(env, reg)) { 11785 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11786 rec->spin_lock_off, head_type_name); 11787 return -EINVAL; 11788 } 11789 11790 if (*head_field) { 11791 verifier_bug(env, "repeating %s arg", head_type_name); 11792 return -EFAULT; 11793 } 11794 *head_field = field; 11795 return 0; 11796 } 11797 11798 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11799 struct bpf_reg_state *reg, argno_t argno, 11800 struct bpf_kfunc_call_arg_meta *meta) 11801 { 11802 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD, 11803 &meta->arg_list_head.field); 11804 } 11805 11806 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11807 struct bpf_reg_state *reg, argno_t argno, 11808 struct bpf_kfunc_call_arg_meta *meta) 11809 { 11810 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT, 11811 &meta->arg_rbtree_root.field); 11812 } 11813 11814 static int 11815 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11816 struct bpf_reg_state *reg, argno_t argno, 11817 struct bpf_kfunc_call_arg_meta *meta, 11818 enum btf_field_type head_field_type, 11819 enum btf_field_type node_field_type, 11820 struct btf_field **node_field) 11821 { 11822 const char *node_type_name; 11823 const struct btf_type *et, *t; 11824 struct btf_field *field; 11825 u32 node_off; 11826 11827 if (meta->btf != btf_vmlinux) { 11828 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11829 return -EFAULT; 11830 } 11831 11832 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11833 return -EFAULT; 11834 11835 node_type_name = btf_field_type_name(node_field_type); 11836 if (!tnum_is_const(reg->var_off)) { 11837 verbose(env, 11838 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11839 reg_arg_name(env, argno), node_type_name); 11840 return -EINVAL; 11841 } 11842 11843 node_off = reg->var_off.value; 11844 field = reg_find_field_offset(reg, node_off, node_field_type); 11845 if (!field) { 11846 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11847 return -EINVAL; 11848 } 11849 11850 field = *node_field; 11851 11852 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11853 t = btf_type_by_id(reg->btf, reg->btf_id); 11854 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11855 field->graph_root.value_btf_id, true)) { 11856 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11857 "in struct %s, but arg is at offset=%d in struct %s\n", 11858 btf_field_type_name(head_field_type), 11859 btf_field_type_name(node_field_type), 11860 field->graph_root.node_offset, 11861 btf_name_by_offset(field->graph_root.btf, et->name_off), 11862 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11863 return -EINVAL; 11864 } 11865 meta->arg_btf = reg->btf; 11866 meta->arg_btf_id = reg->btf_id; 11867 11868 if (node_off != field->graph_root.node_offset) { 11869 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11870 node_off, btf_field_type_name(node_field_type), 11871 field->graph_root.node_offset, 11872 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11873 return -EINVAL; 11874 } 11875 11876 return 0; 11877 } 11878 11879 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11880 struct bpf_reg_state *reg, argno_t argno, 11881 struct bpf_kfunc_call_arg_meta *meta) 11882 { 11883 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 11884 BPF_LIST_HEAD, BPF_LIST_NODE, 11885 &meta->arg_list_head.field); 11886 } 11887 11888 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11889 struct bpf_reg_state *reg, argno_t argno, 11890 struct bpf_kfunc_call_arg_meta *meta) 11891 { 11892 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 11893 BPF_RB_ROOT, BPF_RB_NODE, 11894 &meta->arg_rbtree_root.field); 11895 } 11896 11897 /* 11898 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11899 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11900 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11901 * them can only be attached to some specific hook points. 11902 */ 11903 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11904 { 11905 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11906 11907 switch (prog_type) { 11908 case BPF_PROG_TYPE_LSM: 11909 return true; 11910 case BPF_PROG_TYPE_TRACING: 11911 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11912 return true; 11913 fallthrough; 11914 default: 11915 return in_sleepable(env); 11916 } 11917 } 11918 11919 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11920 int insn_idx) 11921 { 11922 const char *func_name = meta->func_name, *ref_tname; 11923 struct bpf_func_state *caller = cur_func(env); 11924 struct bpf_reg_state *regs = cur_regs(env); 11925 const struct btf *btf = meta->btf; 11926 const struct btf_param *args; 11927 struct btf_record *rec; 11928 u32 i, nargs; 11929 int ret; 11930 11931 args = (const struct btf_param *)(meta->func_proto + 1); 11932 nargs = btf_type_vlen(meta->func_proto); 11933 if (nargs > MAX_BPF_FUNC_ARGS) { 11934 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11935 MAX_BPF_FUNC_ARGS); 11936 return -EINVAL; 11937 } 11938 if (nargs > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) { 11939 verbose(env, "JIT does not support kfunc %s() with %d args\n", 11940 func_name, nargs); 11941 return -ENOTSUPP; 11942 } 11943 11944 ret = check_outgoing_stack_args(env, caller, nargs); 11945 if (ret) 11946 return ret; 11947 11948 /* Check that BTF function arguments match actual types that the 11949 * verifier sees. 11950 */ 11951 for (i = 0; i < nargs; i++) { 11952 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 11953 const struct btf_type *t, *ref_t, *resolve_ret; 11954 enum bpf_arg_type arg_type = ARG_DONTCARE; 11955 argno_t argno = argno_from_arg(i + 1); 11956 int regno = reg_from_argno(argno); 11957 bool btf_id_fixed_off_ok = true; 11958 u32 ref_id, type_size; 11959 bool is_ret_buf_sz = false; 11960 int kf_arg_type; 11961 11962 if (is_kfunc_arg_prog_aux(btf, &args[i])) { 11963 /* Reject repeated use bpf_prog_aux */ 11964 if (meta->arg_prog) { 11965 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc"); 11966 return -EFAULT; 11967 } 11968 if (regno < 0) { 11969 verbose(env, "%s prog->aux cannot be a stack argument\n", 11970 reg_arg_name(env, argno)); 11971 return -EINVAL; 11972 } 11973 meta->arg_prog = true; 11974 cur_aux(env)->arg_prog = regno; 11975 continue; 11976 } 11977 11978 if (is_kfunc_arg_ignore(btf, &args[i]) || is_kfunc_arg_implicit(meta, i)) 11979 continue; 11980 11981 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11982 11983 if (btf_type_is_scalar(t)) { 11984 if (reg->type != SCALAR_VALUE) { 11985 verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno)); 11986 return -EINVAL; 11987 } 11988 11989 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11990 if (meta->arg_constant.found) { 11991 verifier_bug(env, "only one constant argument permitted"); 11992 return -EFAULT; 11993 } 11994 if (!tnum_is_const(reg->var_off)) { 11995 verbose(env, "%s must be a known constant\n", 11996 reg_arg_name(env, argno)); 11997 return -EINVAL; 11998 } 11999 if (regno >= 0) 12000 ret = mark_chain_precision(env, regno); 12001 else 12002 ret = mark_stack_arg_precision(env, i); 12003 if (ret < 0) 12004 return ret; 12005 meta->arg_constant.found = true; 12006 meta->arg_constant.value = reg->var_off.value; 12007 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 12008 meta->r0_rdonly = true; 12009 is_ret_buf_sz = true; 12010 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 12011 is_ret_buf_sz = true; 12012 } 12013 12014 if (is_ret_buf_sz) { 12015 if (meta->r0_size) { 12016 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 12017 return -EINVAL; 12018 } 12019 12020 if (!tnum_is_const(reg->var_off)) { 12021 verbose(env, "%s is not a const\n", 12022 reg_arg_name(env, argno)); 12023 return -EINVAL; 12024 } 12025 12026 meta->r0_size = reg->var_off.value; 12027 if (regno >= 0) 12028 ret = mark_chain_precision(env, regno); 12029 else 12030 ret = mark_stack_arg_precision(env, i); 12031 if (ret) 12032 return ret; 12033 } 12034 continue; 12035 } 12036 12037 if (!btf_type_is_ptr(t)) { 12038 verbose(env, "Unrecognized %s type %s\n", 12039 reg_arg_name(env, argno), btf_type_str(t)); 12040 return -EINVAL; 12041 } 12042 12043 if ((bpf_register_is_null(reg) || type_may_be_null(reg->type)) && 12044 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 12045 verbose(env, "Possibly NULL pointer passed to trusted %s\n", 12046 reg_arg_name(env, argno)); 12047 return -EACCES; 12048 } 12049 12050 if (regno == meta->release_regno && !is_kfunc_arg_dynptr(meta->btf, &args[i]) && 12051 !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) { 12052 verbose(env, "release kfunc %s expects referenced PTR_TO_BTF_ID passed to %s\n", 12053 func_name, reg_arg_name(env, argno)); 12054 return -EINVAL; 12055 } 12056 12057 if (reg_is_referenced(env, reg)) 12058 update_ref_obj(&meta->ref_obj, reg); 12059 12060 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 12061 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12062 12063 kf_arg_type = get_kfunc_ptr_arg_type(env, caller, regs, meta, t, ref_t, ref_tname, 12064 args, i, nargs, argno, reg); 12065 if (kf_arg_type < 0) 12066 return kf_arg_type; 12067 12068 switch (kf_arg_type) { 12069 case KF_ARG_PTR_TO_NULL: 12070 continue; 12071 case KF_ARG_PTR_TO_MAP: 12072 if (!reg->map_ptr) { 12073 verbose(env, "pointer in %s isn't map pointer\n", 12074 reg_arg_name(env, argno)); 12075 return -EINVAL; 12076 } 12077 if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 || 12078 reg->map_ptr->record->task_work_off >= 0)) { 12079 /* Use map_uid (which is unique id of inner map) to reject: 12080 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 12081 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 12082 * if (inner_map1 && inner_map2) { 12083 * wq = bpf_map_lookup_elem(inner_map1); 12084 * if (wq) 12085 * // mismatch would have been allowed 12086 * bpf_wq_init(wq, inner_map2); 12087 * } 12088 * 12089 * Comparing map_ptr is enough to distinguish normal and outer maps. 12090 */ 12091 if (meta->map.ptr != reg->map_ptr || 12092 meta->map.uid != reg->map_uid) { 12093 if (reg->map_ptr->record->task_work_off >= 0) { 12094 verbose(env, 12095 "bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n", 12096 meta->map.uid, reg->map_uid); 12097 return -EINVAL; 12098 } 12099 verbose(env, 12100 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 12101 meta->map.uid, reg->map_uid); 12102 return -EINVAL; 12103 } 12104 } 12105 meta->map.ptr = reg->map_ptr; 12106 meta->map.uid = reg->map_uid; 12107 fallthrough; 12108 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12109 case KF_ARG_PTR_TO_BTF_ID: 12110 if (!is_trusted_reg(env, reg)) { 12111 if (!is_kfunc_rcu(meta)) { 12112 verbose(env, "%s must be referenced or trusted\n", 12113 reg_arg_name(env, argno)); 12114 return -EINVAL; 12115 } 12116 if (!is_rcu_reg(reg)) { 12117 verbose(env, "%s must be a rcu pointer\n", 12118 reg_arg_name(env, argno)); 12119 return -EINVAL; 12120 } 12121 } 12122 fallthrough; 12123 case KF_ARG_PTR_TO_ITER: 12124 case KF_ARG_PTR_TO_LIST_HEAD: 12125 case KF_ARG_PTR_TO_LIST_NODE: 12126 case KF_ARG_PTR_TO_RB_ROOT: 12127 case KF_ARG_PTR_TO_RB_NODE: 12128 case KF_ARG_PTR_TO_MEM: 12129 case KF_ARG_PTR_TO_MEM_SIZE: 12130 case KF_ARG_PTR_TO_CALLBACK: 12131 case KF_ARG_PTR_TO_CONST_STR: 12132 case KF_ARG_PTR_TO_WORKQUEUE: 12133 case KF_ARG_PTR_TO_TIMER: 12134 case KF_ARG_PTR_TO_TASK_WORK: 12135 case KF_ARG_PTR_TO_IRQ_FLAG: 12136 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12137 break; 12138 case KF_ARG_PTR_TO_DYNPTR: 12139 arg_type = ARG_PTR_TO_DYNPTR; 12140 break; 12141 case KF_ARG_PTR_TO_CTX: 12142 arg_type = ARG_PTR_TO_CTX; 12143 break; 12144 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12145 arg_type = ARG_PTR_TO_BTF_ID; 12146 btf_id_fixed_off_ok = false; 12147 break; 12148 default: 12149 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type); 12150 return -EFAULT; 12151 } 12152 12153 if (regno == meta->release_regno) 12154 arg_type |= OBJ_RELEASE; 12155 ret = __check_func_arg_reg_off(env, reg, argno, arg_type, 12156 btf_id_fixed_off_ok); 12157 if (ret < 0) 12158 return ret; 12159 12160 switch (kf_arg_type) { 12161 case KF_ARG_PTR_TO_CTX: 12162 if (reg->type != PTR_TO_CTX) { 12163 verbose(env, "%s expected pointer to ctx, but got %s\n", 12164 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 12165 return -EINVAL; 12166 } 12167 12168 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12169 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 12170 if (ret < 0) 12171 return -EINVAL; 12172 meta->ret_btf_id = ret; 12173 } 12174 break; 12175 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12176 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 12177 if (!is_bpf_obj_drop_kfunc(meta->func_id)) { 12178 verbose(env, "%s expected for bpf_obj_drop()\n", 12179 reg_arg_name(env, argno)); 12180 return -EINVAL; 12181 } 12182 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 12183 if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) { 12184 verbose(env, "%s expected for bpf_percpu_obj_drop()\n", 12185 reg_arg_name(env, argno)); 12186 return -EINVAL; 12187 } 12188 } else { 12189 verbose(env, "%s expected pointer to allocated object\n", 12190 reg_arg_name(env, argno)); 12191 return -EINVAL; 12192 } 12193 if (!reg_is_referenced(env, reg)) { 12194 verbose(env, "allocated object must be referenced\n"); 12195 return -EINVAL; 12196 } 12197 if (meta->btf == btf_vmlinux) { 12198 meta->arg_btf = reg->btf; 12199 meta->arg_btf_id = reg->btf_id; 12200 } 12201 break; 12202 case KF_ARG_PTR_TO_DYNPTR: 12203 { 12204 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 12205 12206 if (is_kfunc_arg_uninit(btf, &args[i])) 12207 dynptr_arg_type |= MEM_UNINIT; 12208 12209 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 12210 dynptr_arg_type |= DYNPTR_TYPE_SKB; 12211 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 12212 dynptr_arg_type |= DYNPTR_TYPE_XDP; 12213 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) { 12214 dynptr_arg_type |= DYNPTR_TYPE_SKB_META; 12215 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 12216 dynptr_arg_type |= DYNPTR_TYPE_FILE; 12217 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) { 12218 dynptr_arg_type |= DYNPTR_TYPE_FILE | OBJ_RELEASE; 12219 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 12220 (dynptr_arg_type & MEM_UNINIT)) { 12221 enum bpf_dynptr_type parent_type = meta->dynptr.type; 12222 12223 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 12224 verifier_bug(env, "no dynptr type for parent of clone"); 12225 return -EFAULT; 12226 } 12227 12228 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12229 } 12230 12231 ret = process_dynptr_func(env, reg, argno, insn_idx, dynptr_arg_type, 12232 &meta->ref_obj, &meta->dynptr); 12233 if (ret < 0) 12234 return ret; 12235 break; 12236 } 12237 case KF_ARG_PTR_TO_ITER: 12238 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12239 if (!check_css_task_iter_allowlist(env)) { 12240 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12241 return -EINVAL; 12242 } 12243 } 12244 ret = process_iter_arg(env, reg, argno, insn_idx, meta); 12245 if (ret < 0) 12246 return ret; 12247 break; 12248 case KF_ARG_PTR_TO_LIST_HEAD: 12249 if (reg->type != PTR_TO_MAP_VALUE && 12250 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12251 verbose(env, "%s expected pointer to map value or allocated object\n", 12252 reg_arg_name(env, argno)); 12253 return -EINVAL; 12254 } 12255 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 12256 !reg_is_referenced(env, reg)) { 12257 verbose(env, "allocated object must be referenced\n"); 12258 return -EINVAL; 12259 } 12260 ret = process_kf_arg_ptr_to_list_head(env, reg, argno, meta); 12261 if (ret < 0) 12262 return ret; 12263 break; 12264 case KF_ARG_PTR_TO_RB_ROOT: 12265 if (reg->type != PTR_TO_MAP_VALUE && 12266 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12267 verbose(env, "%s expected pointer to map value or allocated object\n", 12268 reg_arg_name(env, argno)); 12269 return -EINVAL; 12270 } 12271 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 12272 !reg_is_referenced(env, reg)) { 12273 verbose(env, "allocated object must be referenced\n"); 12274 return -EINVAL; 12275 } 12276 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta); 12277 if (ret < 0) 12278 return ret; 12279 break; 12280 case KF_ARG_PTR_TO_LIST_NODE: 12281 if (is_kfunc_arg_nonown_allowed(btf, &args[i]) && 12282 type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg)) { 12283 /* Allow bpf_list_front/back return value for 12284 * __nonown_allowed list-node arguments. 12285 */ 12286 goto check_ok; 12287 } 12288 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12289 verbose(env, "%s expected pointer to allocated object\n", 12290 reg_arg_name(env, argno)); 12291 return -EINVAL; 12292 } 12293 if (!reg_is_referenced(env, reg)) { 12294 verbose(env, "allocated object must be referenced\n"); 12295 return -EINVAL; 12296 } 12297 check_ok: 12298 ret = process_kf_arg_ptr_to_list_node(env, reg, argno, meta); 12299 if (ret < 0) 12300 return ret; 12301 break; 12302 case KF_ARG_PTR_TO_RB_NODE: 12303 if (is_bpf_rbtree_add_kfunc(meta->func_id)) { 12304 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12305 verbose(env, "%s expected pointer to allocated object\n", 12306 reg_arg_name(env, argno)); 12307 return -EINVAL; 12308 } 12309 if (!reg_is_referenced(env, reg)) { 12310 verbose(env, "allocated object must be referenced\n"); 12311 return -EINVAL; 12312 } 12313 } else { 12314 if (!type_is_non_owning_ref(reg->type) && 12315 !reg_is_referenced(env, reg)) { 12316 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name); 12317 return -EINVAL; 12318 } 12319 if (in_rbtree_lock_required_cb(env)) { 12320 verbose(env, "%s not allowed in rbtree cb\n", func_name); 12321 return -EINVAL; 12322 } 12323 } 12324 12325 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta); 12326 if (ret < 0) 12327 return ret; 12328 break; 12329 case KF_ARG_PTR_TO_MAP: 12330 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12331 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12332 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12333 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12334 fallthrough; 12335 case KF_ARG_PTR_TO_BTF_ID: 12336 /* Only base_type is checked, further checks are done here */ 12337 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12338 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12339 !reg2btf_ids[base_type(reg->type)]) { 12340 verbose(env, "%s is %s ", reg_arg_name(env, argno), 12341 reg_type_str(env, reg->type)); 12342 verbose(env, "expected %s or socket\n", 12343 reg_type_str(env, base_type(reg->type) | 12344 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12345 return -EINVAL; 12346 } 12347 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i, argno); 12348 if (ret < 0) 12349 return ret; 12350 break; 12351 case KF_ARG_PTR_TO_MEM: 12352 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12353 if (IS_ERR(resolve_ret)) { 12354 verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n", 12355 reg_arg_name(env, argno), btf_type_str(ref_t), 12356 ref_tname, PTR_ERR(resolve_ret)); 12357 return -EINVAL; 12358 } 12359 ret = check_mem_reg(env, reg, argno, type_size); 12360 if (ret < 0) 12361 return ret; 12362 break; 12363 case KF_ARG_PTR_TO_MEM_SIZE: 12364 { 12365 struct bpf_reg_state *buff_reg = reg; 12366 const struct btf_param *buff_arg = &args[i]; 12367 struct bpf_reg_state *size_reg = get_func_arg_reg(caller, regs, i + 1); 12368 const struct btf_param *size_arg = &args[i + 1]; 12369 argno_t next_argno = argno_from_arg(i + 2); 12370 12371 if (!bpf_register_is_null(buff_reg) || !is_kfunc_arg_nullable(meta->btf, buff_arg)) { 12372 ret = check_kfunc_mem_size_reg(env, buff_reg, size_reg, 12373 argno, next_argno); 12374 if (ret < 0) { 12375 verbose(env, "%s and ", reg_arg_name(env, argno)); 12376 verbose(env, "%s memory, len pair leads to invalid memory access\n", 12377 reg_arg_name(env, next_argno)); 12378 return ret; 12379 } 12380 } 12381 12382 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12383 if (meta->arg_constant.found) { 12384 verifier_bug(env, "only one constant argument permitted"); 12385 return -EFAULT; 12386 } 12387 if (!tnum_is_const(size_reg->var_off)) { 12388 verbose(env, "%s must be a known constant\n", 12389 reg_arg_name(env, next_argno)); 12390 return -EINVAL; 12391 } 12392 meta->arg_constant.found = true; 12393 meta->arg_constant.value = size_reg->var_off.value; 12394 } 12395 12396 /* Skip next '__sz' or '__szk' argument */ 12397 i++; 12398 break; 12399 } 12400 case KF_ARG_PTR_TO_CALLBACK: 12401 if (reg->type != PTR_TO_FUNC) { 12402 verbose(env, "%s expected pointer to func\n", reg_arg_name(env, argno)); 12403 return -EINVAL; 12404 } 12405 meta->subprogno = reg->subprogno; 12406 break; 12407 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12408 if (!type_is_ptr_alloc_obj(reg->type)) { 12409 verbose(env, "%s is neither owning or non-owning ref\n", 12410 reg_arg_name(env, argno)); 12411 return -EINVAL; 12412 } 12413 if (!type_is_non_owning_ref(reg->type)) 12414 meta->arg_owning_ref = true; 12415 12416 rec = reg_btf_record(reg); 12417 if (!rec) { 12418 verifier_bug(env, "Couldn't find btf_record"); 12419 return -EFAULT; 12420 } 12421 12422 if (rec->refcount_off < 0) { 12423 verbose(env, "%s doesn't point to a type with bpf_refcount field\n", 12424 reg_arg_name(env, argno)); 12425 return -EINVAL; 12426 } 12427 12428 meta->arg_btf = reg->btf; 12429 meta->arg_btf_id = reg->btf_id; 12430 break; 12431 case KF_ARG_PTR_TO_CONST_STR: 12432 if (reg->type != PTR_TO_MAP_VALUE) { 12433 verbose(env, "%s doesn't point to a const string\n", 12434 reg_arg_name(env, argno)); 12435 return -EINVAL; 12436 } 12437 ret = check_arg_const_str(env, reg, argno); 12438 if (ret) 12439 return ret; 12440 break; 12441 case KF_ARG_PTR_TO_WORKQUEUE: 12442 if (reg->type != PTR_TO_MAP_VALUE) { 12443 verbose(env, "%s doesn't point to a map value\n", 12444 reg_arg_name(env, argno)); 12445 return -EINVAL; 12446 } 12447 ret = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map); 12448 if (ret < 0) 12449 return ret; 12450 break; 12451 case KF_ARG_PTR_TO_TIMER: 12452 if (reg->type != PTR_TO_MAP_VALUE) { 12453 verbose(env, "%s doesn't point to a map value\n", 12454 reg_arg_name(env, argno)); 12455 return -EINVAL; 12456 } 12457 ret = process_timer_kfunc(env, reg, argno, meta); 12458 if (ret < 0) 12459 return ret; 12460 break; 12461 case KF_ARG_PTR_TO_TASK_WORK: 12462 if (reg->type != PTR_TO_MAP_VALUE) { 12463 verbose(env, "%s doesn't point to a map value\n", 12464 reg_arg_name(env, argno)); 12465 return -EINVAL; 12466 } 12467 ret = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map); 12468 if (ret < 0) 12469 return ret; 12470 break; 12471 case KF_ARG_PTR_TO_IRQ_FLAG: 12472 if (reg->type != PTR_TO_STACK) { 12473 verbose(env, "%s doesn't point to an irq flag on stack\n", 12474 reg_arg_name(env, argno)); 12475 return -EINVAL; 12476 } 12477 ret = process_irq_flag(env, reg, argno, meta); 12478 if (ret < 0) 12479 return ret; 12480 break; 12481 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12482 { 12483 int flags = PROCESS_RES_LOCK; 12484 12485 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12486 verbose(env, "%s doesn't point to map value or allocated object\n", 12487 reg_arg_name(env, argno)); 12488 return -EINVAL; 12489 } 12490 12491 if (!is_bpf_res_spin_lock_kfunc(meta->func_id)) 12492 return -EFAULT; 12493 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 12494 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 12495 flags |= PROCESS_SPIN_LOCK; 12496 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 12497 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 12498 flags |= PROCESS_LOCK_IRQ; 12499 ret = process_spin_lock(env, reg, argno, flags); 12500 if (ret < 0) 12501 return ret; 12502 break; 12503 } 12504 } 12505 } 12506 12507 return 0; 12508 } 12509 12510 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, 12511 s32 func_id, 12512 s16 offset, 12513 struct bpf_kfunc_call_arg_meta *meta) 12514 { 12515 struct bpf_kfunc_meta kfunc; 12516 int err; 12517 12518 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 12519 if (err) 12520 return err; 12521 12522 memset(meta, 0, sizeof(*meta)); 12523 meta->btf = kfunc.btf; 12524 meta->func_id = kfunc.id; 12525 meta->func_proto = kfunc.proto; 12526 meta->func_name = kfunc.name; 12527 12528 if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog)) 12529 return -EACCES; 12530 12531 meta->kfunc_flags = *kfunc.flags; 12532 12533 /* Only support release referenced argument passed by register */ 12534 if (is_kfunc_release(meta)) 12535 meta->release_regno = BPF_REG_1; 12536 12537 return 0; 12538 } 12539 12540 /* 12541 * Determine how many bytes a helper accesses through a stack pointer at 12542 * argument position @arg (0-based, corresponding to R1-R5). 12543 * 12544 * Returns: 12545 * > 0 known read access size in bytes 12546 * 0 doesn't read anything directly 12547 * S64_MIN unknown 12548 * < 0 known write access of (-return) bytes 12549 */ 12550 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12551 int arg, int insn_idx) 12552 { 12553 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12554 const struct bpf_func_proto *fn; 12555 enum bpf_arg_type at; 12556 s64 size; 12557 12558 if (bpf_get_helper_proto(env, insn->imm, &fn) < 0) 12559 return S64_MIN; 12560 12561 at = fn->arg_type[arg]; 12562 12563 switch (base_type(at)) { 12564 case ARG_PTR_TO_MAP_KEY: 12565 case ARG_PTR_TO_MAP_VALUE: { 12566 bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY; 12567 u64 val; 12568 int i, map_reg; 12569 12570 for (i = 0; i < arg; i++) { 12571 if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR) 12572 break; 12573 } 12574 if (i >= arg) 12575 goto scan_all_maps; 12576 12577 map_reg = BPF_REG_1 + i; 12578 12579 if (!(aux->const_reg_map_mask & BIT(map_reg))) 12580 goto scan_all_maps; 12581 12582 i = aux->const_reg_vals[map_reg]; 12583 if (i < env->used_map_cnt) { 12584 size = is_key ? env->used_maps[i]->key_size 12585 : env->used_maps[i]->value_size; 12586 goto out; 12587 } 12588 scan_all_maps: 12589 /* 12590 * Map pointer is not known at this call site (e.g. different 12591 * maps on merged paths). Conservatively return the largest 12592 * key_size or value_size across all maps used by the program. 12593 */ 12594 val = 0; 12595 for (i = 0; i < env->used_map_cnt; i++) { 12596 struct bpf_map *map = env->used_maps[i]; 12597 u32 sz = is_key ? map->key_size : map->value_size; 12598 12599 if (sz > val) 12600 val = sz; 12601 if (map->inner_map_meta) { 12602 sz = is_key ? map->inner_map_meta->key_size 12603 : map->inner_map_meta->value_size; 12604 if (sz > val) 12605 val = sz; 12606 } 12607 } 12608 if (!val) 12609 return S64_MIN; 12610 size = val; 12611 goto out; 12612 } 12613 case ARG_PTR_TO_MEM: 12614 if (at & MEM_FIXED_SIZE) { 12615 size = fn->arg_size[arg]; 12616 goto out; 12617 } 12618 if (arg + 1 < ARRAY_SIZE(fn->arg_type) && 12619 arg_type_is_mem_size(fn->arg_type[arg + 1])) { 12620 int size_reg = BPF_REG_1 + arg + 1; 12621 12622 if (aux->const_reg_mask & BIT(size_reg)) { 12623 size = (s64)aux->const_reg_vals[size_reg]; 12624 goto out; 12625 } 12626 /* 12627 * Size arg is const on each path but differs across merged 12628 * paths. MAX_BPF_STACK is a safe upper bound for reads. 12629 */ 12630 if (at & MEM_UNINIT) 12631 return 0; 12632 return MAX_BPF_STACK; 12633 } 12634 return S64_MIN; 12635 case ARG_PTR_TO_DYNPTR: 12636 size = BPF_DYNPTR_SIZE; 12637 break; 12638 case ARG_PTR_TO_STACK: 12639 /* 12640 * Only used by bpf_calls_callback() helpers. The helper itself 12641 * doesn't access stack. The callback subprog does and it's 12642 * analyzed separately. 12643 */ 12644 return 0; 12645 default: 12646 return S64_MIN; 12647 } 12648 out: 12649 /* 12650 * MEM_UNINIT args are write-only: the helper initializes the 12651 * buffer without reading it. 12652 */ 12653 if (at & MEM_UNINIT) 12654 return -size; 12655 return size; 12656 } 12657 12658 /* 12659 * Determine how many bytes a kfunc accesses through a stack pointer at 12660 * argument position @arg (0-based, corresponding to R1-R5). 12661 * 12662 * Returns: 12663 * > 0 known read access size in bytes 12664 * 0 doesn't access memory through that argument (ex: not a pointer) 12665 * S64_MIN unknown 12666 * < 0 known write access of (-return) bytes 12667 */ 12668 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12669 int arg, int insn_idx) 12670 { 12671 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12672 struct bpf_kfunc_call_arg_meta meta; 12673 const struct btf_param *args; 12674 const struct btf_type *t, *ref_t; 12675 const struct btf *btf; 12676 u32 nargs, type_size; 12677 s64 size; 12678 12679 if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0) 12680 return S64_MIN; 12681 12682 btf = meta.btf; 12683 args = btf_params(meta.func_proto); 12684 nargs = btf_type_vlen(meta.func_proto); 12685 if (arg >= nargs) 12686 return 0; 12687 12688 t = btf_type_skip_modifiers(btf, args[arg].type, NULL); 12689 if (!btf_type_is_ptr(t)) 12690 return 0; 12691 12692 /* dynptr: fixed 16-byte on-stack representation */ 12693 if (is_kfunc_arg_dynptr(btf, &args[arg])) { 12694 size = BPF_DYNPTR_SIZE; 12695 goto out; 12696 } 12697 12698 /* ptr + __sz/__szk pair: size is in the next register */ 12699 if (arg + 1 < nargs && 12700 (btf_param_match_suffix(btf, &args[arg + 1], "__sz") || 12701 btf_param_match_suffix(btf, &args[arg + 1], "__szk"))) { 12702 int size_reg = BPF_REG_1 + arg + 1; 12703 12704 if (aux->const_reg_mask & BIT(size_reg)) { 12705 size = (s64)aux->const_reg_vals[size_reg]; 12706 goto out; 12707 } 12708 return MAX_BPF_STACK; 12709 } 12710 12711 /* fixed-size pointed-to type: resolve via BTF */ 12712 ref_t = btf_type_skip_modifiers(btf, t->type, NULL); 12713 if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) { 12714 size = type_size; 12715 goto out; 12716 } 12717 12718 return S64_MIN; 12719 out: 12720 /* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */ 12721 if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW) 12722 return -size; 12723 if (is_kfunc_arg_uninit(btf, &args[arg])) 12724 return -size; 12725 return size; 12726 } 12727 12728 /* check special kfuncs and return: 12729 * 1 - not fall-through to 'else' branch, continue verification 12730 * 0 - fall-through to 'else' branch 12731 * < 0 - not fall-through to 'else' branch, return error 12732 */ 12733 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 12734 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 12735 const struct btf_type *ptr_type, struct btf *desc_btf) 12736 { 12737 const struct btf_type *ret_t; 12738 int err = 0; 12739 12740 if (meta->btf != btf_vmlinux) 12741 return 0; 12742 12743 if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12744 struct btf_struct_meta *struct_meta; 12745 struct btf *ret_btf; 12746 u32 ret_btf_id; 12747 12748 if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set) 12749 return -ENOMEM; 12750 12751 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 12752 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12753 return -EINVAL; 12754 } 12755 12756 ret_btf = env->prog->aux->btf; 12757 ret_btf_id = meta->arg_constant.value; 12758 12759 /* This may be NULL due to user not supplying a BTF */ 12760 if (!ret_btf) { 12761 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12762 return -EINVAL; 12763 } 12764 12765 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12766 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12767 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12768 return -EINVAL; 12769 } 12770 12771 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12772 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12773 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12774 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12775 return -EINVAL; 12776 } 12777 12778 if (!bpf_global_percpu_ma_set) { 12779 mutex_lock(&bpf_percpu_ma_lock); 12780 if (!bpf_global_percpu_ma_set) { 12781 /* Charge memory allocated with bpf_global_percpu_ma to 12782 * root memcg. The obj_cgroup for root memcg is NULL. 12783 */ 12784 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12785 if (!err) 12786 bpf_global_percpu_ma_set = true; 12787 } 12788 mutex_unlock(&bpf_percpu_ma_lock); 12789 if (err) 12790 return err; 12791 } 12792 12793 mutex_lock(&bpf_percpu_ma_lock); 12794 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12795 mutex_unlock(&bpf_percpu_ma_lock); 12796 if (err) 12797 return err; 12798 } 12799 12800 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12801 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12802 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12803 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12804 return -EINVAL; 12805 } 12806 12807 if (struct_meta) { 12808 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12809 return -EINVAL; 12810 } 12811 } 12812 12813 mark_reg_known_zero(env, regs, BPF_REG_0); 12814 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12815 regs[BPF_REG_0].btf = ret_btf; 12816 regs[BPF_REG_0].btf_id = ret_btf_id; 12817 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) 12818 regs[BPF_REG_0].type |= MEM_PERCPU; 12819 12820 insn_aux->obj_new_size = ret_t->size; 12821 insn_aux->kptr_struct_meta = struct_meta; 12822 } else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) { 12823 mark_reg_known_zero(env, regs, BPF_REG_0); 12824 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12825 regs[BPF_REG_0].btf = meta->arg_btf; 12826 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 12827 12828 insn_aux->kptr_struct_meta = 12829 btf_find_struct_meta(meta->arg_btf, 12830 meta->arg_btf_id); 12831 } else if (is_list_node_type(ptr_type)) { 12832 struct btf_field *field = meta->arg_list_head.field; 12833 12834 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12835 } else if (is_rbtree_node_type(ptr_type)) { 12836 struct btf_field *field = meta->arg_rbtree_root.field; 12837 12838 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12839 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12840 mark_reg_known_zero(env, regs, BPF_REG_0); 12841 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12842 regs[BPF_REG_0].btf = desc_btf; 12843 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 12844 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12845 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 12846 if (!ret_t) { 12847 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n", 12848 meta->arg_constant.value); 12849 return -EINVAL; 12850 } else if (btf_type_is_struct(ret_t)) { 12851 mark_reg_known_zero(env, regs, BPF_REG_0); 12852 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12853 regs[BPF_REG_0].btf = desc_btf; 12854 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 12855 } else if (btf_type_is_void(ret_t)) { 12856 mark_reg_known_zero(env, regs, BPF_REG_0); 12857 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED; 12858 regs[BPF_REG_0].mem_size = 0; 12859 } else { 12860 verbose(env, 12861 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n"); 12862 return -EINVAL; 12863 } 12864 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12865 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12866 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type); 12867 12868 mark_reg_known_zero(env, regs, BPF_REG_0); 12869 12870 if (!meta->arg_constant.found) { 12871 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size"); 12872 return -EFAULT; 12873 } 12874 12875 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 12876 12877 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12878 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12879 12880 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12881 regs[BPF_REG_0].type |= MEM_RDONLY; 12882 } else { 12883 /* this will set env->seen_direct_write to true */ 12884 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12885 verbose(env, "the prog does not allow writes to packet data\n"); 12886 return -EINVAL; 12887 } 12888 } 12889 12890 if (!meta->dynptr.id) { 12891 verifier_bug(env, "no dynptr id"); 12892 return -EFAULT; 12893 } 12894 regs[BPF_REG_0].parent_id = meta->dynptr.id; 12895 } else { 12896 return 0; 12897 } 12898 12899 return 1; 12900 } 12901 12902 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12903 12904 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12905 int *insn_idx_p) 12906 { 12907 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12908 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12909 struct bpf_reg_state *regs = cur_regs(env); 12910 const char *func_name, *ptr_type_name; 12911 const struct btf_type *t, *ptr_type; 12912 struct bpf_kfunc_call_arg_meta meta; 12913 struct bpf_insn_aux_data *insn_aux; 12914 int err, insn_idx = *insn_idx_p; 12915 const struct btf_param *args; 12916 u32 i, nargs, ptr_type_id; 12917 struct btf *desc_btf; 12918 int id; 12919 12920 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12921 if (!insn->imm) 12922 return 0; 12923 12924 err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta); 12925 if (err == -EACCES && meta.func_name) 12926 verbose(env, "calling kernel function %s is not allowed\n", meta.func_name); 12927 if (err) 12928 return err; 12929 desc_btf = meta.btf; 12930 func_name = meta.func_name; 12931 insn_aux = &env->insn_aux_data[insn_idx]; 12932 12933 insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta); 12934 12935 if (!insn->off && 12936 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 12937 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 12938 struct bpf_verifier_state *branch; 12939 struct bpf_reg_state *regs; 12940 12941 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 12942 if (IS_ERR(branch)) { 12943 verbose(env, "failed to push state for failed lock acquisition\n"); 12944 return PTR_ERR(branch); 12945 } 12946 12947 regs = branch->frame[branch->curframe]->regs; 12948 12949 /* Clear r0-r5 registers in forked state */ 12950 for (i = 0; i < CALLER_SAVED_REGS; i++) 12951 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 12952 12953 mark_reg_unknown(env, regs, BPF_REG_0); 12954 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 12955 if (err) { 12956 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 12957 return err; 12958 } 12959 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32)); 12960 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 12961 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 12962 return -EFAULT; 12963 } 12964 12965 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12966 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12967 return -EACCES; 12968 } 12969 12970 sleepable = bpf_is_kfunc_sleepable(&meta); 12971 if (sleepable && !in_sleepable(env)) { 12972 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12973 return -EACCES; 12974 } 12975 12976 /* Track non-sleepable context for kfuncs, same as for helpers. */ 12977 if (!in_sleepable_context(env)) 12978 insn_aux->non_sleepable = true; 12979 12980 /* Check the arguments */ 12981 err = check_kfunc_args(env, &meta, insn_idx); 12982 if (err < 0) 12983 return err; 12984 12985 if ((is_bpf_obj_drop_kfunc(meta.func_id) || 12986 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (is_tracing_prog_type(prog_type) || 12987 /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */ 12988 (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER 12989 && !env->prog->sleepable))) { 12990 struct btf_struct_meta *struct_meta; 12991 12992 struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12993 if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) { 12994 verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n", 12995 func_name); 12996 return -EINVAL; 12997 } 12998 } 12999 13000 if (is_bpf_rbtree_add_kfunc(meta.func_id)) { 13001 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13002 set_rbtree_add_callback_state); 13003 if (err) { 13004 verbose(env, "kfunc %s#%d failed callback verification\n", 13005 func_name, meta.func_id); 13006 return err; 13007 } 13008 } 13009 13010 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 13011 meta.r0_size = sizeof(u64); 13012 meta.r0_rdonly = false; 13013 } 13014 13015 if (is_bpf_wq_set_callback_kfunc(meta.func_id)) { 13016 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13017 set_timer_callback_state); 13018 if (err) { 13019 verbose(env, "kfunc %s#%d failed callback verification\n", 13020 func_name, meta.func_id); 13021 return err; 13022 } 13023 } 13024 13025 if (is_task_work_add_kfunc(meta.func_id)) { 13026 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13027 set_task_work_schedule_callback_state); 13028 if (err) { 13029 verbose(env, "kfunc %s#%d failed callback verification\n", 13030 func_name, meta.func_id); 13031 return err; 13032 } 13033 } 13034 13035 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 13036 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 13037 13038 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 13039 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 13040 13041 if (rcu_lock) { 13042 env->cur_state->active_rcu_locks++; 13043 } else if (rcu_unlock) { 13044 if (env->cur_state->active_rcu_locks == 0) { 13045 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 13046 return -EINVAL; 13047 } 13048 if (--env->cur_state->active_rcu_locks == 0) 13049 invalidate_rcu_protected_refs(env); 13050 } else if (preempt_disable) { 13051 env->cur_state->active_preempt_locks++; 13052 } else if (preempt_enable) { 13053 if (env->cur_state->active_preempt_locks == 0) { 13054 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 13055 return -EINVAL; 13056 } 13057 env->cur_state->active_preempt_locks--; 13058 } 13059 13060 if (sleepable && !in_sleepable_context(env)) { 13061 verbose(env, "kernel func %s is sleepable within %s\n", 13062 func_name, non_sleepable_context_description(env)); 13063 return -EACCES; 13064 } 13065 13066 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 13067 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 13068 return -EACCES; 13069 } 13070 13071 if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) { 13072 verbose(env, "kernel func %s requires RCU critical section protection\n", func_name); 13073 return -EACCES; 13074 } 13075 13076 /* In case of release function, we get register number of refcounted 13077 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 13078 */ 13079 if (meta.release_regno) { 13080 err = release_reg(env, ®s[meta.release_regno], false, !!meta.dynptr.id); 13081 if (err) 13082 return err; 13083 } 13084 13085 if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) { 13086 id = regs[BPF_REG_2].id; 13087 insn_aux->insert_off = regs[BPF_REG_2].var_off.value; 13088 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13089 ref_convert_owning_non_owning(env, id); 13090 } 13091 13092 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 13093 if (!bpf_jit_supports_exceptions()) { 13094 verbose(env, "JIT does not support calling kfunc %s#%d\n", 13095 func_name, meta.func_id); 13096 return -ENOTSUPP; 13097 } 13098 env->seen_exception = true; 13099 13100 /* In the case of the default callback, the cookie value passed 13101 * to bpf_throw becomes the return value of the program. 13102 */ 13103 if (!env->exception_callback_subprog) { 13104 err = check_return_code(env, BPF_REG_1, "R1"); 13105 if (err < 0) 13106 return err; 13107 } 13108 } 13109 13110 for (i = 0; i < CALLER_SAVED_REGS; i++) { 13111 u32 regno = caller_saved[i]; 13112 13113 bpf_mark_reg_not_init(env, ®s[regno]); 13114 regs[regno].subreg_def = DEF_NOT_SUBREG; 13115 } 13116 invalidate_outgoing_stack_args(env, cur_func(env)); 13117 13118 /* Check return type */ 13119 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13120 13121 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13122 if (meta.btf != btf_vmlinux || 13123 (!is_bpf_obj_new_kfunc(meta.func_id) && 13124 !is_bpf_percpu_obj_new_kfunc(meta.func_id) && 13125 !is_bpf_refcount_acquire_kfunc(meta.func_id))) { 13126 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13127 return -EINVAL; 13128 } 13129 } 13130 13131 if (btf_type_is_scalar(t)) { 13132 mark_reg_unknown(env, regs, BPF_REG_0); 13133 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13134 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13135 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 13136 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 13137 } else if (btf_type_is_ptr(t)) { 13138 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 13139 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 13140 if (err) { 13141 if (err < 0) 13142 return err; 13143 } else if (btf_type_is_void(ptr_type)) { 13144 /* kfunc returning 'void *' is equivalent to returning scalar */ 13145 mark_reg_unknown(env, regs, BPF_REG_0); 13146 } else if (!__btf_type_is_struct(ptr_type)) { 13147 if (!meta.r0_size) { 13148 __u32 sz; 13149 13150 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 13151 meta.r0_size = sz; 13152 meta.r0_rdonly = true; 13153 } 13154 } 13155 if (!meta.r0_size) { 13156 ptr_type_name = btf_name_by_offset(desc_btf, 13157 ptr_type->name_off); 13158 verbose(env, 13159 "kernel function %s returns pointer type %s %s is not supported\n", 13160 func_name, 13161 btf_type_str(ptr_type), 13162 ptr_type_name); 13163 return -EINVAL; 13164 } 13165 13166 mark_reg_known_zero(env, regs, BPF_REG_0); 13167 regs[BPF_REG_0].type = PTR_TO_MEM; 13168 regs[BPF_REG_0].mem_size = meta.r0_size; 13169 13170 if (meta.r0_rdonly) 13171 regs[BPF_REG_0].type |= MEM_RDONLY; 13172 13173 /* Ensures we don't access the memory after a release_reference() */ 13174 if (meta.ref_obj.id) { 13175 err = validate_ref_obj(env, &meta.ref_obj); 13176 if (err) 13177 return err; 13178 regs[BPF_REG_0].parent_id = meta.ref_obj.id; 13179 } 13180 13181 if (is_kfunc_rcu_protected(&meta)) 13182 regs[BPF_REG_0].type |= MEM_RCU; 13183 } else { 13184 enum bpf_reg_type type = PTR_TO_BTF_ID; 13185 13186 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 13187 type |= PTR_UNTRUSTED; 13188 else if (is_kfunc_rcu_protected(&meta) || 13189 (bpf_is_iter_next_kfunc(&meta) && 13190 (get_iter_from_state(env->cur_state, &meta) 13191 ->type & MEM_RCU))) { 13192 /* 13193 * If the iterator's constructor (the _new 13194 * function e.g., bpf_iter_task_new) has been 13195 * annotated with BPF kfunc flag 13196 * KF_RCU_PROTECTED and was called within a RCU 13197 * read-side critical section, also propagate 13198 * the MEM_RCU flag to the pointer returned from 13199 * the iterator's next function (e.g., 13200 * bpf_iter_task_next). 13201 */ 13202 type |= MEM_RCU; 13203 } else { 13204 /* 13205 * Any PTR_TO_BTF_ID that is returned from a BPF 13206 * kfunc should by default be treated as 13207 * implicitly trusted. 13208 */ 13209 type |= PTR_TRUSTED; 13210 } 13211 13212 mark_reg_known_zero(env, regs, BPF_REG_0); 13213 regs[BPF_REG_0].btf = desc_btf; 13214 regs[BPF_REG_0].type = type; 13215 regs[BPF_REG_0].btf_id = ptr_type_id; 13216 } 13217 13218 if (is_kfunc_ret_null(&meta)) { 13219 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 13220 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 13221 regs[BPF_REG_0].id = ++env->id_gen; 13222 } 13223 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 13224 if (is_kfunc_acquire(&meta)) { 13225 id = acquire_reference(env, insn_idx, 0); 13226 if (id < 0) 13227 return id; 13228 regs[BPF_REG_0].id = id; 13229 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 13230 ref_set_non_owning(env, ®s[BPF_REG_0]); 13231 } 13232 13233 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 13234 regs[BPF_REG_0].id = ++env->id_gen; 13235 } else if (btf_type_is_void(t)) { 13236 if (meta.btf == btf_vmlinux) { 13237 if (is_bpf_obj_drop_kfunc(meta.func_id) || 13238 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) { 13239 insn_aux->kptr_struct_meta = 13240 btf_find_struct_meta(meta.arg_btf, 13241 meta.arg_btf_id); 13242 } 13243 } 13244 } 13245 13246 if (bpf_is_kfunc_pkt_changing(&meta)) 13247 clear_all_pkt_pointers(env); 13248 13249 nargs = btf_type_vlen(meta.func_proto); 13250 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 13251 struct bpf_func_state *caller = cur_func(env); 13252 struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno]; 13253 u16 out_stack_arg_cnt = nargs - MAX_BPF_FUNC_REG_ARGS; 13254 u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt; 13255 13256 if (stack_arg_cnt > caller_info->stack_arg_cnt) 13257 caller_info->stack_arg_cnt = stack_arg_cnt; 13258 } 13259 13260 args = (const struct btf_param *)(meta.func_proto + 1); 13261 for (i = 0; i < min_t(int, nargs, MAX_BPF_FUNC_REG_ARGS); i++) { 13262 u32 regno = i + 1; 13263 13264 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 13265 if (btf_type_is_ptr(t)) 13266 mark_btf_func_reg_size(env, regno, sizeof(void *)); 13267 else 13268 /* scalar. ensured by check_kfunc_args() */ 13269 mark_btf_func_reg_size(env, regno, t->size); 13270 } 13271 13272 if (bpf_is_iter_next_kfunc(&meta)) { 13273 err = process_iter_next_call(env, insn_idx, &meta); 13274 if (err) 13275 return err; 13276 } 13277 13278 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 13279 env->prog->call_session_cookie = true; 13280 13281 if (bpf_is_throw_kfunc(insn)) 13282 return process_bpf_exit_full(env, NULL, true); 13283 13284 return 0; 13285 } 13286 13287 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env, 13288 const struct bpf_reg_state *reg, 13289 enum bpf_reg_type type) 13290 { 13291 bool known = tnum_is_const(reg->var_off); 13292 s64 val = reg->var_off.value; 13293 s64 smin = reg_smin(reg); 13294 13295 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13296 verbose(env, "math between %s pointer and %lld is not allowed\n", 13297 reg_type_str(env, type), val); 13298 return false; 13299 } 13300 13301 if (smin == S64_MIN) { 13302 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 13303 reg_type_str(env, type)); 13304 return false; 13305 } 13306 13307 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13308 verbose(env, "value %lld makes %s pointer be out of bounds\n", 13309 smin, reg_type_str(env, type)); 13310 return false; 13311 } 13312 13313 return true; 13314 } 13315 13316 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env, 13317 const struct bpf_reg_state *reg, 13318 enum bpf_reg_type type) 13319 { 13320 bool known = tnum_is_const(reg->var_off); 13321 s64 val = reg->var_off.value; 13322 s64 smin = reg_smin(reg); 13323 13324 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13325 verbose(env, "%s pointer offset %lld is not allowed\n", 13326 reg_type_str(env, type), val); 13327 return false; 13328 } 13329 13330 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13331 verbose(env, "%s pointer offset %lld is not allowed\n", 13332 reg_type_str(env, type), smin); 13333 return false; 13334 } 13335 13336 return true; 13337 } 13338 13339 enum { 13340 REASON_BOUNDS = -1, 13341 REASON_TYPE = -2, 13342 REASON_PATHS = -3, 13343 REASON_LIMIT = -4, 13344 REASON_STACK = -5, 13345 }; 13346 13347 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 13348 u32 *alu_limit, bool mask_to_left) 13349 { 13350 u32 max = 0, ptr_limit = 0; 13351 13352 switch (ptr_reg->type) { 13353 case PTR_TO_STACK: 13354 /* Offset 0 is out-of-bounds, but acceptable start for the 13355 * left direction, see BPF_REG_FP. Also, unknown scalar 13356 * offset where we would need to deal with min/max bounds is 13357 * currently prohibited for unprivileged. 13358 */ 13359 max = MAX_BPF_STACK + mask_to_left; 13360 ptr_limit = -ptr_reg->var_off.value; 13361 break; 13362 case PTR_TO_MAP_VALUE: 13363 max = ptr_reg->map_ptr->value_size; 13364 ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg); 13365 break; 13366 default: 13367 return REASON_TYPE; 13368 } 13369 13370 if (ptr_limit >= max) 13371 return REASON_LIMIT; 13372 *alu_limit = ptr_limit; 13373 return 0; 13374 } 13375 13376 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 13377 const struct bpf_insn *insn) 13378 { 13379 return env->bypass_spec_v1 || 13380 BPF_SRC(insn->code) == BPF_K || 13381 cur_aux(env)->nospec; 13382 } 13383 13384 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 13385 u32 alu_state, u32 alu_limit) 13386 { 13387 /* If we arrived here from different branches with different 13388 * state or limits to sanitize, then this won't work. 13389 */ 13390 if (aux->alu_state && 13391 (aux->alu_state != alu_state || 13392 aux->alu_limit != alu_limit)) 13393 return REASON_PATHS; 13394 13395 /* Corresponding fixup done in do_misc_fixups(). */ 13396 aux->alu_state = alu_state; 13397 aux->alu_limit = alu_limit; 13398 return 0; 13399 } 13400 13401 static int sanitize_val_alu(struct bpf_verifier_env *env, 13402 struct bpf_insn *insn) 13403 { 13404 struct bpf_insn_aux_data *aux = cur_aux(env); 13405 13406 if (can_skip_alu_sanitation(env, insn)) 13407 return 0; 13408 13409 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13410 } 13411 13412 static bool sanitize_needed(u8 opcode) 13413 { 13414 return opcode == BPF_ADD || opcode == BPF_SUB; 13415 } 13416 13417 struct bpf_sanitize_info { 13418 struct bpf_insn_aux_data aux; 13419 bool mask_to_left; 13420 }; 13421 13422 static int sanitize_speculative_path(struct bpf_verifier_env *env, 13423 const struct bpf_insn *insn, 13424 u32 next_idx, u32 curr_idx) 13425 { 13426 struct bpf_verifier_state *branch; 13427 struct bpf_reg_state *regs; 13428 13429 branch = push_stack(env, next_idx, curr_idx, true); 13430 if (!IS_ERR(branch) && insn) { 13431 regs = branch->frame[branch->curframe]->regs; 13432 if (BPF_SRC(insn->code) == BPF_K) { 13433 mark_reg_unknown(env, regs, insn->dst_reg); 13434 } else if (BPF_SRC(insn->code) == BPF_X) { 13435 mark_reg_unknown(env, regs, insn->dst_reg); 13436 mark_reg_unknown(env, regs, insn->src_reg); 13437 } 13438 } 13439 return PTR_ERR_OR_ZERO(branch); 13440 } 13441 13442 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13443 struct bpf_insn *insn, 13444 const struct bpf_reg_state *ptr_reg, 13445 const struct bpf_reg_state *off_reg, 13446 struct bpf_reg_state *dst_reg, 13447 struct bpf_sanitize_info *info, 13448 const bool commit_window) 13449 { 13450 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13451 struct bpf_verifier_state *vstate = env->cur_state; 13452 bool off_is_imm = tnum_is_const(off_reg->var_off); 13453 bool off_is_neg = reg_smin(off_reg) < 0; 13454 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13455 u8 opcode = BPF_OP(insn->code); 13456 u32 alu_state, alu_limit; 13457 struct bpf_reg_state tmp; 13458 int err; 13459 13460 if (can_skip_alu_sanitation(env, insn)) 13461 return 0; 13462 13463 /* We already marked aux for masking from non-speculative 13464 * paths, thus we got here in the first place. We only care 13465 * to explore bad access from here. 13466 */ 13467 if (vstate->speculative) 13468 goto do_sim; 13469 13470 if (!commit_window) { 13471 if (!tnum_is_const(off_reg->var_off) && 13472 (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0)) 13473 return REASON_BOUNDS; 13474 13475 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13476 (opcode == BPF_SUB && !off_is_neg); 13477 } 13478 13479 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13480 if (err < 0) 13481 return err; 13482 13483 if (commit_window) { 13484 /* In commit phase we narrow the masking window based on 13485 * the observed pointer move after the simulated operation. 13486 */ 13487 alu_state = info->aux.alu_state; 13488 alu_limit = abs(info->aux.alu_limit - alu_limit); 13489 } else { 13490 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13491 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13492 alu_state |= ptr_is_dst_reg ? 13493 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13494 13495 /* Limit pruning on unknown scalars to enable deep search for 13496 * potential masking differences from other program paths. 13497 */ 13498 if (!off_is_imm) 13499 env->explore_alu_limits = true; 13500 } 13501 13502 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13503 if (err < 0) 13504 return err; 13505 do_sim: 13506 /* If we're in commit phase, we're done here given we already 13507 * pushed the truncated dst_reg into the speculative verification 13508 * stack. 13509 * 13510 * Also, when register is a known constant, we rewrite register-based 13511 * operation to immediate-based, and thus do not need masking (and as 13512 * a consequence, do not need to simulate the zero-truncation either). 13513 */ 13514 if (commit_window || off_is_imm) 13515 return 0; 13516 13517 /* Simulate and find potential out-of-bounds access under 13518 * speculative execution from truncation as a result of 13519 * masking when off was not within expected range. If off 13520 * sits in dst, then we temporarily need to move ptr there 13521 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13522 * for cases where we use K-based arithmetic in one direction 13523 * and truncated reg-based in the other in order to explore 13524 * bad access. 13525 */ 13526 if (!ptr_is_dst_reg) { 13527 tmp = *dst_reg; 13528 *dst_reg = *ptr_reg; 13529 } 13530 err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx); 13531 if (err < 0) 13532 return REASON_STACK; 13533 if (!ptr_is_dst_reg) 13534 *dst_reg = tmp; 13535 return 0; 13536 } 13537 13538 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13539 { 13540 struct bpf_verifier_state *vstate = env->cur_state; 13541 13542 /* If we simulate paths under speculation, we don't update the 13543 * insn as 'seen' such that when we verify unreachable paths in 13544 * the non-speculative domain, sanitize_dead_code() can still 13545 * rewrite/sanitize them. 13546 */ 13547 if (!vstate->speculative) 13548 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13549 } 13550 13551 static int sanitize_err(struct bpf_verifier_env *env, 13552 const struct bpf_insn *insn, int reason, 13553 const struct bpf_reg_state *off_reg, 13554 const struct bpf_reg_state *dst_reg) 13555 { 13556 static const char *err = "pointer arithmetic with it prohibited for !root"; 13557 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13558 u32 dst = insn->dst_reg, src = insn->src_reg; 13559 13560 switch (reason) { 13561 case REASON_BOUNDS: 13562 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13563 off_reg == dst_reg ? dst : src, err); 13564 break; 13565 case REASON_TYPE: 13566 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13567 off_reg == dst_reg ? src : dst, err); 13568 break; 13569 case REASON_PATHS: 13570 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13571 dst, op, err); 13572 break; 13573 case REASON_LIMIT: 13574 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13575 dst, op, err); 13576 break; 13577 case REASON_STACK: 13578 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13579 dst, err); 13580 return -ENOMEM; 13581 default: 13582 verifier_bug(env, "unknown reason (%d)", reason); 13583 break; 13584 } 13585 13586 return -EACCES; 13587 } 13588 13589 /* check that stack access falls within stack limits and that 'reg' doesn't 13590 * have a variable offset. 13591 * 13592 * Variable offset is prohibited for unprivileged mode for simplicity since it 13593 * requires corresponding support in Spectre masking for stack ALU. See also 13594 * retrieve_ptr_limit(). 13595 */ 13596 static int check_stack_access_for_ptr_arithmetic( 13597 struct bpf_verifier_env *env, 13598 int regno, 13599 const struct bpf_reg_state *reg, 13600 int off) 13601 { 13602 if (!tnum_is_const(reg->var_off)) { 13603 char tn_buf[48]; 13604 13605 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13606 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13607 regno, tn_buf, off); 13608 return -EACCES; 13609 } 13610 13611 if (off >= 0 || off < -MAX_BPF_STACK) { 13612 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13613 "prohibited for !root; off=%d\n", regno, off); 13614 return -EACCES; 13615 } 13616 13617 return 0; 13618 } 13619 13620 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13621 const struct bpf_insn *insn, 13622 struct bpf_reg_state *dst_reg) 13623 { 13624 u32 dst = insn->dst_reg; 13625 13626 /* For unprivileged we require that resulting offset must be in bounds 13627 * in order to be able to sanitize access later on. 13628 */ 13629 if (env->bypass_spec_v1) 13630 return 0; 13631 13632 switch (dst_reg->type) { 13633 case PTR_TO_STACK: 13634 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13635 dst_reg->var_off.value)) 13636 return -EACCES; 13637 break; 13638 case PTR_TO_MAP_VALUE: 13639 if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) { 13640 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13641 "prohibited for !root\n", dst); 13642 return -EACCES; 13643 } 13644 break; 13645 default: 13646 return -EOPNOTSUPP; 13647 } 13648 13649 return 0; 13650 } 13651 13652 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13653 * Caller should also handle BPF_MOV case separately. 13654 * If we return -EACCES, caller may want to try again treating pointer as a 13655 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13656 */ 13657 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13658 struct bpf_insn *insn, 13659 const struct bpf_reg_state *ptr_reg, 13660 const struct bpf_reg_state *off_reg) 13661 { 13662 struct bpf_verifier_state *vstate = env->cur_state; 13663 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13664 struct bpf_reg_state *regs = state->regs, *dst_reg; 13665 bool known = tnum_is_const(off_reg->var_off); 13666 s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg); 13667 u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg); 13668 struct bpf_sanitize_info info = {}; 13669 u8 opcode = BPF_OP(insn->code); 13670 u32 dst = insn->dst_reg; 13671 int ret, bounds_ret; 13672 13673 dst_reg = ®s[dst]; 13674 13675 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13676 smin_val > smax_val || umin_val > umax_val) { 13677 /* Taint dst register if offset had invalid bounds derived from 13678 * e.g. dead branches. 13679 */ 13680 __mark_reg_unknown(env, dst_reg); 13681 return 0; 13682 } 13683 13684 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13685 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13686 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13687 __mark_reg_unknown(env, dst_reg); 13688 return 0; 13689 } 13690 13691 verbose(env, 13692 "R%d 32-bit pointer arithmetic prohibited\n", 13693 dst); 13694 return -EACCES; 13695 } 13696 13697 if (ptr_reg->type & PTR_MAYBE_NULL) { 13698 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13699 dst, reg_type_str(env, ptr_reg->type)); 13700 return -EACCES; 13701 } 13702 13703 /* 13704 * Accesses to untrusted PTR_TO_MEM are done through probe 13705 * instructions, hence no need to track offsets. 13706 */ 13707 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 13708 return 0; 13709 13710 switch (base_type(ptr_reg->type)) { 13711 case PTR_TO_CTX: 13712 case PTR_TO_MAP_VALUE: 13713 case PTR_TO_MAP_KEY: 13714 case PTR_TO_STACK: 13715 case PTR_TO_PACKET_META: 13716 case PTR_TO_PACKET: 13717 case PTR_TO_TP_BUFFER: 13718 case PTR_TO_BTF_ID: 13719 case PTR_TO_MEM: 13720 case PTR_TO_BUF: 13721 case PTR_TO_FUNC: 13722 case CONST_PTR_TO_DYNPTR: 13723 break; 13724 case PTR_TO_FLOW_KEYS: 13725 if (known) 13726 break; 13727 fallthrough; 13728 case CONST_PTR_TO_MAP: 13729 /* smin_val represents the known value */ 13730 if (known && smin_val == 0 && opcode == BPF_ADD) 13731 break; 13732 fallthrough; 13733 default: 13734 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13735 dst, reg_type_str(env, ptr_reg->type)); 13736 return -EACCES; 13737 } 13738 13739 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13740 * The id may be overwritten later if we create a new variable offset. 13741 */ 13742 dst_reg->type = ptr_reg->type; 13743 dst_reg->id = ptr_reg->id; 13744 13745 if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type) || 13746 !check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) 13747 return -EINVAL; 13748 13749 /* pointer types do not carry 32-bit bounds at the moment. */ 13750 __mark_reg32_unbounded(dst_reg); 13751 13752 if (sanitize_needed(opcode)) { 13753 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13754 &info, false); 13755 if (ret < 0) 13756 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13757 } 13758 13759 switch (opcode) { 13760 case BPF_ADD: 13761 /* 13762 * dst_reg gets the pointer type and since some positive 13763 * integer value was added to the pointer, give it a new 'id' 13764 * if it's a PTR_TO_PACKET. 13765 * this creates a new 'base' pointer, off_reg (variable) gets 13766 * added into the variable offset, and we copy the fixed offset 13767 * from ptr_reg. 13768 */ 13769 dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64); 13770 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13771 dst_reg->raw = ptr_reg->raw; 13772 if (reg_is_pkt_pointer(ptr_reg)) { 13773 if (!known) 13774 dst_reg->id = ++env->id_gen; 13775 /* 13776 * Clear range for unknown addends since we can't know 13777 * where the pkt pointer ended up. Also clear AT_PKT_END / 13778 * BEYOND_PKT_END from prior comparison as any pointer 13779 * arithmetic invalidates them. 13780 */ 13781 if (!known || dst_reg->range < 0) 13782 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13783 } 13784 break; 13785 case BPF_SUB: 13786 if (dst_reg == off_reg) { 13787 /* scalar -= pointer. Creates an unknown scalar */ 13788 verbose(env, "R%d tried to subtract pointer from scalar\n", 13789 dst); 13790 return -EACCES; 13791 } 13792 /* We don't allow subtraction from FP, because (according to 13793 * test_verifier.c test "invalid fp arithmetic", JITs might not 13794 * be able to deal with it. 13795 */ 13796 if (ptr_reg->type == PTR_TO_STACK) { 13797 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13798 dst); 13799 return -EACCES; 13800 } 13801 dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64)); 13802 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13803 dst_reg->raw = ptr_reg->raw; 13804 if (reg_is_pkt_pointer(ptr_reg)) { 13805 if (!known) 13806 dst_reg->id = ++env->id_gen; 13807 /* 13808 * Clear range if the subtrahend may be negative since 13809 * pkt pointer could move past its bounds. A positive 13810 * subtrahend moves it backwards keeping positive range 13811 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from 13812 * prior comparison as arithmetic invalidates them. 13813 */ 13814 if ((!known && smin_val < 0) || dst_reg->range < 0) 13815 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13816 } 13817 break; 13818 case BPF_AND: 13819 case BPF_OR: 13820 case BPF_XOR: 13821 /* bitwise ops on pointers are troublesome, prohibit. */ 13822 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13823 dst, bpf_alu_string[opcode >> 4]); 13824 return -EACCES; 13825 default: 13826 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13827 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13828 dst, bpf_alu_string[opcode >> 4]); 13829 return -EACCES; 13830 } 13831 13832 if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) 13833 return -EINVAL; 13834 reg_bounds_sync(dst_reg); 13835 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 13836 if (bounds_ret == -EACCES) 13837 return bounds_ret; 13838 if (sanitize_needed(opcode)) { 13839 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13840 &info, true); 13841 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 13842 && !env->cur_state->speculative 13843 && bounds_ret 13844 && !ret, 13845 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 13846 return -EFAULT; 13847 } 13848 if (ret < 0) 13849 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13850 } 13851 13852 return 0; 13853 } 13854 13855 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13856 struct bpf_reg_state *src_reg) 13857 { 13858 dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32); 13859 } 13860 13861 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13862 struct bpf_reg_state *src_reg) 13863 { 13864 dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64); 13865 } 13866 13867 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13868 struct bpf_reg_state *src_reg) 13869 { 13870 dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32)); 13871 } 13872 13873 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13874 struct bpf_reg_state *src_reg) 13875 { 13876 dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64)); 13877 } 13878 13879 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13880 struct bpf_reg_state *src_reg) 13881 { 13882 s32 smin = reg_s32_min(dst_reg); 13883 s32 smax = reg_s32_max(dst_reg); 13884 u32 umin = reg_u32_min(dst_reg); 13885 u32 umax = reg_u32_max(dst_reg); 13886 s32 tmp_prod[4]; 13887 13888 if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) || 13889 check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) { 13890 /* Overflow possible, we know nothing */ 13891 umin = 0; 13892 umax = U32_MAX; 13893 } 13894 if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) || 13895 check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) || 13896 check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) || 13897 check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) { 13898 /* Overflow possible, we know nothing */ 13899 smin = S32_MIN; 13900 smax = S32_MAX; 13901 } else { 13902 smin = min_array(tmp_prod, 4); 13903 smax = max_array(tmp_prod, 4); 13904 } 13905 13906 dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax), 13907 cnum32_from_srange(smin, smax)); 13908 } 13909 13910 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13911 struct bpf_reg_state *src_reg) 13912 { 13913 s64 smin = reg_smin(dst_reg); 13914 s64 smax = reg_smax(dst_reg); 13915 u64 umin = reg_umin(dst_reg); 13916 u64 umax = reg_umax(dst_reg); 13917 s64 tmp_prod[4]; 13918 13919 if (check_mul_overflow(umax, reg_umax(src_reg), &umax) || 13920 check_mul_overflow(umin, reg_umin(src_reg), &umin)) { 13921 /* Overflow possible, we know nothing */ 13922 umin = 0; 13923 umax = U64_MAX; 13924 } 13925 if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) || 13926 check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) || 13927 check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) || 13928 check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) { 13929 /* Overflow possible, we know nothing */ 13930 smin = S64_MIN; 13931 smax = S64_MAX; 13932 } else { 13933 smin = min_array(tmp_prod, 4); 13934 smax = max_array(tmp_prod, 4); 13935 } 13936 13937 dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax), 13938 cnum64_from_srange(smin, smax)); 13939 } 13940 13941 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg, 13942 struct bpf_reg_state *src_reg) 13943 { 13944 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 13945 13946 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val, 13947 reg_u32_max(dst_reg) / src_val); 13948 13949 /* Reset other ranges/tnum to unbounded/unknown. */ 13950 reset_reg64_and_tnum(dst_reg); 13951 } 13952 13953 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg, 13954 struct bpf_reg_state *src_reg) 13955 { 13956 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 13957 13958 reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val), 13959 div64_u64(reg_umax(dst_reg), src_val)); 13960 13961 /* Reset other ranges/tnum to unbounded/unknown. */ 13962 reset_reg32_and_tnum(dst_reg); 13963 } 13964 13965 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg, 13966 struct bpf_reg_state *src_reg) 13967 { 13968 s32 smin = reg_s32_min(dst_reg); 13969 s32 smax = reg_s32_max(dst_reg); 13970 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 13971 s32 res1, res2; 13972 13973 /* BPF div specification: S32_MIN / -1 = S32_MIN */ 13974 if (smin == S32_MIN && src_val == -1) { 13975 /* 13976 * If the dividend range contains more than just S32_MIN, 13977 * we cannot precisely track the result, so it becomes unbounded. 13978 * e.g., [S32_MIN, S32_MIN+10]/(-1), 13979 * = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)] 13980 * = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX] 13981 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN. 13982 */ 13983 if (smax != S32_MIN) { 13984 smin = S32_MIN; 13985 smax = S32_MAX; 13986 } 13987 goto reset; 13988 } 13989 13990 res1 = smin / src_val; 13991 res2 = smax / src_val; 13992 smin = min(res1, res2); 13993 smax = max(res1, res2); 13994 13995 reset: 13996 reg_set_srange32(dst_reg, smin, smax); 13997 /* Reset other ranges/tnum to unbounded/unknown. */ 13998 reset_reg64_and_tnum(dst_reg); 13999 } 14000 14001 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg, 14002 struct bpf_reg_state *src_reg) 14003 { 14004 s64 smin = reg_smin(dst_reg); 14005 s64 smax = reg_smax(dst_reg); 14006 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14007 s64 res1, res2; 14008 14009 /* BPF div specification: S64_MIN / -1 = S64_MIN */ 14010 if (smin == S64_MIN && src_val == -1) { 14011 /* 14012 * If the dividend range contains more than just S64_MIN, 14013 * we cannot precisely track the result, so it becomes unbounded. 14014 * e.g., [S64_MIN, S64_MIN+10]/(-1), 14015 * = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)] 14016 * = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX] 14017 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN. 14018 */ 14019 if (smax != S64_MIN) { 14020 smin = S64_MIN; 14021 smax = S64_MAX; 14022 } 14023 goto reset; 14024 } 14025 14026 res1 = div64_s64(smin, src_val); 14027 res2 = div64_s64(smax, src_val); 14028 smin = min(res1, res2); 14029 smax = max(res1, res2); 14030 14031 reset: 14032 reg_set_srange64(dst_reg, smin, smax); 14033 /* Reset other ranges/tnum to unbounded/unknown. */ 14034 reset_reg32_and_tnum(dst_reg); 14035 } 14036 14037 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg, 14038 struct bpf_reg_state *src_reg) 14039 { 14040 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 14041 u32 res_max = src_val - 1; 14042 14043 /* 14044 * If dst_umax <= res_max, the result remains unchanged. 14045 * e.g., [2, 5] % 10 = [2, 5]. 14046 */ 14047 if (reg_u32_max(dst_reg) <= res_max) 14048 return; 14049 14050 reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max)); 14051 14052 /* Reset other ranges/tnum to unbounded/unknown. */ 14053 reset_reg64_and_tnum(dst_reg); 14054 } 14055 14056 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg, 14057 struct bpf_reg_state *src_reg) 14058 { 14059 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 14060 u64 res_max = src_val - 1; 14061 14062 /* 14063 * If dst_umax <= res_max, the result remains unchanged. 14064 * e.g., [2, 5] % 10 = [2, 5]. 14065 */ 14066 if (reg_umax(dst_reg) <= res_max) 14067 return; 14068 14069 reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max)); 14070 14071 /* Reset other ranges/tnum to unbounded/unknown. */ 14072 reset_reg32_and_tnum(dst_reg); 14073 } 14074 14075 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg, 14076 struct bpf_reg_state *src_reg) 14077 { 14078 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 14079 14080 /* 14081 * Safe absolute value calculation: 14082 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648. 14083 * Here use unsigned integer to avoid overflow. 14084 */ 14085 u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val; 14086 14087 /* 14088 * Calculate the maximum possible absolute value of the result. 14089 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives 14090 * 2147483647 (S32_MAX), which fits perfectly in s32. 14091 */ 14092 s32 res_max_abs = src_abs - 1; 14093 14094 /* 14095 * If the dividend is already within the result range, 14096 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14097 */ 14098 if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs) 14099 return; 14100 14101 /* General case: result has the same sign as the dividend. */ 14102 if (reg_s32_min(dst_reg) >= 0) { 14103 reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs)); 14104 } else if (reg_s32_max(dst_reg) <= 0) { 14105 reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0); 14106 } else { 14107 reg_set_srange32(dst_reg, -res_max_abs, res_max_abs); 14108 } 14109 14110 /* Reset other ranges/tnum to unbounded/unknown. */ 14111 reset_reg64_and_tnum(dst_reg); 14112 } 14113 14114 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg, 14115 struct bpf_reg_state *src_reg) 14116 { 14117 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14118 14119 /* 14120 * Safe absolute value calculation: 14121 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63. 14122 * Here use unsigned integer to avoid overflow. 14123 */ 14124 u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val; 14125 14126 /* 14127 * Calculate the maximum possible absolute value of the result. 14128 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives 14129 * 2^63 - 1 (S64_MAX), which fits perfectly in s64. 14130 */ 14131 s64 res_max_abs = src_abs - 1; 14132 14133 /* 14134 * If the dividend is already within the result range, 14135 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14136 */ 14137 if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs) 14138 return; 14139 14140 /* General case: result has the same sign as the dividend. */ 14141 if (reg_smin(dst_reg) >= 0) { 14142 reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs)); 14143 } else if (reg_smax(dst_reg) <= 0) { 14144 reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0); 14145 } else { 14146 reg_set_srange64(dst_reg, -res_max_abs, res_max_abs); 14147 } 14148 14149 /* Reset other ranges/tnum to unbounded/unknown. */ 14150 reset_reg32_and_tnum(dst_reg); 14151 } 14152 14153 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14154 struct bpf_reg_state *src_reg) 14155 { 14156 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14157 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14158 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14159 u32 umax_val = reg_u32_max(src_reg); 14160 14161 if (src_known && dst_known) { 14162 __mark_reg32_known(dst_reg, var32_off.value); 14163 return; 14164 } 14165 14166 /* We get our minimum from the var_off, since that's inherently 14167 * bitwise. Our maximum is the minimum of the operands' maxima. 14168 */ 14169 reg_set_urange32(dst_reg, 14170 var32_off.value, 14171 min(reg_u32_max(dst_reg), umax_val)); 14172 } 14173 14174 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14175 struct bpf_reg_state *src_reg) 14176 { 14177 bool src_known = tnum_is_const(src_reg->var_off); 14178 bool dst_known = tnum_is_const(dst_reg->var_off); 14179 u64 umax_val = reg_umax(src_reg); 14180 14181 if (src_known && dst_known) { 14182 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14183 return; 14184 } 14185 14186 /* We get our minimum from the var_off, since that's inherently 14187 * bitwise. Our maximum is the minimum of the operands' maxima. 14188 */ 14189 reg_set_urange64(dst_reg, 14190 dst_reg->var_off.value, 14191 min(reg_umax(dst_reg), umax_val)); 14192 14193 /* We may learn something more from the var_off */ 14194 __update_reg_bounds(dst_reg); 14195 } 14196 14197 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14198 struct bpf_reg_state *src_reg) 14199 { 14200 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14201 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14202 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14203 u32 umin_val = reg_u32_min(src_reg); 14204 14205 if (src_known && dst_known) { 14206 __mark_reg32_known(dst_reg, var32_off.value); 14207 return; 14208 } 14209 14210 /* We get our maximum from the var_off, and our minimum is the 14211 * maximum of the operands' minima 14212 */ 14213 reg_set_urange32(dst_reg, 14214 max(reg_u32_min(dst_reg), umin_val), 14215 var32_off.value | var32_off.mask); 14216 } 14217 14218 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14219 struct bpf_reg_state *src_reg) 14220 { 14221 bool src_known = tnum_is_const(src_reg->var_off); 14222 bool dst_known = tnum_is_const(dst_reg->var_off); 14223 u64 umin_val = reg_umin(src_reg); 14224 14225 if (src_known && dst_known) { 14226 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14227 return; 14228 } 14229 14230 /* We get our maximum from the var_off, and our minimum is the 14231 * maximum of the operands' minima 14232 */ 14233 reg_set_urange64(dst_reg, 14234 max(reg_umin(dst_reg), umin_val), 14235 dst_reg->var_off.value | dst_reg->var_off.mask); 14236 14237 /* We may learn something more from the var_off */ 14238 __update_reg_bounds(dst_reg); 14239 } 14240 14241 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 14242 struct bpf_reg_state *src_reg) 14243 { 14244 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14245 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14246 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14247 14248 if (src_known && dst_known) { 14249 __mark_reg32_known(dst_reg, var32_off.value); 14250 return; 14251 } 14252 14253 /* We get both minimum and maximum from the var32_off. */ 14254 reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask); 14255 } 14256 14257 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 14258 struct bpf_reg_state *src_reg) 14259 { 14260 bool src_known = tnum_is_const(src_reg->var_off); 14261 bool dst_known = tnum_is_const(dst_reg->var_off); 14262 14263 if (src_known && dst_known) { 14264 /* dst_reg->var_off.value has been updated earlier */ 14265 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14266 return; 14267 } 14268 14269 /* We get both minimum and maximum from the var_off. */ 14270 reg_set_urange64(dst_reg, 14271 dst_reg->var_off.value, 14272 dst_reg->var_off.value | dst_reg->var_off.mask); 14273 } 14274 14275 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14276 u64 umin_val, u64 umax_val) 14277 { 14278 /* If we might shift our top bit out, then we know nothing */ 14279 if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val)) 14280 reg_set_urange32(dst_reg, 0, U32_MAX); 14281 else 14282 /* We lose all sign bit information (except what we can pick 14283 * up from var_off) 14284 */ 14285 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val, 14286 reg_u32_max(dst_reg) << umax_val); 14287 } 14288 14289 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14290 struct bpf_reg_state *src_reg) 14291 { 14292 u32 umax_val = reg_u32_max(src_reg); 14293 u32 umin_val = reg_u32_min(src_reg); 14294 /* u32 alu operation will zext upper bits */ 14295 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14296 14297 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14298 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 14299 /* Not required but being careful mark reg64 bounds as unknown so 14300 * that we are forced to pick them up from tnum and zext later and 14301 * if some path skips this step we are still safe. 14302 */ 14303 __mark_reg64_unbounded(dst_reg); 14304 __update_reg32_bounds(dst_reg); 14305 } 14306 14307 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 14308 u64 umin_val, u64 umax_val) 14309 { 14310 struct cnum64 u, s; 14311 14312 /* Special case <<32 because it is a common compiler pattern to sign 14313 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct 14314 * because s32 bounds don't flip sign when shifting to the left by 14315 * 32bits. 14316 */ 14317 if (umin_val == 32 && umax_val == 32) 14318 s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32, 14319 (s64)reg_s32_max(dst_reg) << 32); 14320 else 14321 s = CNUM64_UNBOUNDED; 14322 14323 /* If we might shift our top bit out, then we know nothing */ 14324 if (reg_umax(dst_reg) > 1ULL << (63 - umax_val)) 14325 u = CNUM64_UNBOUNDED; 14326 else 14327 u = cnum64_from_urange(reg_umin(dst_reg) << umin_val, 14328 reg_umax(dst_reg) << umax_val); 14329 14330 dst_reg->r64 = cnum64_intersect(u, s); 14331 } 14332 14333 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 14334 struct bpf_reg_state *src_reg) 14335 { 14336 u64 umax_val = reg_umax(src_reg); 14337 u64 umin_val = reg_umin(src_reg); 14338 14339 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 14340 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 14341 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14342 14343 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 14344 /* We may learn something more from the var_off */ 14345 __update_reg_bounds(dst_reg); 14346 } 14347 14348 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 14349 struct bpf_reg_state *src_reg) 14350 { 14351 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14352 u32 umax_val = reg_u32_max(src_reg); 14353 u32 umin_val = reg_u32_min(src_reg); 14354 14355 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14356 * be negative, then either: 14357 * 1) src_reg might be zero, so the sign bit of the result is 14358 * unknown, so we lose our signed bounds 14359 * 2) it's known negative, thus the unsigned bounds capture the 14360 * signed bounds 14361 * 3) the signed bounds cross zero, so they tell us nothing 14362 * about the result 14363 * If the value in dst_reg is known nonnegative, then again the 14364 * unsigned bounds capture the signed bounds. 14365 * Thus, in all cases it suffices to blow away our signed bounds 14366 * and rely on inferring new ones from the unsigned bounds and 14367 * var_off of the result. 14368 */ 14369 14370 dst_reg->var_off = tnum_rshift(subreg, umin_val); 14371 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val, 14372 reg_u32_max(dst_reg) >> umin_val); 14373 14374 __mark_reg64_unbounded(dst_reg); 14375 __update_reg32_bounds(dst_reg); 14376 } 14377 14378 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 14379 struct bpf_reg_state *src_reg) 14380 { 14381 u64 umax_val = reg_umax(src_reg); 14382 u64 umin_val = reg_umin(src_reg); 14383 14384 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14385 * be negative, then either: 14386 * 1) src_reg might be zero, so the sign bit of the result is 14387 * unknown, so we lose our signed bounds 14388 * 2) it's known negative, thus the unsigned bounds capture the 14389 * signed bounds 14390 * 3) the signed bounds cross zero, so they tell us nothing 14391 * about the result 14392 * If the value in dst_reg is known nonnegative, then again the 14393 * unsigned bounds capture the signed bounds. 14394 * Thus, in all cases it suffices to blow away our signed bounds 14395 * and rely on inferring new ones from the unsigned bounds and 14396 * var_off of the result. 14397 */ 14398 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 14399 reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val, 14400 reg_umax(dst_reg) >> umin_val); 14401 14402 /* Its not easy to operate on alu32 bounds here because it depends 14403 * on bits being shifted in. Take easy way out and mark unbounded 14404 * so we can recalculate later from tnum. 14405 */ 14406 __mark_reg32_unbounded(dst_reg); 14407 __update_reg_bounds(dst_reg); 14408 } 14409 14410 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 14411 struct bpf_reg_state *src_reg) 14412 { 14413 u64 umin_val = reg_u32_min(src_reg); 14414 14415 /* Upon reaching here, src_known is true and 14416 * umax_val is equal to umin_val. 14417 * Blow away the dst_reg umin_value/umax_value and rely on 14418 * dst_reg var_off to refine the result. 14419 */ 14420 reg_set_srange32(dst_reg, 14421 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val), 14422 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val)); 14423 14424 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 14425 14426 __mark_reg64_unbounded(dst_reg); 14427 __update_reg32_bounds(dst_reg); 14428 } 14429 14430 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 14431 struct bpf_reg_state *src_reg) 14432 { 14433 u64 umin_val = reg_umin(src_reg); 14434 14435 /* Upon reaching here, src_known is true and umax_val is equal 14436 * to umin_val. 14437 */ 14438 reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val, 14439 reg_smax(dst_reg) >> umin_val); 14440 14441 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14442 14443 /* Its not easy to operate on alu32 bounds here because it depends 14444 * on bits being shifted in from upper 32-bits. Take easy way out 14445 * and mark unbounded so we can recalculate later from tnum. 14446 */ 14447 __mark_reg32_unbounded(dst_reg); 14448 __update_reg_bounds(dst_reg); 14449 } 14450 14451 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn) 14452 { 14453 /* 14454 * Byte swap operation - update var_off using tnum_bswap. 14455 * Three cases: 14456 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE) 14457 * unconditional swap 14458 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE) 14459 * swap on big-endian, truncation or no-op on little-endian 14460 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE) 14461 * swap on little-endian, truncation or no-op on big-endian 14462 */ 14463 14464 bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64; 14465 bool to_le = BPF_SRC(insn->code) == BPF_TO_LE; 14466 bool is_big_endian; 14467 #ifdef CONFIG_CPU_BIG_ENDIAN 14468 is_big_endian = true; 14469 #else 14470 is_big_endian = false; 14471 #endif 14472 /* Apply bswap if alu64 or switch between big-endian and little-endian machines */ 14473 bool need_bswap = alu64 || (to_le == is_big_endian); 14474 14475 /* 14476 * If the register is mutated, manually reset its scalar ID to break 14477 * any existing ties and avoid incorrect bounds propagation. 14478 */ 14479 if (need_bswap || insn->imm == 16 || insn->imm == 32) 14480 clear_scalar_id(dst_reg); 14481 14482 if (need_bswap) { 14483 if (insn->imm == 16) 14484 dst_reg->var_off = tnum_bswap16(dst_reg->var_off); 14485 else if (insn->imm == 32) 14486 dst_reg->var_off = tnum_bswap32(dst_reg->var_off); 14487 else if (insn->imm == 64) 14488 dst_reg->var_off = tnum_bswap64(dst_reg->var_off); 14489 /* 14490 * Byteswap scrambles the range, so we must reset bounds. 14491 * Bounds will be re-derived from the new tnum later. 14492 */ 14493 __mark_reg_unbounded(dst_reg); 14494 } 14495 /* For bswap16/32, truncate dst register to match the swapped size */ 14496 if (insn->imm == 16 || insn->imm == 32) 14497 coerce_reg_to_size(dst_reg, insn->imm / 8); 14498 } 14499 14500 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14501 const struct bpf_reg_state *src_reg) 14502 { 14503 bool src_is_const = false; 14504 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14505 14506 if (insn_bitness == 32) { 14507 if (tnum_subreg_is_const(src_reg->var_off) 14508 && reg_s32_min(src_reg) == reg_s32_max(src_reg) 14509 && reg_u32_min(src_reg) == reg_u32_max(src_reg)) 14510 src_is_const = true; 14511 } else { 14512 if (tnum_is_const(src_reg->var_off) 14513 && reg_smin(src_reg) == reg_smax(src_reg) 14514 && reg_umin(src_reg) == reg_umax(src_reg)) 14515 src_is_const = true; 14516 } 14517 14518 switch (BPF_OP(insn->code)) { 14519 case BPF_ADD: 14520 case BPF_SUB: 14521 case BPF_NEG: 14522 case BPF_AND: 14523 case BPF_XOR: 14524 case BPF_OR: 14525 case BPF_MUL: 14526 case BPF_END: 14527 return true; 14528 14529 /* 14530 * Division and modulo operators range is only safe to compute when the 14531 * divisor is a constant. 14532 */ 14533 case BPF_DIV: 14534 case BPF_MOD: 14535 return src_is_const; 14536 14537 /* Shift operators range is only computable if shift dimension operand 14538 * is a constant. Shifts greater than 31 or 63 are undefined. This 14539 * includes shifts by a negative number. 14540 */ 14541 case BPF_LSH: 14542 case BPF_RSH: 14543 case BPF_ARSH: 14544 return (src_is_const && reg_umax(src_reg) < insn_bitness); 14545 default: 14546 return false; 14547 } 14548 } 14549 14550 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn, 14551 struct bpf_reg_state *dst_reg) 14552 { 14553 struct bpf_verifier_state *branch; 14554 struct bpf_reg_state *regs; 14555 bool alu32; 14556 14557 if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0) 14558 alu32 = false; 14559 else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0) 14560 alu32 = true; 14561 else 14562 return 0; 14563 14564 branch = push_stack(env, env->insn_idx, env->insn_idx, false); 14565 if (IS_ERR(branch)) 14566 return PTR_ERR(branch); 14567 14568 regs = branch->frame[branch->curframe]->regs; 14569 if (alu32) { 14570 __mark_reg32_known(®s[insn->dst_reg], 0); 14571 __mark_reg32_known(dst_reg, -1ull); 14572 } else { 14573 __mark_reg_known(®s[insn->dst_reg], 0); 14574 __mark_reg_known(dst_reg, -1ull); 14575 } 14576 return 0; 14577 } 14578 14579 /* WARNING: This function does calculations on 64-bit values, but the actual 14580 * execution may occur on 32-bit values. Therefore, things like bitshifts 14581 * need extra checks in the 32-bit case. 14582 */ 14583 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14584 struct bpf_insn *insn, 14585 struct bpf_reg_state *dst_reg, 14586 struct bpf_reg_state src_reg) 14587 { 14588 u8 opcode = BPF_OP(insn->code); 14589 s16 off = insn->off; 14590 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14591 int ret; 14592 14593 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14594 __mark_reg_unknown(env, dst_reg); 14595 return 0; 14596 } 14597 14598 if (sanitize_needed(opcode)) { 14599 ret = sanitize_val_alu(env, insn); 14600 if (ret < 0) 14601 return sanitize_err(env, insn, ret, NULL, NULL); 14602 } 14603 14604 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14605 * There are two classes of instructions: The first class we track both 14606 * alu32 and alu64 sign/unsigned bounds independently this provides the 14607 * greatest amount of precision when alu operations are mixed with jmp32 14608 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14609 * and BPF_OR. This is possible because these ops have fairly easy to 14610 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14611 * See alu32 verifier tests for examples. The second class of 14612 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14613 * with regards to tracking sign/unsigned bounds because the bits may 14614 * cross subreg boundaries in the alu64 case. When this happens we mark 14615 * the reg unbounded in the subreg bound space and use the resulting 14616 * tnum to calculate an approximation of the sign/unsigned bounds. 14617 */ 14618 switch (opcode) { 14619 case BPF_ADD: 14620 scalar32_min_max_add(dst_reg, &src_reg); 14621 scalar_min_max_add(dst_reg, &src_reg); 14622 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14623 break; 14624 case BPF_SUB: 14625 scalar32_min_max_sub(dst_reg, &src_reg); 14626 scalar_min_max_sub(dst_reg, &src_reg); 14627 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14628 break; 14629 case BPF_NEG: 14630 env->fake_reg[0] = *dst_reg; 14631 __mark_reg_known(dst_reg, 0); 14632 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 14633 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 14634 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 14635 break; 14636 case BPF_MUL: 14637 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14638 scalar32_min_max_mul(dst_reg, &src_reg); 14639 scalar_min_max_mul(dst_reg, &src_reg); 14640 break; 14641 case BPF_DIV: 14642 /* BPF div specification: x / 0 = 0 */ 14643 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) { 14644 ___mark_reg_known(dst_reg, 0); 14645 break; 14646 } 14647 if (alu32) 14648 if (off == 1) 14649 scalar32_min_max_sdiv(dst_reg, &src_reg); 14650 else 14651 scalar32_min_max_udiv(dst_reg, &src_reg); 14652 else 14653 if (off == 1) 14654 scalar_min_max_sdiv(dst_reg, &src_reg); 14655 else 14656 scalar_min_max_udiv(dst_reg, &src_reg); 14657 break; 14658 case BPF_MOD: 14659 /* BPF mod specification: x % 0 = x */ 14660 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) 14661 break; 14662 if (alu32) 14663 if (off == 1) 14664 scalar32_min_max_smod(dst_reg, &src_reg); 14665 else 14666 scalar32_min_max_umod(dst_reg, &src_reg); 14667 else 14668 if (off == 1) 14669 scalar_min_max_smod(dst_reg, &src_reg); 14670 else 14671 scalar_min_max_umod(dst_reg, &src_reg); 14672 break; 14673 case BPF_AND: 14674 if (tnum_is_const(src_reg.var_off)) { 14675 ret = maybe_fork_scalars(env, insn, dst_reg); 14676 if (ret) 14677 return ret; 14678 } 14679 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14680 scalar32_min_max_and(dst_reg, &src_reg); 14681 scalar_min_max_and(dst_reg, &src_reg); 14682 break; 14683 case BPF_OR: 14684 if (tnum_is_const(src_reg.var_off)) { 14685 ret = maybe_fork_scalars(env, insn, dst_reg); 14686 if (ret) 14687 return ret; 14688 } 14689 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14690 scalar32_min_max_or(dst_reg, &src_reg); 14691 scalar_min_max_or(dst_reg, &src_reg); 14692 break; 14693 case BPF_XOR: 14694 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14695 scalar32_min_max_xor(dst_reg, &src_reg); 14696 scalar_min_max_xor(dst_reg, &src_reg); 14697 break; 14698 case BPF_LSH: 14699 if (alu32) 14700 scalar32_min_max_lsh(dst_reg, &src_reg); 14701 else 14702 scalar_min_max_lsh(dst_reg, &src_reg); 14703 break; 14704 case BPF_RSH: 14705 if (alu32) 14706 scalar32_min_max_rsh(dst_reg, &src_reg); 14707 else 14708 scalar_min_max_rsh(dst_reg, &src_reg); 14709 break; 14710 case BPF_ARSH: 14711 if (alu32) 14712 scalar32_min_max_arsh(dst_reg, &src_reg); 14713 else 14714 scalar_min_max_arsh(dst_reg, &src_reg); 14715 break; 14716 case BPF_END: 14717 scalar_byte_swap(dst_reg, insn); 14718 break; 14719 default: 14720 break; 14721 } 14722 14723 /* 14724 * ALU32 ops are zero extended into 64bit register. 14725 * 14726 * BPF_END is already handled inside the helper (truncation), 14727 * so skip zext here to avoid unexpected zero extension. 14728 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40 14729 * This is a 64bit byte swap operation with alu32==true, 14730 * but we should not zero extend the result. 14731 */ 14732 if (alu32 && opcode != BPF_END) 14733 zext_32_to_64(dst_reg); 14734 reg_bounds_sync(dst_reg); 14735 return 0; 14736 } 14737 14738 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14739 * and var_off. 14740 */ 14741 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14742 struct bpf_insn *insn) 14743 { 14744 struct bpf_verifier_state *vstate = env->cur_state; 14745 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14746 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14747 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14748 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14749 u8 opcode = BPF_OP(insn->code); 14750 int err; 14751 14752 dst_reg = ®s[insn->dst_reg]; 14753 if (BPF_SRC(insn->code) == BPF_X) 14754 src_reg = ®s[insn->src_reg]; 14755 else 14756 src_reg = NULL; 14757 14758 /* Case where at least one operand is an arena. */ 14759 if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) { 14760 struct bpf_insn_aux_data *aux = cur_aux(env); 14761 14762 if (dst_reg->type != PTR_TO_ARENA) 14763 *dst_reg = *src_reg; 14764 14765 dst_reg->subreg_def = env->insn_idx + 1; 14766 14767 if (BPF_CLASS(insn->code) == BPF_ALU64) 14768 /* 14769 * 32-bit operations zero upper bits automatically. 14770 * 64-bit operations need to be converted to 32. 14771 */ 14772 aux->needs_zext = true; 14773 14774 /* Any arithmetic operations are allowed on arena pointers */ 14775 return 0; 14776 } 14777 14778 if (dst_reg->type != SCALAR_VALUE) 14779 ptr_reg = dst_reg; 14780 14781 if (BPF_SRC(insn->code) == BPF_X) { 14782 if (src_reg->type != SCALAR_VALUE) { 14783 if (dst_reg->type != SCALAR_VALUE) { 14784 /* Combining two pointers by any ALU op yields 14785 * an arbitrary scalar. Disallow all math except 14786 * pointer subtraction 14787 */ 14788 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14789 mark_reg_unknown(env, regs, insn->dst_reg); 14790 return 0; 14791 } 14792 verbose(env, "R%d pointer %s pointer prohibited\n", 14793 insn->dst_reg, 14794 bpf_alu_string[opcode >> 4]); 14795 return -EACCES; 14796 } else { 14797 /* scalar += pointer 14798 * This is legal, but we have to reverse our 14799 * src/dest handling in computing the range 14800 */ 14801 err = mark_chain_precision(env, insn->dst_reg); 14802 if (err) 14803 return err; 14804 return adjust_ptr_min_max_vals(env, insn, 14805 src_reg, dst_reg); 14806 } 14807 } else if (ptr_reg) { 14808 /* pointer += scalar */ 14809 err = mark_chain_precision(env, insn->src_reg); 14810 if (err) 14811 return err; 14812 return adjust_ptr_min_max_vals(env, insn, 14813 dst_reg, src_reg); 14814 } else if (dst_reg->precise) { 14815 /* if dst_reg is precise, src_reg should be precise as well */ 14816 err = mark_chain_precision(env, insn->src_reg); 14817 if (err) 14818 return err; 14819 } 14820 } else { 14821 /* Pretend the src is a reg with a known value, since we only 14822 * need to be able to read from this state. 14823 */ 14824 off_reg.type = SCALAR_VALUE; 14825 __mark_reg_known(&off_reg, insn->imm); 14826 src_reg = &off_reg; 14827 if (ptr_reg) /* pointer += K */ 14828 return adjust_ptr_min_max_vals(env, insn, 14829 ptr_reg, src_reg); 14830 } 14831 14832 /* Got here implies adding two SCALAR_VALUEs */ 14833 if (WARN_ON_ONCE(ptr_reg)) { 14834 print_verifier_state(env, vstate, vstate->curframe, true); 14835 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14836 return -EFAULT; 14837 } 14838 if (WARN_ON(!src_reg)) { 14839 print_verifier_state(env, vstate, vstate->curframe, true); 14840 verbose(env, "verifier internal error: no src_reg\n"); 14841 return -EFAULT; 14842 } 14843 /* 14844 * For alu32 linked register tracking, we need to check dst_reg's 14845 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(), 14846 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX. 14847 */ 14848 u64 dst_umax = reg_umax(dst_reg); 14849 14850 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14851 if (err) 14852 return err; 14853 /* 14854 * Compilers can generate the code 14855 * r1 = r2 14856 * r1 += 0x1 14857 * if r2 < 1000 goto ... 14858 * use r1 in memory access 14859 * So remember constant delta between r2 and r1 and update r1 after 14860 * 'if' condition. 14861 */ 14862 if (env->bpf_capable && 14863 (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) && 14864 dst_reg->id && is_reg_const(src_reg, alu32) && 14865 !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) { 14866 u64 val = reg_const_value(src_reg, alu32); 14867 s32 off; 14868 14869 if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX)) 14870 goto clear_id; 14871 14872 if (alu32 && (dst_umax > U32_MAX)) 14873 goto clear_id; 14874 14875 off = (s32)val; 14876 14877 if (BPF_OP(insn->code) == BPF_SUB) { 14878 /* Negating S32_MIN would overflow */ 14879 if (off == S32_MIN) 14880 goto clear_id; 14881 off = -off; 14882 } 14883 14884 if (dst_reg->id & BPF_ADD_CONST) { 14885 /* 14886 * If the register already went through rX += val 14887 * we cannot accumulate another val into rx->off. 14888 */ 14889 clear_id: 14890 clear_scalar_id(dst_reg); 14891 } else { 14892 if (alu32) 14893 dst_reg->id |= BPF_ADD_CONST32; 14894 else 14895 dst_reg->id |= BPF_ADD_CONST64; 14896 dst_reg->delta = off; 14897 } 14898 } else { 14899 /* 14900 * Make sure ID is cleared otherwise dst_reg min/max could be 14901 * incorrectly propagated into other registers by sync_linked_regs() 14902 */ 14903 clear_scalar_id(dst_reg); 14904 } 14905 return 0; 14906 } 14907 14908 /* check validity of 32-bit and 64-bit arithmetic operations */ 14909 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14910 { 14911 struct bpf_reg_state *regs = cur_regs(env); 14912 u8 opcode = BPF_OP(insn->code); 14913 int err; 14914 14915 if (opcode == BPF_END || opcode == BPF_NEG) { 14916 /* check src operand */ 14917 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14918 if (err) 14919 return err; 14920 14921 if (is_pointer_value(env, insn->dst_reg)) { 14922 verbose(env, "R%d pointer arithmetic prohibited\n", 14923 insn->dst_reg); 14924 return -EACCES; 14925 } 14926 14927 /* check dest operand */ 14928 if (regs[insn->dst_reg].type == SCALAR_VALUE) { 14929 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14930 err = err ?: adjust_scalar_min_max_vals(env, insn, 14931 ®s[insn->dst_reg], 14932 regs[insn->dst_reg]); 14933 } else { 14934 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14935 } 14936 if (err) 14937 return err; 14938 14939 } else if (opcode == BPF_MOV) { 14940 14941 if (BPF_SRC(insn->code) == BPF_X) { 14942 if (insn->off == BPF_ADDR_SPACE_CAST) { 14943 if (!env->prog->aux->arena) { 14944 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14945 return -EINVAL; 14946 } 14947 } 14948 14949 /* check src operand */ 14950 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14951 if (err) 14952 return err; 14953 } 14954 14955 /* check dest operand, mark as required later */ 14956 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14957 if (err) 14958 return err; 14959 14960 if (BPF_SRC(insn->code) == BPF_X) { 14961 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14962 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14963 14964 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14965 if (insn->imm) { 14966 /* off == BPF_ADDR_SPACE_CAST */ 14967 mark_reg_unknown(env, regs, insn->dst_reg); 14968 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14969 dst_reg->type = PTR_TO_ARENA; 14970 /* PTR_TO_ARENA is 32-bit */ 14971 dst_reg->subreg_def = env->insn_idx + 1; 14972 } 14973 } else if (insn->off == 0) { 14974 /* case: R1 = R2 14975 * copy register state to dest reg 14976 */ 14977 assign_scalar_id_before_mov(env, src_reg); 14978 *dst_reg = *src_reg; 14979 dst_reg->subreg_def = DEF_NOT_SUBREG; 14980 } else { 14981 /* case: R1 = (s8, s16 s32)R2 */ 14982 if (is_pointer_value(env, insn->src_reg)) { 14983 verbose(env, 14984 "R%d sign-extension part of pointer\n", 14985 insn->src_reg); 14986 return -EACCES; 14987 } else if (src_reg->type == SCALAR_VALUE) { 14988 bool no_sext; 14989 14990 no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 14991 if (no_sext) 14992 assign_scalar_id_before_mov(env, src_reg); 14993 *dst_reg = *src_reg; 14994 if (!no_sext) 14995 clear_scalar_id(dst_reg); 14996 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 14997 dst_reg->subreg_def = DEF_NOT_SUBREG; 14998 } else { 14999 mark_reg_unknown(env, regs, insn->dst_reg); 15000 } 15001 } 15002 } else { 15003 /* R1 = (u32) R2 */ 15004 if (is_pointer_value(env, insn->src_reg)) { 15005 verbose(env, 15006 "R%d partial copy of pointer\n", 15007 insn->src_reg); 15008 return -EACCES; 15009 } else if (src_reg->type == SCALAR_VALUE) { 15010 if (insn->off == 0) { 15011 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 15012 15013 if (is_src_reg_u32) 15014 assign_scalar_id_before_mov(env, src_reg); 15015 *dst_reg = *src_reg; 15016 /* Make sure ID is cleared if src_reg is not in u32 15017 * range otherwise dst_reg min/max could be incorrectly 15018 * propagated into src_reg by sync_linked_regs() 15019 */ 15020 if (!is_src_reg_u32) 15021 clear_scalar_id(dst_reg); 15022 dst_reg->subreg_def = env->insn_idx + 1; 15023 } else { 15024 /* case: W1 = (s8, s16)W2 */ 15025 bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 15026 15027 if (no_sext) 15028 assign_scalar_id_before_mov(env, src_reg); 15029 *dst_reg = *src_reg; 15030 if (!no_sext) 15031 clear_scalar_id(dst_reg); 15032 dst_reg->subreg_def = env->insn_idx + 1; 15033 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 15034 } 15035 } else { 15036 mark_reg_unknown(env, regs, 15037 insn->dst_reg); 15038 } 15039 zext_32_to_64(dst_reg); 15040 reg_bounds_sync(dst_reg); 15041 } 15042 } else { 15043 /* case: R = imm 15044 * remember the value we stored into this reg 15045 */ 15046 /* clear any state __mark_reg_known doesn't set */ 15047 mark_reg_unknown(env, regs, insn->dst_reg); 15048 regs[insn->dst_reg].type = SCALAR_VALUE; 15049 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15050 __mark_reg_known(regs + insn->dst_reg, 15051 insn->imm); 15052 } else { 15053 __mark_reg_known(regs + insn->dst_reg, 15054 (u32)insn->imm); 15055 } 15056 } 15057 15058 } else { /* all other ALU ops: and, sub, xor, add, ... */ 15059 15060 if (BPF_SRC(insn->code) == BPF_X) { 15061 /* check src1 operand */ 15062 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15063 if (err) 15064 return err; 15065 } 15066 15067 /* check src2 operand */ 15068 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15069 if (err) 15070 return err; 15071 15072 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 15073 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 15074 verbose(env, "div by zero\n"); 15075 return -EINVAL; 15076 } 15077 15078 if ((opcode == BPF_LSH || opcode == BPF_RSH || 15079 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 15080 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 15081 15082 if (insn->imm < 0 || insn->imm >= size) { 15083 verbose(env, "invalid shift %d\n", insn->imm); 15084 return -EINVAL; 15085 } 15086 } 15087 15088 /* check dest operand */ 15089 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15090 err = err ?: adjust_reg_min_max_vals(env, insn); 15091 if (err) 15092 return err; 15093 } 15094 15095 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 15096 } 15097 15098 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 15099 struct bpf_reg_state *dst_reg, 15100 enum bpf_reg_type type, 15101 bool range_right_open) 15102 { 15103 struct bpf_func_state *state; 15104 struct bpf_reg_state *reg; 15105 int new_range; 15106 15107 if (reg_umax(dst_reg) == 0 && range_right_open) 15108 /* This doesn't give us any range */ 15109 return; 15110 15111 if (reg_umax(dst_reg) > MAX_PACKET_OFF) 15112 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15113 * than pkt_end, but that's because it's also less than pkt. 15114 */ 15115 return; 15116 15117 new_range = reg_umax(dst_reg); 15118 if (range_right_open) 15119 new_range++; 15120 15121 /* Examples for register markings: 15122 * 15123 * pkt_data in dst register: 15124 * 15125 * r2 = r3; 15126 * r2 += 8; 15127 * if (r2 > pkt_end) goto <handle exception> 15128 * <access okay> 15129 * 15130 * r2 = r3; 15131 * r2 += 8; 15132 * if (r2 < pkt_end) goto <access okay> 15133 * <handle exception> 15134 * 15135 * Where: 15136 * r2 == dst_reg, pkt_end == src_reg 15137 * r2=pkt(id=n,off=8,r=0) 15138 * r3=pkt(id=n,off=0,r=0) 15139 * 15140 * pkt_data in src register: 15141 * 15142 * r2 = r3; 15143 * r2 += 8; 15144 * if (pkt_end >= r2) goto <access okay> 15145 * <handle exception> 15146 * 15147 * r2 = r3; 15148 * r2 += 8; 15149 * if (pkt_end <= r2) goto <handle exception> 15150 * <access okay> 15151 * 15152 * Where: 15153 * pkt_end == dst_reg, r2 == src_reg 15154 * r2=pkt(id=n,off=8,r=0) 15155 * r3=pkt(id=n,off=0,r=0) 15156 * 15157 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15158 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15159 * and [r3, r3 + 8-1) respectively is safe to access depending on 15160 * the check. 15161 */ 15162 15163 /* If our ids match, then we must have the same max_value. And we 15164 * don't care about the other reg's fixed offset, since if it's too big 15165 * the range won't allow anything. 15166 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16. 15167 */ 15168 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15169 if (reg->type == type && reg->id == dst_reg->id) 15170 /* keep the maximum range already checked */ 15171 reg->range = max(reg->range, new_range); 15172 })); 15173 } 15174 15175 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15176 u8 opcode, bool is_jmp32); 15177 static u8 rev_opcode(u8 opcode); 15178 15179 /* 15180 * Learn more information about live branches by simulating refinement on both branches. 15181 * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means 15182 * that branch is dead. 15183 */ 15184 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32) 15185 { 15186 /* Fallthrough (FALSE) branch */ 15187 regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32); 15188 reg_bounds_sync(&env->false_reg1); 15189 reg_bounds_sync(&env->false_reg2); 15190 /* 15191 * If there is a range bounds violation in *any* of the abstract values in either 15192 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only 15193 * TRUE branch will be taken. 15194 */ 15195 if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2)) 15196 return 1; 15197 15198 /* Jump (TRUE) branch */ 15199 regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32); 15200 reg_bounds_sync(&env->true_reg1); 15201 reg_bounds_sync(&env->true_reg2); 15202 /* 15203 * If there is a range bounds violation in *any* of the abstract values in either 15204 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead. 15205 * Only FALSE branch will be taken. 15206 */ 15207 if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2)) 15208 return 0; 15209 15210 /* Both branches are possible, we can't determine which one will be taken. */ 15211 return -1; 15212 } 15213 15214 /* 15215 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15216 */ 15217 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15218 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15219 { 15220 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15221 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15222 u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1); 15223 u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1); 15224 s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1); 15225 s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1); 15226 u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2); 15227 u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2); 15228 s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2); 15229 s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2); 15230 15231 if (reg1 == reg2) { 15232 switch (opcode) { 15233 case BPF_JGE: 15234 case BPF_JLE: 15235 case BPF_JSGE: 15236 case BPF_JSLE: 15237 case BPF_JEQ: 15238 return 1; 15239 case BPF_JGT: 15240 case BPF_JLT: 15241 case BPF_JSGT: 15242 case BPF_JSLT: 15243 case BPF_JNE: 15244 return 0; 15245 case BPF_JSET: 15246 if (tnum_is_const(t1)) 15247 return t1.value != 0; 15248 else 15249 return (smin1 <= 0 && smax1 >= 0) ? -1 : 1; 15250 default: 15251 return -1; 15252 } 15253 } 15254 15255 switch (opcode) { 15256 case BPF_JEQ: 15257 /* constants, umin/umax and smin/smax checks would be 15258 * redundant in this case because they all should match 15259 */ 15260 if (tnum_is_const(t1) && tnum_is_const(t2)) 15261 return t1.value == t2.value; 15262 if (!tnum_overlap(t1, t2)) 15263 return 0; 15264 /* non-overlapping ranges */ 15265 if (umin1 > umax2 || umax1 < umin2) 15266 return 0; 15267 if (smin1 > smax2 || smax1 < smin2) 15268 return 0; 15269 if (!is_jmp32) { 15270 /* if 64-bit ranges are inconclusive, see if we can 15271 * utilize 32-bit subrange knowledge to eliminate 15272 * branches that can't be taken a priori 15273 */ 15274 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15275 reg_u32_max(reg1) < reg_u32_min(reg2)) 15276 return 0; 15277 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15278 reg_s32_max(reg1) < reg_s32_min(reg2)) 15279 return 0; 15280 } 15281 break; 15282 case BPF_JNE: 15283 /* constants, umin/umax and smin/smax checks would be 15284 * redundant in this case because they all should match 15285 */ 15286 if (tnum_is_const(t1) && tnum_is_const(t2)) 15287 return t1.value != t2.value; 15288 if (!tnum_overlap(t1, t2)) 15289 return 1; 15290 /* non-overlapping ranges */ 15291 if (umin1 > umax2 || umax1 < umin2) 15292 return 1; 15293 if (smin1 > smax2 || smax1 < smin2) 15294 return 1; 15295 if (!is_jmp32) { 15296 /* if 64-bit ranges are inconclusive, see if we can 15297 * utilize 32-bit subrange knowledge to eliminate 15298 * branches that can't be taken a priori 15299 */ 15300 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15301 reg_u32_max(reg1) < reg_u32_min(reg2)) 15302 return 1; 15303 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15304 reg_s32_max(reg1) < reg_s32_min(reg2)) 15305 return 1; 15306 } 15307 break; 15308 case BPF_JSET: 15309 if (!is_reg_const(reg2, is_jmp32)) { 15310 swap(reg1, reg2); 15311 swap(t1, t2); 15312 } 15313 if (!is_reg_const(reg2, is_jmp32)) 15314 return -1; 15315 if ((~t1.mask & t1.value) & t2.value) 15316 return 1; 15317 if (!((t1.mask | t1.value) & t2.value)) 15318 return 0; 15319 break; 15320 case BPF_JGT: 15321 if (umin1 > umax2) 15322 return 1; 15323 else if (umax1 <= umin2) 15324 return 0; 15325 break; 15326 case BPF_JSGT: 15327 if (smin1 > smax2) 15328 return 1; 15329 else if (smax1 <= smin2) 15330 return 0; 15331 break; 15332 case BPF_JLT: 15333 if (umax1 < umin2) 15334 return 1; 15335 else if (umin1 >= umax2) 15336 return 0; 15337 break; 15338 case BPF_JSLT: 15339 if (smax1 < smin2) 15340 return 1; 15341 else if (smin1 >= smax2) 15342 return 0; 15343 break; 15344 case BPF_JGE: 15345 if (umin1 >= umax2) 15346 return 1; 15347 else if (umax1 < umin2) 15348 return 0; 15349 break; 15350 case BPF_JSGE: 15351 if (smin1 >= smax2) 15352 return 1; 15353 else if (smax1 < smin2) 15354 return 0; 15355 break; 15356 case BPF_JLE: 15357 if (umax1 <= umin2) 15358 return 1; 15359 else if (umin1 > umax2) 15360 return 0; 15361 break; 15362 case BPF_JSLE: 15363 if (smax1 <= smin2) 15364 return 1; 15365 else if (smin1 > smax2) 15366 return 0; 15367 break; 15368 } 15369 15370 return simulate_both_branches_taken(env, opcode, is_jmp32); 15371 } 15372 15373 static int flip_opcode(u32 opcode) 15374 { 15375 /* How can we transform "a <op> b" into "b <op> a"? */ 15376 static const u8 opcode_flip[16] = { 15377 /* these stay the same */ 15378 [BPF_JEQ >> 4] = BPF_JEQ, 15379 [BPF_JNE >> 4] = BPF_JNE, 15380 [BPF_JSET >> 4] = BPF_JSET, 15381 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 15382 [BPF_JGE >> 4] = BPF_JLE, 15383 [BPF_JGT >> 4] = BPF_JLT, 15384 [BPF_JLE >> 4] = BPF_JGE, 15385 [BPF_JLT >> 4] = BPF_JGT, 15386 [BPF_JSGE >> 4] = BPF_JSLE, 15387 [BPF_JSGT >> 4] = BPF_JSLT, 15388 [BPF_JSLE >> 4] = BPF_JSGE, 15389 [BPF_JSLT >> 4] = BPF_JSGT 15390 }; 15391 return opcode_flip[opcode >> 4]; 15392 } 15393 15394 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 15395 struct bpf_reg_state *src_reg, 15396 u8 opcode) 15397 { 15398 struct bpf_reg_state *pkt; 15399 15400 if (src_reg->type == PTR_TO_PACKET_END) { 15401 pkt = dst_reg; 15402 } else if (dst_reg->type == PTR_TO_PACKET_END) { 15403 pkt = src_reg; 15404 opcode = flip_opcode(opcode); 15405 } else { 15406 return -1; 15407 } 15408 15409 if (pkt->range >= 0) 15410 return -1; 15411 15412 switch (opcode) { 15413 case BPF_JLE: 15414 /* pkt <= pkt_end */ 15415 fallthrough; 15416 case BPF_JGT: 15417 /* pkt > pkt_end */ 15418 if (pkt->range == BEYOND_PKT_END) 15419 /* pkt has at last one extra byte beyond pkt_end */ 15420 return opcode == BPF_JGT; 15421 break; 15422 case BPF_JLT: 15423 /* pkt < pkt_end */ 15424 fallthrough; 15425 case BPF_JGE: 15426 /* pkt >= pkt_end */ 15427 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 15428 return opcode == BPF_JGE; 15429 break; 15430 } 15431 return -1; 15432 } 15433 15434 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 15435 * and return: 15436 * 1 - branch will be taken and "goto target" will be executed 15437 * 0 - branch will not be taken and fall-through to next insn 15438 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 15439 * range [0,10] 15440 */ 15441 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15442 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15443 { 15444 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 15445 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 15446 15447 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 15448 u64 val; 15449 15450 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 15451 if (!is_reg_const(reg2, is_jmp32)) { 15452 opcode = flip_opcode(opcode); 15453 swap(reg1, reg2); 15454 } 15455 /* and ensure that reg2 is a constant */ 15456 if (!is_reg_const(reg2, is_jmp32)) 15457 return -1; 15458 15459 if (!reg_not_null(env, reg1)) 15460 return -1; 15461 15462 /* If pointer is valid tests against zero will fail so we can 15463 * use this to direct branch taken. 15464 */ 15465 val = reg_const_value(reg2, is_jmp32); 15466 if (val != 0) 15467 return -1; 15468 15469 switch (opcode) { 15470 case BPF_JEQ: 15471 return 0; 15472 case BPF_JNE: 15473 return 1; 15474 default: 15475 return -1; 15476 } 15477 } 15478 15479 /* now deal with two scalars, but not necessarily constants */ 15480 return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32); 15481 } 15482 15483 /* Opcode that corresponds to a *false* branch condition. 15484 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 15485 */ 15486 static u8 rev_opcode(u8 opcode) 15487 { 15488 switch (opcode) { 15489 case BPF_JEQ: return BPF_JNE; 15490 case BPF_JNE: return BPF_JEQ; 15491 /* JSET doesn't have it's reverse opcode in BPF, so add 15492 * BPF_X flag to denote the reverse of that operation 15493 */ 15494 case BPF_JSET: return BPF_JSET | BPF_X; 15495 case BPF_JSET | BPF_X: return BPF_JSET; 15496 case BPF_JGE: return BPF_JLT; 15497 case BPF_JGT: return BPF_JLE; 15498 case BPF_JLE: return BPF_JGT; 15499 case BPF_JLT: return BPF_JGE; 15500 case BPF_JSGE: return BPF_JSLT; 15501 case BPF_JSGT: return BPF_JSLE; 15502 case BPF_JSLE: return BPF_JSGT; 15503 case BPF_JSLT: return BPF_JSGE; 15504 default: return 0; 15505 } 15506 } 15507 15508 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 15509 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15510 u8 opcode, bool is_jmp32) 15511 { 15512 struct tnum t; 15513 u64 val; 15514 15515 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 15516 switch (opcode) { 15517 case BPF_JGE: 15518 case BPF_JGT: 15519 case BPF_JSGE: 15520 case BPF_JSGT: 15521 opcode = flip_opcode(opcode); 15522 swap(reg1, reg2); 15523 break; 15524 default: 15525 break; 15526 } 15527 15528 switch (opcode) { 15529 case BPF_JEQ: 15530 if (is_jmp32) { 15531 reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32); 15532 reg2->r32 = reg1->r32; 15533 15534 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 15535 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15536 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 15537 } else { 15538 reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64); 15539 reg2->r64 = reg1->r64; 15540 15541 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 15542 reg2->var_off = reg1->var_off; 15543 } 15544 break; 15545 case BPF_JNE: 15546 if (!is_reg_const(reg2, is_jmp32)) 15547 swap(reg1, reg2); 15548 if (!is_reg_const(reg2, is_jmp32)) 15549 break; 15550 15551 /* try to recompute the bound of reg1 if reg2 is a const and 15552 * is exactly the edge of reg1. 15553 */ 15554 val = reg_const_value(reg2, is_jmp32); 15555 if (is_jmp32) { 15556 /* Complement of the range [val, val] as cnum32. */ 15557 cnum32_intersect_with(®1->r32, (struct cnum32){ val + 1, U32_MAX - 1 }); 15558 } else { 15559 /* Complement of the range [val, val] as cnum64. */ 15560 cnum64_intersect_with(®1->r64, (struct cnum64){ val + 1, U64_MAX - 1 }); 15561 } 15562 break; 15563 case BPF_JSET: 15564 if (!is_reg_const(reg2, is_jmp32)) 15565 swap(reg1, reg2); 15566 if (!is_reg_const(reg2, is_jmp32)) 15567 break; 15568 val = reg_const_value(reg2, is_jmp32); 15569 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 15570 * requires single bit to learn something useful. E.g., if we 15571 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 15572 * are actually set? We can learn something definite only if 15573 * it's a single-bit value to begin with. 15574 * 15575 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 15576 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 15577 * bit 1 is set, which we can readily use in adjustments. 15578 */ 15579 if (!is_power_of_2(val)) 15580 break; 15581 if (is_jmp32) { 15582 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 15583 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15584 } else { 15585 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 15586 } 15587 break; 15588 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 15589 if (!is_reg_const(reg2, is_jmp32)) 15590 swap(reg1, reg2); 15591 if (!is_reg_const(reg2, is_jmp32)) 15592 break; 15593 val = reg_const_value(reg2, is_jmp32); 15594 /* Forget the ranges before narrowing tnums, to avoid invariant 15595 * violations if we're on a dead branch. 15596 */ 15597 __mark_reg_unbounded(reg1); 15598 if (is_jmp32) { 15599 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 15600 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15601 } else { 15602 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15603 } 15604 break; 15605 case BPF_JLE: 15606 if (is_jmp32) { 15607 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2)); 15608 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1), U32_MAX); 15609 } else { 15610 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2)); 15611 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1), U64_MAX); 15612 } 15613 break; 15614 case BPF_JLT: 15615 if (is_jmp32) { 15616 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2) - 1); 15617 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1) + 1, U32_MAX); 15618 } else { 15619 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2) - 1); 15620 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1) + 1, U64_MAX); 15621 } 15622 break; 15623 case BPF_JSLE: 15624 if (is_jmp32) { 15625 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2)); 15626 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1), S32_MAX); 15627 } else { 15628 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2)); 15629 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1), S64_MAX); 15630 } 15631 break; 15632 case BPF_JSLT: 15633 if (is_jmp32) { 15634 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2) - 1); 15635 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1) + 1, S32_MAX); 15636 } else { 15637 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2) - 1); 15638 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1) + 1, S64_MAX); 15639 } 15640 break; 15641 default: 15642 return; 15643 } 15644 } 15645 15646 /* Check for invariant violations on the registers for both branches of a condition */ 15647 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env) 15648 { 15649 int err; 15650 15651 err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1"); 15652 err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2"); 15653 err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1"); 15654 err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2"); 15655 return err; 15656 } 15657 15658 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 15659 struct bpf_reg_state *reg, u32 id, 15660 bool is_null) 15661 { 15662 if (type_may_be_null(reg->type) && reg->id == id && 15663 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 15664 /* Old offset should have been known-zero, because we don't 15665 * allow pointer arithmetic on pointers that might be NULL. 15666 * If we see this happening, don't convert the register. 15667 * 15668 * But in some cases, some helpers that return local kptrs 15669 * advance offset for the returned pointer. In those cases, 15670 * it is fine to expect to see reg->var_off. 15671 */ 15672 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 15673 WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0))) 15674 return; 15675 if (is_null) { 15676 /* We don't need id from this point 15677 * onwards anymore, thus we should better reset it, 15678 * so that state pruning has chances to take effect. 15679 */ 15680 __mark_reg_known_zero(reg); 15681 reg->type = SCALAR_VALUE; 15682 15683 return; 15684 } 15685 15686 mark_ptr_not_null_reg(reg); 15687 15688 /* 15689 * reg->id is preserved for object relationship tracking 15690 * and spin_lock lock state tracking 15691 */ 15692 } 15693 } 15694 15695 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15696 * be folded together at some point. 15697 */ 15698 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15699 bool is_null) 15700 { 15701 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15702 struct bpf_reg_state *regs = state->regs, *reg; 15703 u32 id = regs[regno].id; 15704 15705 if (is_null && find_reference_state(vstate, id)) 15706 /* regs[regno] is in the " == NULL" branch. 15707 * No one could have freed the reference state before 15708 * doing the NULL check. 15709 */ 15710 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 15711 15712 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15713 mark_ptr_or_null_reg(state, reg, id, is_null); 15714 })); 15715 } 15716 15717 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15718 struct bpf_reg_state *dst_reg, 15719 struct bpf_reg_state *src_reg, 15720 struct bpf_verifier_state *this_branch, 15721 struct bpf_verifier_state *other_branch) 15722 { 15723 if (BPF_SRC(insn->code) != BPF_X) 15724 return false; 15725 15726 /* Pointers are always 64-bit. */ 15727 if (BPF_CLASS(insn->code) == BPF_JMP32) 15728 return false; 15729 15730 switch (BPF_OP(insn->code)) { 15731 case BPF_JGT: 15732 if ((dst_reg->type == PTR_TO_PACKET && 15733 src_reg->type == PTR_TO_PACKET_END) || 15734 (dst_reg->type == PTR_TO_PACKET_META && 15735 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15736 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15737 find_good_pkt_pointers(this_branch, dst_reg, 15738 dst_reg->type, false); 15739 mark_pkt_end(other_branch, insn->dst_reg, true); 15740 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15741 src_reg->type == PTR_TO_PACKET) || 15742 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15743 src_reg->type == PTR_TO_PACKET_META)) { 15744 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15745 find_good_pkt_pointers(other_branch, src_reg, 15746 src_reg->type, true); 15747 mark_pkt_end(this_branch, insn->src_reg, false); 15748 } else { 15749 return false; 15750 } 15751 break; 15752 case BPF_JLT: 15753 if ((dst_reg->type == PTR_TO_PACKET && 15754 src_reg->type == PTR_TO_PACKET_END) || 15755 (dst_reg->type == PTR_TO_PACKET_META && 15756 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15757 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15758 find_good_pkt_pointers(other_branch, dst_reg, 15759 dst_reg->type, true); 15760 mark_pkt_end(this_branch, insn->dst_reg, false); 15761 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15762 src_reg->type == PTR_TO_PACKET) || 15763 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15764 src_reg->type == PTR_TO_PACKET_META)) { 15765 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15766 find_good_pkt_pointers(this_branch, src_reg, 15767 src_reg->type, false); 15768 mark_pkt_end(other_branch, insn->src_reg, true); 15769 } else { 15770 return false; 15771 } 15772 break; 15773 case BPF_JGE: 15774 if ((dst_reg->type == PTR_TO_PACKET && 15775 src_reg->type == PTR_TO_PACKET_END) || 15776 (dst_reg->type == PTR_TO_PACKET_META && 15777 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15778 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15779 find_good_pkt_pointers(this_branch, dst_reg, 15780 dst_reg->type, true); 15781 mark_pkt_end(other_branch, insn->dst_reg, false); 15782 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15783 src_reg->type == PTR_TO_PACKET) || 15784 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15785 src_reg->type == PTR_TO_PACKET_META)) { 15786 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15787 find_good_pkt_pointers(other_branch, src_reg, 15788 src_reg->type, false); 15789 mark_pkt_end(this_branch, insn->src_reg, true); 15790 } else { 15791 return false; 15792 } 15793 break; 15794 case BPF_JLE: 15795 if ((dst_reg->type == PTR_TO_PACKET && 15796 src_reg->type == PTR_TO_PACKET_END) || 15797 (dst_reg->type == PTR_TO_PACKET_META && 15798 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15799 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15800 find_good_pkt_pointers(other_branch, dst_reg, 15801 dst_reg->type, false); 15802 mark_pkt_end(this_branch, insn->dst_reg, true); 15803 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15804 src_reg->type == PTR_TO_PACKET) || 15805 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15806 src_reg->type == PTR_TO_PACKET_META)) { 15807 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15808 find_good_pkt_pointers(this_branch, src_reg, 15809 src_reg->type, true); 15810 mark_pkt_end(other_branch, insn->src_reg, false); 15811 } else { 15812 return false; 15813 } 15814 break; 15815 default: 15816 return false; 15817 } 15818 15819 return true; 15820 } 15821 15822 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 15823 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 15824 { 15825 struct linked_reg *e; 15826 15827 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 15828 return; 15829 15830 e = linked_regs_push(reg_set); 15831 if (e) { 15832 e->frameno = frameno; 15833 e->is_reg = is_reg; 15834 e->regno = spi_or_reg; 15835 } else { 15836 clear_scalar_id(reg); 15837 } 15838 } 15839 15840 /* For all R being scalar registers or spilled scalar registers 15841 * in verifier state, save R in linked_regs if R->id == id. 15842 * If there are too many Rs sharing same id, reset id for leftover Rs. 15843 */ 15844 static void collect_linked_regs(struct bpf_verifier_env *env, 15845 struct bpf_verifier_state *vstate, 15846 u32 id, 15847 struct linked_regs *linked_regs) 15848 { 15849 struct bpf_insn_aux_data *aux = env->insn_aux_data; 15850 struct bpf_func_state *func; 15851 struct bpf_reg_state *reg; 15852 u16 live_regs; 15853 int i, j; 15854 15855 id = id & ~BPF_ADD_CONST; 15856 for (i = vstate->curframe; i >= 0; i--) { 15857 live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before; 15858 func = vstate->frame[i]; 15859 for (j = 0; j < BPF_REG_FP; j++) { 15860 if (!(live_regs & BIT(j))) 15861 continue; 15862 reg = &func->regs[j]; 15863 __collect_linked_regs(linked_regs, reg, id, i, j, true); 15864 } 15865 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 15866 if (!bpf_is_spilled_reg(&func->stack[j])) 15867 continue; 15868 reg = &func->stack[j].spilled_ptr; 15869 __collect_linked_regs(linked_regs, reg, id, i, j, false); 15870 } 15871 } 15872 } 15873 15874 /* For all R in linked_regs, copy known_reg range into R 15875 * if R->id == known_reg->id. 15876 */ 15877 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate, 15878 struct bpf_reg_state *known_reg, struct linked_regs *linked_regs) 15879 { 15880 struct bpf_reg_state fake_reg; 15881 struct bpf_reg_state *reg; 15882 struct linked_reg *e; 15883 int i; 15884 15885 for (i = 0; i < linked_regs->cnt; ++i) { 15886 e = &linked_regs->entries[i]; 15887 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 15888 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 15889 if (reg->type != SCALAR_VALUE || reg == known_reg) 15890 continue; 15891 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15892 continue; 15893 /* 15894 * Skip mixed 32/64-bit links: the delta relationship doesn't 15895 * hold across different ALU widths. 15896 */ 15897 if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST) 15898 continue; 15899 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15900 reg->delta == known_reg->delta) { 15901 s32 saved_subreg_def = reg->subreg_def; 15902 15903 *reg = *known_reg; 15904 reg->subreg_def = saved_subreg_def; 15905 } else { 15906 s32 saved_subreg_def = reg->subreg_def; 15907 s32 saved_off = reg->delta; 15908 u32 saved_id = reg->id; 15909 15910 fake_reg.type = SCALAR_VALUE; 15911 __mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta); 15912 15913 /* reg = known_reg; reg += delta */ 15914 *reg = *known_reg; 15915 /* 15916 * Must preserve off, id and subreg_def flag, 15917 * otherwise another sync_linked_regs() will be incorrect. 15918 */ 15919 reg->delta = saved_off; 15920 reg->id = saved_id; 15921 reg->subreg_def = saved_subreg_def; 15922 15923 scalar32_min_max_add(reg, &fake_reg); 15924 scalar_min_max_add(reg, &fake_reg); 15925 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15926 if ((reg->id | known_reg->id) & BPF_ADD_CONST32) 15927 zext_32_to_64(reg); 15928 reg_bounds_sync(reg); 15929 } 15930 if (e->is_reg) 15931 mark_reg_scratched(env, e->regno); 15932 else 15933 mark_stack_slot_scratched(env, e->spi); 15934 } 15935 } 15936 15937 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15938 struct bpf_insn *insn, int *insn_idx) 15939 { 15940 struct bpf_verifier_state *this_branch = env->cur_state; 15941 struct bpf_verifier_state *other_branch; 15942 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15943 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15944 struct bpf_reg_state *eq_branch_regs; 15945 struct linked_regs linked_regs = {}; 15946 u8 opcode = BPF_OP(insn->code); 15947 int insn_flags = 0; 15948 bool is_jmp32; 15949 int pred = -1; 15950 int err; 15951 15952 /* Only conditional jumps are expected to reach here. */ 15953 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15954 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15955 return -EINVAL; 15956 } 15957 15958 if (opcode == BPF_JCOND) { 15959 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15960 int idx = *insn_idx; 15961 15962 prev_st = find_prev_entry(env, cur_st->parent, idx); 15963 15964 /* branch out 'fallthrough' insn as a new state to explore */ 15965 queued_st = push_stack(env, idx + 1, idx, false); 15966 if (IS_ERR(queued_st)) 15967 return PTR_ERR(queued_st); 15968 15969 queued_st->may_goto_depth++; 15970 if (prev_st) 15971 widen_imprecise_scalars(env, prev_st, queued_st); 15972 *insn_idx += insn->off; 15973 return 0; 15974 } 15975 15976 /* check src2 operand */ 15977 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15978 if (err) 15979 return err; 15980 15981 dst_reg = ®s[insn->dst_reg]; 15982 if (BPF_SRC(insn->code) == BPF_X) { 15983 /* check src1 operand */ 15984 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15985 if (err) 15986 return err; 15987 15988 src_reg = ®s[insn->src_reg]; 15989 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15990 is_pointer_value(env, insn->src_reg)) { 15991 verbose(env, "R%d pointer comparison prohibited\n", 15992 insn->src_reg); 15993 return -EACCES; 15994 } 15995 15996 if (src_reg->type == PTR_TO_STACK) 15997 insn_flags |= INSN_F_SRC_REG_STACK; 15998 if (dst_reg->type == PTR_TO_STACK) 15999 insn_flags |= INSN_F_DST_REG_STACK; 16000 } else { 16001 src_reg = &env->fake_reg[0]; 16002 memset(src_reg, 0, sizeof(*src_reg)); 16003 src_reg->type = SCALAR_VALUE; 16004 __mark_reg_known(src_reg, insn->imm); 16005 16006 if (dst_reg->type == PTR_TO_STACK) 16007 insn_flags |= INSN_F_DST_REG_STACK; 16008 } 16009 16010 if (insn_flags) { 16011 err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, 0); 16012 if (err) 16013 return err; 16014 } 16015 16016 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 16017 env->false_reg1 = *dst_reg; 16018 env->false_reg2 = *src_reg; 16019 env->true_reg1 = *dst_reg; 16020 env->true_reg2 = *src_reg; 16021 pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32); 16022 if (pred >= 0) { 16023 /* If we get here with a dst_reg pointer type it is because 16024 * above is_branch_taken() special cased the 0 comparison. 16025 */ 16026 if (!__is_pointer_value(false, dst_reg)) 16027 err = mark_chain_precision(env, insn->dst_reg); 16028 if (BPF_SRC(insn->code) == BPF_X && !err && 16029 !__is_pointer_value(false, src_reg)) 16030 err = mark_chain_precision(env, insn->src_reg); 16031 if (err) 16032 return err; 16033 } 16034 16035 if (pred == 1) { 16036 /* Only follow the goto, ignore fall-through. If needed, push 16037 * the fall-through branch for simulation under speculative 16038 * execution. 16039 */ 16040 if (!env->bypass_spec_v1) { 16041 err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx); 16042 if (err < 0) 16043 return err; 16044 } 16045 if (env->log.level & BPF_LOG_LEVEL) 16046 print_insn_state(env, this_branch, this_branch->curframe); 16047 *insn_idx += insn->off; 16048 return 0; 16049 } else if (pred == 0) { 16050 /* Only follow the fall-through branch, since that's where the 16051 * program will go. If needed, push the goto branch for 16052 * simulation under speculative execution. 16053 */ 16054 if (!env->bypass_spec_v1) { 16055 err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1, 16056 *insn_idx); 16057 if (err < 0) 16058 return err; 16059 } 16060 if (env->log.level & BPF_LOG_LEVEL) 16061 print_insn_state(env, this_branch, this_branch->curframe); 16062 return 0; 16063 } 16064 16065 /* Push scalar registers sharing same ID to jump history, 16066 * do this before creating 'other_branch', so that both 16067 * 'this_branch' and 'other_branch' share this history 16068 * if parent state is created. 16069 */ 16070 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 16071 collect_linked_regs(env, this_branch, src_reg->id, &linked_regs); 16072 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 16073 collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs); 16074 if (linked_regs.cnt > 1) { 16075 err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, linked_regs_pack(&linked_regs)); 16076 if (err) 16077 return err; 16078 } 16079 16080 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); 16081 if (IS_ERR(other_branch)) 16082 return PTR_ERR(other_branch); 16083 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 16084 16085 err = regs_bounds_sanity_check_branches(env); 16086 if (err) 16087 return err; 16088 16089 *dst_reg = env->false_reg1; 16090 *src_reg = env->false_reg2; 16091 other_branch_regs[insn->dst_reg] = env->true_reg1; 16092 if (BPF_SRC(insn->code) == BPF_X) 16093 other_branch_regs[insn->src_reg] = env->true_reg2; 16094 16095 if (BPF_SRC(insn->code) == BPF_X && 16096 src_reg->type == SCALAR_VALUE && src_reg->id && 16097 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 16098 sync_linked_regs(env, this_branch, src_reg, &linked_regs); 16099 sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg], 16100 &linked_regs); 16101 } 16102 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 16103 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 16104 sync_linked_regs(env, this_branch, dst_reg, &linked_regs); 16105 sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg], 16106 &linked_regs); 16107 } 16108 16109 /* if one pointer register is compared to another pointer 16110 * register check if PTR_MAYBE_NULL could be lifted. 16111 * E.g. register A - maybe null 16112 * register B - not null 16113 * for JNE A, B, ... - A is not null in the false branch; 16114 * for JEQ A, B, ... - A is not null in the true branch. 16115 * 16116 * Since PTR_TO_BTF_ID points to a kernel struct that does 16117 * not need to be null checked by the BPF program, i.e., 16118 * could be null even without PTR_MAYBE_NULL marking, so 16119 * only propagate nullness when neither reg is that type. 16120 */ 16121 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16122 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16123 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16124 base_type(src_reg->type) != PTR_TO_BTF_ID && 16125 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16126 eq_branch_regs = NULL; 16127 switch (opcode) { 16128 case BPF_JEQ: 16129 eq_branch_regs = other_branch_regs; 16130 break; 16131 case BPF_JNE: 16132 eq_branch_regs = regs; 16133 break; 16134 default: 16135 /* do nothing */ 16136 break; 16137 } 16138 if (eq_branch_regs) { 16139 if (type_may_be_null(src_reg->type)) 16140 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16141 else 16142 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16143 } 16144 } 16145 16146 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16147 * Also does the same detection for a register whose the value is 16148 * known to be 0. 16149 * NOTE: these optimizations below are related with pointer comparison 16150 * which will never be JMP32. 16151 */ 16152 if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16153 type_may_be_null(dst_reg->type) && 16154 ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) || 16155 (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) { 16156 /* Mark all identical registers in each branch as either 16157 * safe or unknown depending R == 0 or R != 0 conditional. 16158 */ 16159 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16160 opcode == BPF_JNE); 16161 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16162 opcode == BPF_JEQ); 16163 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16164 this_branch, other_branch) && 16165 is_pointer_value(env, insn->dst_reg)) { 16166 verbose(env, "R%d pointer comparison prohibited\n", 16167 insn->dst_reg); 16168 return -EACCES; 16169 } 16170 if (env->log.level & BPF_LOG_LEVEL) 16171 print_insn_state(env, this_branch, this_branch->curframe); 16172 return 0; 16173 } 16174 16175 /* verify BPF_LD_IMM64 instruction */ 16176 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16177 { 16178 struct bpf_insn_aux_data *aux = cur_aux(env); 16179 struct bpf_reg_state *regs = cur_regs(env); 16180 struct bpf_reg_state *dst_reg; 16181 struct bpf_map *map; 16182 int err; 16183 16184 if (BPF_SIZE(insn->code) != BPF_DW) { 16185 verbose(env, "invalid BPF_LD_IMM insn\n"); 16186 return -EINVAL; 16187 } 16188 16189 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16190 if (err) 16191 return err; 16192 16193 dst_reg = ®s[insn->dst_reg]; 16194 if (insn->src_reg == 0) { 16195 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16196 16197 dst_reg->type = SCALAR_VALUE; 16198 __mark_reg_known(®s[insn->dst_reg], imm); 16199 return 0; 16200 } 16201 16202 /* All special src_reg cases are listed below. From this point onwards 16203 * we either succeed and assign a corresponding dst_reg->type after 16204 * zeroing the offset, or fail and reject the program. 16205 */ 16206 mark_reg_known_zero(env, regs, insn->dst_reg); 16207 16208 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16209 dst_reg->type = aux->btf_var.reg_type; 16210 switch (base_type(dst_reg->type)) { 16211 case PTR_TO_MEM: 16212 dst_reg->mem_size = aux->btf_var.mem_size; 16213 break; 16214 case PTR_TO_BTF_ID: 16215 dst_reg->btf = aux->btf_var.btf; 16216 dst_reg->btf_id = aux->btf_var.btf_id; 16217 break; 16218 default: 16219 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 16220 return -EFAULT; 16221 } 16222 return 0; 16223 } 16224 16225 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16226 struct bpf_prog_aux *aux = env->prog->aux; 16227 u32 subprogno = bpf_find_subprog(env, 16228 env->insn_idx + insn->imm + 1); 16229 16230 if (!aux->func_info) { 16231 verbose(env, "missing btf func_info\n"); 16232 return -EINVAL; 16233 } 16234 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16235 verbose(env, "callback function not static\n"); 16236 return -EINVAL; 16237 } 16238 16239 dst_reg->type = PTR_TO_FUNC; 16240 dst_reg->subprogno = subprogno; 16241 return 0; 16242 } 16243 16244 map = env->used_maps[aux->map_index]; 16245 16246 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16247 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16248 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16249 __mark_reg_unknown(env, dst_reg); 16250 dst_reg->map_ptr = map; 16251 return 0; 16252 } 16253 __mark_reg_known(dst_reg, aux->map_off); 16254 dst_reg->type = PTR_TO_MAP_VALUE; 16255 dst_reg->map_ptr = map; 16256 WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY && 16257 map->max_entries != 1); 16258 /* We want reg->id to be same (0) as map_value is not distinct */ 16259 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16260 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16261 dst_reg->type = CONST_PTR_TO_MAP; 16262 dst_reg->map_ptr = map; 16263 } else { 16264 verifier_bug(env, "unexpected src reg value for ldimm64"); 16265 return -EFAULT; 16266 } 16267 16268 return 0; 16269 } 16270 16271 static bool may_access_skb(enum bpf_prog_type type) 16272 { 16273 switch (type) { 16274 case BPF_PROG_TYPE_SOCKET_FILTER: 16275 case BPF_PROG_TYPE_SCHED_CLS: 16276 case BPF_PROG_TYPE_SCHED_ACT: 16277 return true; 16278 default: 16279 return false; 16280 } 16281 } 16282 16283 /* verify safety of LD_ABS|LD_IND instructions: 16284 * - they can only appear in the programs where ctx == skb 16285 * - since they are wrappers of function calls, they scratch R1-R5 registers, 16286 * preserve R6-R9, and store return value into R0 16287 * 16288 * Implicit input: 16289 * ctx == skb == R6 == CTX 16290 * 16291 * Explicit input: 16292 * SRC == any register 16293 * IMM == 32-bit immediate 16294 * 16295 * Output: 16296 * R0 - 8/16/32-bit skb data converted to cpu endianness 16297 */ 16298 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 16299 { 16300 struct bpf_reg_state *regs = cur_regs(env); 16301 static const int ctx_reg = BPF_REG_6; 16302 u8 mode = BPF_MODE(insn->code); 16303 int i, err; 16304 16305 if (!may_access_skb(resolve_prog_type(env->prog))) { 16306 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 16307 return -EINVAL; 16308 } 16309 16310 if (!env->ops->gen_ld_abs) { 16311 verifier_bug(env, "gen_ld_abs is null"); 16312 return -EFAULT; 16313 } 16314 16315 /* check whether implicit source operand (register R6) is readable */ 16316 err = check_reg_arg(env, ctx_reg, SRC_OP); 16317 if (err) 16318 return err; 16319 16320 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 16321 * gen_ld_abs() may terminate the program at runtime, leading to 16322 * reference leak. 16323 */ 16324 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 16325 if (err) 16326 return err; 16327 16328 if (regs[ctx_reg].type != PTR_TO_CTX) { 16329 verbose(env, 16330 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 16331 return -EINVAL; 16332 } 16333 16334 if (mode == BPF_IND) { 16335 /* check explicit source operand */ 16336 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16337 if (err) 16338 return err; 16339 } 16340 16341 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 16342 if (err < 0) 16343 return err; 16344 16345 /* reset caller saved regs to unreadable */ 16346 for (i = 0; i < CALLER_SAVED_REGS; i++) { 16347 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 16348 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 16349 } 16350 16351 /* mark destination R0 register as readable, since it contains 16352 * the value fetched from the packet. 16353 * Already marked as written above. 16354 */ 16355 mark_reg_unknown(env, regs, BPF_REG_0); 16356 /* ld_abs load up to 32-bit skb data. */ 16357 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 16358 /* 16359 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0 16360 * which must be explored by the verifier when in a subprog. 16361 */ 16362 if (env->cur_state->curframe) { 16363 struct bpf_verifier_state *branch; 16364 16365 mark_reg_scratched(env, BPF_REG_0); 16366 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 16367 if (IS_ERR(branch)) 16368 return PTR_ERR(branch); 16369 mark_reg_known_zero(env, regs, BPF_REG_0); 16370 err = prepare_func_exit(env, &env->insn_idx); 16371 if (err) 16372 return err; 16373 env->insn_idx--; 16374 } 16375 return 0; 16376 } 16377 16378 16379 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range) 16380 { 16381 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16382 16383 /* Default return value range. */ 16384 *range = retval_range(0, 1); 16385 16386 switch (prog_type) { 16387 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 16388 switch (env->prog->expected_attach_type) { 16389 case BPF_CGROUP_UDP4_RECVMSG: 16390 case BPF_CGROUP_UDP6_RECVMSG: 16391 case BPF_CGROUP_UNIX_RECVMSG: 16392 case BPF_CGROUP_INET4_GETPEERNAME: 16393 case BPF_CGROUP_INET6_GETPEERNAME: 16394 case BPF_CGROUP_UNIX_GETPEERNAME: 16395 case BPF_CGROUP_INET4_GETSOCKNAME: 16396 case BPF_CGROUP_INET6_GETSOCKNAME: 16397 case BPF_CGROUP_UNIX_GETSOCKNAME: 16398 *range = retval_range(1, 1); 16399 break; 16400 case BPF_CGROUP_INET4_BIND: 16401 case BPF_CGROUP_INET6_BIND: 16402 *range = retval_range(0, 3); 16403 break; 16404 default: 16405 break; 16406 } 16407 break; 16408 case BPF_PROG_TYPE_CGROUP_SKB: 16409 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) 16410 *range = retval_range(0, 3); 16411 break; 16412 case BPF_PROG_TYPE_CGROUP_SOCK: 16413 case BPF_PROG_TYPE_SOCK_OPS: 16414 case BPF_PROG_TYPE_CGROUP_DEVICE: 16415 case BPF_PROG_TYPE_CGROUP_SYSCTL: 16416 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 16417 break; 16418 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16419 if (!env->prog->aux->attach_btf_id) 16420 return false; 16421 *range = retval_range(0, 0); 16422 break; 16423 case BPF_PROG_TYPE_TRACING: 16424 switch (env->prog->expected_attach_type) { 16425 case BPF_TRACE_FENTRY: 16426 case BPF_TRACE_FEXIT: 16427 case BPF_TRACE_FSESSION: 16428 case BPF_TRACE_FENTRY_MULTI: 16429 case BPF_TRACE_FEXIT_MULTI: 16430 case BPF_TRACE_FSESSION_MULTI: 16431 *range = retval_range(0, 0); 16432 break; 16433 case BPF_TRACE_RAW_TP: 16434 case BPF_MODIFY_RETURN: 16435 return false; 16436 case BPF_TRACE_ITER: 16437 default: 16438 break; 16439 } 16440 break; 16441 case BPF_PROG_TYPE_KPROBE: 16442 switch (env->prog->expected_attach_type) { 16443 case BPF_TRACE_KPROBE_SESSION: 16444 case BPF_TRACE_UPROBE_SESSION: 16445 break; 16446 default: 16447 return false; 16448 } 16449 break; 16450 case BPF_PROG_TYPE_SK_LOOKUP: 16451 *range = retval_range(SK_DROP, SK_PASS); 16452 break; 16453 16454 case BPF_PROG_TYPE_LSM: 16455 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 16456 /* no range found, any return value is allowed */ 16457 if (!get_func_retval_range(env->prog, range)) 16458 return false; 16459 /* no restricted range, any return value is allowed */ 16460 if (range->minval == S32_MIN && range->maxval == S32_MAX) 16461 return false; 16462 range->return_32bit = true; 16463 } else if (!env->prog->aux->attach_func_proto->type) { 16464 /* Make sure programs that attach to void 16465 * hooks don't try to modify return value. 16466 */ 16467 *range = retval_range(1, 1); 16468 } 16469 break; 16470 16471 case BPF_PROG_TYPE_NETFILTER: 16472 *range = retval_range(NF_DROP, NF_ACCEPT); 16473 break; 16474 case BPF_PROG_TYPE_STRUCT_OPS: 16475 *range = retval_range(0, 0); 16476 break; 16477 case BPF_PROG_TYPE_EXT: 16478 /* freplace program can return anything as its return value 16479 * depends on the to-be-replaced kernel func or bpf program. 16480 */ 16481 default: 16482 return false; 16483 } 16484 16485 /* Continue calculating. */ 16486 16487 return true; 16488 } 16489 16490 static bool program_returns_void(struct bpf_verifier_env *env) 16491 { 16492 const struct bpf_prog *prog = env->prog; 16493 enum bpf_prog_type prog_type = prog->type; 16494 16495 switch (prog_type) { 16496 case BPF_PROG_TYPE_LSM: 16497 /* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */ 16498 if (prog->expected_attach_type != BPF_LSM_CGROUP && 16499 !prog->aux->attach_func_proto->type) 16500 return true; 16501 break; 16502 case BPF_PROG_TYPE_STRUCT_OPS: 16503 if (!prog->aux->attach_func_proto->type) 16504 return true; 16505 break; 16506 case BPF_PROG_TYPE_EXT: 16507 /* 16508 * If the actual program is an extension, let it 16509 * return void - attaching will succeed only if the 16510 * program being replaced also returns void, and since 16511 * it has passed verification its actual type doesn't matter. 16512 */ 16513 if (subprog_returns_void(env, 0)) 16514 return true; 16515 break; 16516 default: 16517 break; 16518 } 16519 return false; 16520 } 16521 16522 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 16523 { 16524 const char *exit_ctx = "At program exit"; 16525 struct tnum enforce_attach_type_range = tnum_unknown; 16526 const struct bpf_prog *prog = env->prog; 16527 struct bpf_reg_state *reg = reg_state(env, regno); 16528 struct bpf_retval_range range = retval_range(0, 1); 16529 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16530 struct bpf_func_state *frame = env->cur_state->frame[0]; 16531 const struct btf_type *reg_type, *ret_type = NULL; 16532 int err; 16533 16534 /* LSM and struct_ops func-ptr's return type could be "void" */ 16535 if (!frame->in_async_callback_fn && program_returns_void(env)) 16536 return 0; 16537 16538 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) { 16539 /* Allow a struct_ops program to return a referenced kptr if it 16540 * matches the operator's return type and is in its unmodified 16541 * form. A scalar zero (i.e., a null pointer) is also allowed. 16542 */ 16543 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 16544 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 16545 prog->aux->attach_func_proto->type, 16546 NULL); 16547 if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg)) 16548 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 16549 } 16550 16551 /* eBPF calling convention is such that R0 is used 16552 * to return the value from eBPF program. 16553 * Make sure that it's readable at this time 16554 * of bpf_exit, which means that program wrote 16555 * something into it earlier 16556 */ 16557 err = check_reg_arg(env, regno, SRC_OP); 16558 if (err) 16559 return err; 16560 16561 if (is_pointer_value(env, regno)) { 16562 verbose(env, "R%d leaks addr as return value\n", regno); 16563 return -EACCES; 16564 } 16565 16566 if (frame->in_async_callback_fn) { 16567 exit_ctx = "At async callback return"; 16568 range = frame->callback_ret_range; 16569 goto enforce_retval; 16570 } 16571 16572 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type) 16573 return 0; 16574 16575 if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)) 16576 enforce_attach_type_range = tnum_range(2, 3); 16577 16578 if (!return_retval_range(env, &range)) 16579 return 0; 16580 16581 enforce_retval: 16582 if (reg->type != SCALAR_VALUE) { 16583 verbose(env, "%s the register R%d is not a known value (%s)\n", 16584 exit_ctx, regno, reg_type_str(env, reg->type)); 16585 return -EINVAL; 16586 } 16587 16588 err = mark_chain_precision(env, regno); 16589 if (err) 16590 return err; 16591 16592 if (!retval_range_within(range, reg)) { 16593 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 16594 if (prog->expected_attach_type == BPF_LSM_CGROUP && 16595 prog_type == BPF_PROG_TYPE_LSM && 16596 !prog->aux->attach_func_proto->type) 16597 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 16598 return -EINVAL; 16599 } 16600 16601 if (!tnum_is_unknown(enforce_attach_type_range) && 16602 tnum_in(enforce_attach_type_range, reg->var_off)) 16603 env->prog->enforce_expected_attach_type = 1; 16604 return 0; 16605 } 16606 16607 static int check_global_subprog_return_code(struct bpf_verifier_env *env) 16608 { 16609 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 16610 struct bpf_func_state *cur_frame = cur_func(env); 16611 int err; 16612 16613 if (subprog_returns_void(env, cur_frame->subprogno)) 16614 return 0; 16615 16616 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 16617 if (err) 16618 return err; 16619 16620 /* Pointers to arena are safe to pass between subprograms. */ 16621 if (is_arena_reg(env, BPF_REG_0)) 16622 return 0; 16623 16624 if (is_pointer_value(env, BPF_REG_0)) { 16625 verbose(env, "R%d leaks addr as return value\n", BPF_REG_0); 16626 return -EACCES; 16627 } 16628 16629 if (reg->type != SCALAR_VALUE) { 16630 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 16631 reg_type_str(env, reg->type)); 16632 return -EINVAL; 16633 } 16634 16635 return 0; 16636 } 16637 16638 /* Bitmask with 1s for all caller saved registers */ 16639 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16640 16641 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16642 * replacement patch is presumed to follow bpf_fastcall contract 16643 * (see mark_fastcall_pattern_for_call() below). 16644 */ 16645 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 16646 { 16647 switch (imm) { 16648 #ifdef CONFIG_X86_64 16649 case BPF_FUNC_get_smp_processor_id: 16650 #ifdef CONFIG_SMP 16651 case BPF_FUNC_get_current_task_btf: 16652 case BPF_FUNC_get_current_task: 16653 #endif 16654 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 16655 #endif 16656 default: 16657 return false; 16658 } 16659 } 16660 16661 /* If @call is a kfunc or helper call, fills @cs and returns true, 16662 * otherwise returns false. 16663 */ 16664 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 16665 struct bpf_call_summary *cs) 16666 { 16667 struct bpf_kfunc_call_arg_meta meta; 16668 const struct bpf_func_proto *fn; 16669 int i; 16670 16671 if (bpf_helper_call(call)) { 16672 16673 if (bpf_get_helper_proto(env, call->imm, &fn) < 0) 16674 /* error would be reported later */ 16675 return false; 16676 cs->fastcall = fn->allow_fastcall && 16677 (bpf_verifier_inlines_helper_call(env, call->imm) || 16678 bpf_jit_inlines_helper_call(call->imm)); 16679 cs->is_void = fn->ret_type == RET_VOID; 16680 cs->num_params = 0; 16681 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 16682 if (fn->arg_type[i] == ARG_DONTCARE) 16683 break; 16684 cs->num_params++; 16685 } 16686 return true; 16687 } 16688 16689 if (bpf_pseudo_kfunc_call(call)) { 16690 int err; 16691 16692 err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta); 16693 if (err < 0) 16694 /* error would be reported later */ 16695 return false; 16696 cs->num_params = btf_type_vlen(meta.func_proto); 16697 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 16698 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 16699 return true; 16700 } 16701 16702 return false; 16703 } 16704 16705 /* LLVM define a bpf_fastcall function attribute. 16706 * This attribute means that function scratches only some of 16707 * the caller saved registers defined by ABI. 16708 * For BPF the set of such registers could be defined as follows: 16709 * - R0 is scratched only if function is non-void; 16710 * - R1-R5 are scratched only if corresponding parameter type is defined 16711 * in the function prototype. 16712 * 16713 * The contract between kernel and clang allows to simultaneously use 16714 * such functions and maintain backwards compatibility with old 16715 * kernels that don't understand bpf_fastcall calls: 16716 * 16717 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 16718 * registers are not scratched by the call; 16719 * 16720 * - as a post-processing step, clang visits each bpf_fastcall call and adds 16721 * spill/fill for every live r0-r5; 16722 * 16723 * - stack offsets used for the spill/fill are allocated as lowest 16724 * stack offsets in whole function and are not used for any other 16725 * purposes; 16726 * 16727 * - when kernel loads a program, it looks for such patterns 16728 * (bpf_fastcall function surrounded by spills/fills) and checks if 16729 * spill/fill stack offsets are used exclusively in fastcall patterns; 16730 * 16731 * - if so, and if verifier or current JIT inlines the call to the 16732 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 16733 * spill/fill pairs; 16734 * 16735 * - when old kernel loads a program, presence of spill/fill pairs 16736 * keeps BPF program valid, albeit slightly less efficient. 16737 * 16738 * For example: 16739 * 16740 * r1 = 1; 16741 * r2 = 2; 16742 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16743 * *(u64 *)(r10 - 16) = r2; r2 = 2; 16744 * call %[to_be_inlined] --> call %[to_be_inlined] 16745 * r2 = *(u64 *)(r10 - 16); r0 = r1; 16746 * r1 = *(u64 *)(r10 - 8); r0 += r2; 16747 * r0 = r1; exit; 16748 * r0 += r2; 16749 * exit; 16750 * 16751 * The purpose of mark_fastcall_pattern_for_call is to: 16752 * - look for such patterns; 16753 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 16754 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 16755 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 16756 * at which bpf_fastcall spill/fill stack slots start; 16757 * - update env->subprog_info[*]->keep_fastcall_stack. 16758 * 16759 * The .fastcall_pattern and .fastcall_stack_off are used by 16760 * check_fastcall_stack_contract() to check if every stack access to 16761 * fastcall spill/fill stack slot originates from spill/fill 16762 * instructions, members of fastcall patterns. 16763 * 16764 * If such condition holds true for a subprogram, fastcall patterns could 16765 * be rewritten by remove_fastcall_spills_fills(). 16766 * Otherwise bpf_fastcall patterns are not changed in the subprogram 16767 * (code, presumably, generated by an older clang version). 16768 * 16769 * For example, it is *not* safe to remove spill/fill below: 16770 * 16771 * r1 = 1; 16772 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16773 * call %[to_be_inlined] --> call %[to_be_inlined] 16774 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 16775 * r0 = *(u64 *)(r10 - 8); r0 += r1; 16776 * r0 += r1; exit; 16777 * exit; 16778 */ 16779 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 16780 struct bpf_subprog_info *subprog, 16781 int insn_idx, s16 lowest_off) 16782 { 16783 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 16784 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 16785 u32 clobbered_regs_mask; 16786 struct bpf_call_summary cs; 16787 u32 expected_regs_mask; 16788 s16 off; 16789 int i; 16790 16791 if (!bpf_get_call_summary(env, call, &cs)) 16792 return; 16793 16794 /* A bitmask specifying which caller saved registers are clobbered 16795 * by a call to a helper/kfunc *as if* this helper/kfunc follows 16796 * bpf_fastcall contract: 16797 * - includes R0 if function is non-void; 16798 * - includes R1-R5 if corresponding parameter has is described 16799 * in the function prototype. 16800 */ 16801 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 16802 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 16803 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 16804 16805 /* match pairs of form: 16806 * 16807 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 16808 * ... 16809 * call %[to_be_inlined] 16810 * ... 16811 * rX = *(u64 *)(r10 - Y) 16812 */ 16813 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 16814 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 16815 break; 16816 stx = &insns[insn_idx - i]; 16817 ldx = &insns[insn_idx + i]; 16818 /* must be a stack spill/fill pair */ 16819 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 16820 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 16821 stx->dst_reg != BPF_REG_10 || 16822 ldx->src_reg != BPF_REG_10) 16823 break; 16824 /* must be a spill/fill for the same reg */ 16825 if (stx->src_reg != ldx->dst_reg) 16826 break; 16827 /* must be one of the previously unseen registers */ 16828 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 16829 break; 16830 /* must be a spill/fill for the same expected offset, 16831 * no need to check offset alignment, BPF_DW stack access 16832 * is always 8-byte aligned. 16833 */ 16834 if (stx->off != off || ldx->off != off) 16835 break; 16836 expected_regs_mask &= ~BIT(stx->src_reg); 16837 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 16838 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 16839 } 16840 if (i == 1) 16841 return; 16842 16843 /* Conditionally set 'fastcall_spills_num' to allow forward 16844 * compatibility when more helper functions are marked as 16845 * bpf_fastcall at compile time than current kernel supports, e.g: 16846 * 16847 * 1: *(u64 *)(r10 - 8) = r1 16848 * 2: call A ;; assume A is bpf_fastcall for current kernel 16849 * 3: r1 = *(u64 *)(r10 - 8) 16850 * 4: *(u64 *)(r10 - 8) = r1 16851 * 5: call B ;; assume B is not bpf_fastcall for current kernel 16852 * 6: r1 = *(u64 *)(r10 - 8) 16853 * 16854 * There is no need to block bpf_fastcall rewrite for such program. 16855 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 16856 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 16857 * does not remove spill/fill pair {4,6}. 16858 */ 16859 if (cs.fastcall) 16860 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 16861 else 16862 subprog->keep_fastcall_stack = 1; 16863 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 16864 } 16865 16866 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 16867 { 16868 struct bpf_subprog_info *subprog = env->subprog_info; 16869 struct bpf_insn *insn; 16870 s16 lowest_off; 16871 int s, i; 16872 16873 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 16874 /* find lowest stack spill offset used in this subprog */ 16875 lowest_off = 0; 16876 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16877 insn = env->prog->insnsi + i; 16878 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 16879 insn->dst_reg != BPF_REG_10) 16880 continue; 16881 lowest_off = min(lowest_off, insn->off); 16882 } 16883 /* use this offset to find fastcall patterns */ 16884 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16885 insn = env->prog->insnsi + i; 16886 if (insn->code != (BPF_JMP | BPF_CALL)) 16887 continue; 16888 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 16889 } 16890 } 16891 return 0; 16892 } 16893 16894 static void adjust_btf_func(struct bpf_verifier_env *env) 16895 { 16896 struct bpf_prog_aux *aux = env->prog->aux; 16897 int i; 16898 16899 if (!aux->func_info) 16900 return; 16901 16902 /* func_info is not available for hidden subprogs */ 16903 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16904 aux->func_info[i].insn_off = env->subprog_info[i].start; 16905 } 16906 16907 /* Find id in idset and increment its count, or add new entry */ 16908 static void idset_cnt_inc(struct bpf_idset *idset, u32 id) 16909 { 16910 u32 i; 16911 16912 for (i = 0; i < idset->num_ids; i++) { 16913 if (idset->entries[i].id == id) { 16914 idset->entries[i].cnt++; 16915 return; 16916 } 16917 } 16918 /* New id */ 16919 if (idset->num_ids < BPF_ID_MAP_SIZE) { 16920 idset->entries[idset->num_ids].id = id; 16921 idset->entries[idset->num_ids].cnt = 1; 16922 idset->num_ids++; 16923 } 16924 } 16925 16926 /* Find id in idset and return its count, or 0 if not found */ 16927 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id) 16928 { 16929 u32 i; 16930 16931 for (i = 0; i < idset->num_ids; i++) { 16932 if (idset->entries[i].id == id) 16933 return idset->entries[i].cnt; 16934 } 16935 return 0; 16936 } 16937 16938 /* 16939 * Clear singular scalar ids in a state. 16940 * A register with a non-zero id is called singular if no other register shares 16941 * the same base id. Such registers can be treated as independent (id=0). 16942 */ 16943 void bpf_clear_singular_ids(struct bpf_verifier_env *env, 16944 struct bpf_verifier_state *st) 16945 { 16946 struct bpf_idset *idset = &env->idset_scratch; 16947 struct bpf_func_state *func; 16948 struct bpf_reg_state *reg; 16949 16950 idset->num_ids = 0; 16951 16952 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16953 if (reg->type != SCALAR_VALUE) 16954 continue; 16955 if (!reg->id) 16956 continue; 16957 idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST); 16958 })); 16959 16960 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16961 if (reg->type != SCALAR_VALUE) 16962 continue; 16963 if (!reg->id) 16964 continue; 16965 if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1) 16966 clear_scalar_id(reg); 16967 })); 16968 } 16969 16970 /* Return true if it's OK to have the same insn return a different type. */ 16971 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16972 { 16973 switch (base_type(type)) { 16974 case PTR_TO_CTX: 16975 case PTR_TO_SOCKET: 16976 case PTR_TO_SOCK_COMMON: 16977 case PTR_TO_TCP_SOCK: 16978 case PTR_TO_XDP_SOCK: 16979 case PTR_TO_BTF_ID: 16980 case PTR_TO_ARENA: 16981 return false; 16982 default: 16983 return true; 16984 } 16985 } 16986 16987 /* If an instruction was previously used with particular pointer types, then we 16988 * need to be careful to avoid cases such as the below, where it may be ok 16989 * for one branch accessing the pointer, but not ok for the other branch: 16990 * 16991 * R1 = sock_ptr 16992 * goto X; 16993 * ... 16994 * R1 = some_other_valid_ptr; 16995 * goto X; 16996 * ... 16997 * R2 = *(u32 *)(R1 + 0); 16998 */ 16999 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17000 { 17001 return src != prev && (!reg_type_mismatch_ok(src) || 17002 !reg_type_mismatch_ok(prev)); 17003 } 17004 17005 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type) 17006 { 17007 switch (base_type(type)) { 17008 case PTR_TO_MEM: 17009 case PTR_TO_BTF_ID: 17010 return true; 17011 default: 17012 return false; 17013 } 17014 } 17015 17016 static bool is_ptr_to_mem(enum bpf_reg_type type) 17017 { 17018 return base_type(type) == PTR_TO_MEM; 17019 } 17020 17021 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17022 bool allow_trust_mismatch) 17023 { 17024 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17025 enum bpf_reg_type merged_type; 17026 17027 if (*prev_type == NOT_INIT) { 17028 /* Saw a valid insn 17029 * dst_reg = *(u32 *)(src_reg + off) 17030 * save type to validate intersecting paths 17031 */ 17032 *prev_type = type; 17033 } else if (reg_type_mismatch(type, *prev_type)) { 17034 /* Abuser program is trying to use the same insn 17035 * dst_reg = *(u32*) (src_reg + off) 17036 * with different pointer types: 17037 * src_reg == ctx in one branch and 17038 * src_reg == stack|map in some other branch. 17039 * Reject it. 17040 */ 17041 if (allow_trust_mismatch && 17042 is_ptr_to_mem_or_btf_id(type) && 17043 is_ptr_to_mem_or_btf_id(*prev_type)) { 17044 /* 17045 * Have to support a use case when one path through 17046 * the program yields TRUSTED pointer while another 17047 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17048 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17049 * Same behavior of MEM_RDONLY flag. 17050 */ 17051 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type)) 17052 merged_type = PTR_TO_MEM; 17053 else 17054 merged_type = PTR_TO_BTF_ID; 17055 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED)) 17056 merged_type |= PTR_UNTRUSTED; 17057 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY)) 17058 merged_type |= MEM_RDONLY; 17059 *prev_type = merged_type; 17060 } else { 17061 verbose(env, "same insn cannot be used with different pointers\n"); 17062 return -EINVAL; 17063 } 17064 } 17065 17066 return 0; 17067 } 17068 17069 enum { 17070 PROCESS_BPF_EXIT = 1, 17071 INSN_IDX_UPDATED = 2, 17072 }; 17073 17074 static int process_bpf_exit_full(struct bpf_verifier_env *env, 17075 bool *do_print_state, 17076 bool exception_exit) 17077 { 17078 struct bpf_func_state *cur_frame = cur_func(env); 17079 17080 /* We must do check_reference_leak here before 17081 * prepare_func_exit to handle the case when 17082 * state->curframe > 0, it may be a callback function, 17083 * for which reference_state must match caller reference 17084 * state when it exits. 17085 */ 17086 int err = check_resource_leak(env, exception_exit, 17087 exception_exit || !env->cur_state->curframe, 17088 exception_exit ? "bpf_throw" : 17089 "BPF_EXIT instruction in main prog"); 17090 if (err) 17091 return err; 17092 17093 /* The side effect of the prepare_func_exit which is 17094 * being skipped is that it frees bpf_func_state. 17095 * Typically, process_bpf_exit will only be hit with 17096 * outermost exit. copy_verifier_state in pop_stack will 17097 * handle freeing of any extra bpf_func_state left over 17098 * from not processing all nested function exits. We 17099 * also skip return code checks as they are not needed 17100 * for exceptional exits. 17101 */ 17102 if (exception_exit) 17103 return PROCESS_BPF_EXIT; 17104 17105 if (env->cur_state->curframe) { 17106 /* exit from nested function */ 17107 err = prepare_func_exit(env, &env->insn_idx); 17108 if (err) 17109 return err; 17110 *do_print_state = true; 17111 return INSN_IDX_UPDATED; 17112 } 17113 17114 /* 17115 * Return from a regular global subprogram differs from return 17116 * from the main program or async/exception callback. 17117 * Main program exit implies return code restrictions 17118 * that depend on program type. 17119 * Exit from exception callback is equivalent to main program exit. 17120 * Exit from async callback implies return code restrictions 17121 * that depend on async scheduling mechanism. 17122 */ 17123 if (cur_frame->subprogno && 17124 !cur_frame->in_async_callback_fn && 17125 !cur_frame->in_exception_callback_fn) 17126 err = check_global_subprog_return_code(env); 17127 else 17128 err = check_return_code(env, BPF_REG_0, "R0"); 17129 if (err) 17130 return err; 17131 return PROCESS_BPF_EXIT; 17132 } 17133 17134 static int indirect_jump_min_max_index(struct bpf_verifier_env *env, 17135 int regno, 17136 struct bpf_map *map, 17137 u32 *pmin_index, u32 *pmax_index) 17138 { 17139 struct bpf_reg_state *reg = reg_state(env, regno); 17140 u64 min_index = reg_umin(reg); 17141 u64 max_index = reg_umax(reg); 17142 const u32 size = 8; 17143 17144 if (min_index > (u64) U32_MAX * size) { 17145 verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg)); 17146 return -ERANGE; 17147 } 17148 if (max_index > (u64) U32_MAX * size) { 17149 verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg)); 17150 return -ERANGE; 17151 } 17152 17153 min_index /= size; 17154 max_index /= size; 17155 17156 if (max_index >= map->max_entries) { 17157 verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n", 17158 regno, min_index, max_index, map->max_entries); 17159 return -EINVAL; 17160 } 17161 17162 *pmin_index = min_index; 17163 *pmax_index = max_index; 17164 return 0; 17165 } 17166 17167 /* gotox *dst_reg */ 17168 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn) 17169 { 17170 struct bpf_verifier_state *other_branch; 17171 struct bpf_reg_state *dst_reg; 17172 struct bpf_map *map; 17173 u32 min_index, max_index; 17174 int err = 0; 17175 int n; 17176 int i; 17177 17178 dst_reg = reg_state(env, insn->dst_reg); 17179 if (dst_reg->type != PTR_TO_INSN) { 17180 verbose(env, "R%d has type %s, expected PTR_TO_INSN\n", 17181 insn->dst_reg, reg_type_str(env, dst_reg->type)); 17182 return -EINVAL; 17183 } 17184 17185 map = dst_reg->map_ptr; 17186 if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg)) 17187 return -EFAULT; 17188 17189 if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env, 17190 "R%d has incorrect map type %d", insn->dst_reg, map->map_type)) 17191 return -EFAULT; 17192 17193 err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index); 17194 if (err) 17195 return err; 17196 17197 /* Ensure that the buffer is large enough */ 17198 if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) { 17199 env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf, 17200 max_index - min_index + 1); 17201 if (!env->gotox_tmp_buf) 17202 return -ENOMEM; 17203 } 17204 17205 n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items); 17206 if (n < 0) 17207 return n; 17208 if (n == 0) { 17209 verbose(env, "register R%d doesn't point to any offset in map id=%d\n", 17210 insn->dst_reg, map->id); 17211 return -EINVAL; 17212 } 17213 17214 for (i = 0; i < n - 1; i++) { 17215 mark_indirect_target(env, env->gotox_tmp_buf->items[i]); 17216 other_branch = push_stack(env, env->gotox_tmp_buf->items[i], 17217 env->insn_idx, env->cur_state->speculative); 17218 if (IS_ERR(other_branch)) 17219 return PTR_ERR(other_branch); 17220 } 17221 env->insn_idx = env->gotox_tmp_buf->items[n-1]; 17222 mark_indirect_target(env, env->insn_idx); 17223 return INSN_IDX_UPDATED; 17224 } 17225 17226 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 17227 { 17228 int err; 17229 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 17230 u8 class = BPF_CLASS(insn->code); 17231 17232 switch (class) { 17233 case BPF_ALU: 17234 case BPF_ALU64: 17235 return check_alu_op(env, insn); 17236 17237 case BPF_LDX: 17238 return check_load_mem(env, insn, false, 17239 BPF_MODE(insn->code) == BPF_MEMSX, 17240 true, "ldx"); 17241 17242 case BPF_STX: 17243 if (BPF_MODE(insn->code) == BPF_ATOMIC) 17244 return check_atomic(env, insn); 17245 return check_store_reg(env, insn, false); 17246 17247 case BPF_ST: { 17248 /* Handle stack arg write (store immediate) */ 17249 if (is_stack_arg_st(insn)) { 17250 struct bpf_verifier_state *vstate = env->cur_state; 17251 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 17252 17253 return check_stack_arg_write(env, state, insn->off, NULL); 17254 } 17255 17256 enum bpf_reg_type dst_reg_type; 17257 17258 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17259 if (err) 17260 return err; 17261 17262 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 17263 17264 err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg, argno_from_reg(insn->dst_reg), 17265 insn->off, BPF_SIZE(insn->code), 17266 BPF_WRITE, -1, false, false); 17267 if (err) 17268 return err; 17269 17270 return save_aux_ptr_type(env, dst_reg_type, false); 17271 } 17272 case BPF_JMP: 17273 case BPF_JMP32: { 17274 u8 opcode = BPF_OP(insn->code); 17275 17276 env->jmps_processed++; 17277 if (opcode == BPF_CALL) { 17278 if (env->cur_state->active_locks) { 17279 if ((insn->src_reg == BPF_REG_0 && 17280 insn->imm != BPF_FUNC_spin_unlock && 17281 insn->imm != BPF_FUNC_kptr_xchg) || 17282 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17283 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) { 17284 verbose(env, 17285 "function calls are not allowed while holding a lock\n"); 17286 return -EINVAL; 17287 } 17288 } 17289 mark_reg_scratched(env, BPF_REG_0); 17290 if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno])) 17291 cur_func(env)->no_stack_arg_load = true; 17292 if (insn->src_reg == BPF_PSEUDO_CALL) 17293 return check_func_call(env, insn, &env->insn_idx); 17294 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17295 return check_kfunc_call(env, insn, &env->insn_idx); 17296 return check_helper_call(env, insn, &env->insn_idx); 17297 } else if (opcode == BPF_JA) { 17298 if (BPF_SRC(insn->code) == BPF_X) 17299 return check_indirect_jump(env, insn); 17300 17301 if (class == BPF_JMP) 17302 env->insn_idx += insn->off + 1; 17303 else 17304 env->insn_idx += insn->imm + 1; 17305 return INSN_IDX_UPDATED; 17306 } else if (opcode == BPF_EXIT) { 17307 return process_bpf_exit_full(env, do_print_state, false); 17308 } 17309 return check_cond_jmp_op(env, insn, &env->insn_idx); 17310 } 17311 case BPF_LD: { 17312 u8 mode = BPF_MODE(insn->code); 17313 17314 if (mode == BPF_ABS || mode == BPF_IND) 17315 return check_ld_abs(env, insn); 17316 17317 if (mode == BPF_IMM) { 17318 err = check_ld_imm(env, insn); 17319 if (err) 17320 return err; 17321 17322 env->insn_idx++; 17323 sanitize_mark_insn_seen(env); 17324 } 17325 return 0; 17326 } 17327 } 17328 /* all class values are handled above. silence compiler warning */ 17329 return -EFAULT; 17330 } 17331 17332 static int do_check(struct bpf_verifier_env *env) 17333 { 17334 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17335 struct bpf_verifier_state *state = env->cur_state; 17336 struct bpf_insn *insns = env->prog->insnsi; 17337 int insn_cnt = env->prog->len; 17338 bool do_print_state = false; 17339 int prev_insn_idx = -1; 17340 17341 for (;;) { 17342 struct bpf_insn *insn; 17343 struct bpf_insn_aux_data *insn_aux; 17344 int err; 17345 17346 /* reset current history entry on each new instruction */ 17347 env->cur_hist_ent = NULL; 17348 17349 env->prev_insn_idx = prev_insn_idx; 17350 if (env->insn_idx >= insn_cnt) { 17351 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17352 env->insn_idx, insn_cnt); 17353 return -EFAULT; 17354 } 17355 17356 insn = &insns[env->insn_idx]; 17357 insn_aux = &env->insn_aux_data[env->insn_idx]; 17358 17359 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17360 verbose(env, 17361 "BPF program is too large. Processed %d insn\n", 17362 env->insn_processed); 17363 return -E2BIG; 17364 } 17365 17366 state->last_insn_idx = env->prev_insn_idx; 17367 state->insn_idx = env->insn_idx; 17368 17369 if (bpf_is_prune_point(env, env->insn_idx)) { 17370 err = bpf_is_state_visited(env, env->insn_idx); 17371 if (err < 0) 17372 return err; 17373 if (err == 1) { 17374 /* found equivalent state, can prune the search */ 17375 if (env->log.level & BPF_LOG_LEVEL) { 17376 if (do_print_state) 17377 verbose(env, "\nfrom %d to %d%s: safe\n", 17378 env->prev_insn_idx, env->insn_idx, 17379 env->cur_state->speculative ? 17380 " (speculative execution)" : ""); 17381 else 17382 verbose(env, "%d: safe\n", env->insn_idx); 17383 } 17384 goto process_bpf_exit; 17385 } 17386 } 17387 17388 if (bpf_is_jmp_point(env, env->insn_idx)) { 17389 err = bpf_push_jmp_history(env, state, 0, 0, 0, 0); 17390 if (err) 17391 return err; 17392 } 17393 17394 if (signal_pending(current)) 17395 return -EAGAIN; 17396 17397 if (need_resched()) 17398 cond_resched(); 17399 17400 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17401 verbose(env, "\nfrom %d to %d%s:", 17402 env->prev_insn_idx, env->insn_idx, 17403 env->cur_state->speculative ? 17404 " (speculative execution)" : ""); 17405 print_verifier_state(env, state, state->curframe, true); 17406 do_print_state = false; 17407 } 17408 17409 if (env->log.level & BPF_LOG_LEVEL) { 17410 if (verifier_state_scratched(env)) 17411 print_insn_state(env, state, state->curframe); 17412 17413 verbose_linfo(env, env->insn_idx, "; "); 17414 env->prev_log_pos = env->log.end_pos; 17415 verbose(env, "%d: ", env->insn_idx); 17416 bpf_verbose_insn(env, insn); 17417 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17418 env->prev_log_pos = env->log.end_pos; 17419 } 17420 17421 if (bpf_prog_is_offloaded(env->prog->aux)) { 17422 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17423 env->prev_insn_idx); 17424 if (err) 17425 return err; 17426 } 17427 17428 sanitize_mark_insn_seen(env); 17429 prev_insn_idx = env->insn_idx; 17430 17431 /* Sanity check: precomputed constants must match verifier state */ 17432 if (!state->speculative && insn_aux->const_reg_mask) { 17433 struct bpf_reg_state *regs = cur_regs(env); 17434 u16 mask = insn_aux->const_reg_mask; 17435 17436 for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) { 17437 u32 cval = insn_aux->const_reg_vals[r]; 17438 17439 if (!(mask & BIT(r))) 17440 continue; 17441 if (regs[r].type != SCALAR_VALUE) 17442 continue; 17443 if (!tnum_is_const(regs[r].var_off)) 17444 continue; 17445 if (verifier_bug_if((u32)regs[r].var_off.value != cval, 17446 env, "const R%d: %u != %llu", 17447 r, cval, regs[r].var_off.value)) 17448 return -EFAULT; 17449 } 17450 } 17451 17452 /* Reduce verification complexity by stopping speculative path 17453 * verification when a nospec is encountered. 17454 */ 17455 if (state->speculative && insn_aux->nospec) 17456 goto process_bpf_exit; 17457 17458 err = do_check_insn(env, &do_print_state); 17459 if (error_recoverable_with_nospec(err) && state->speculative) { 17460 /* Prevent this speculative path from ever reaching the 17461 * insn that would have been unsafe to execute. 17462 */ 17463 insn_aux->nospec = true; 17464 /* If it was an ADD/SUB insn, potentially remove any 17465 * markings for alu sanitization. 17466 */ 17467 insn_aux->alu_state = 0; 17468 goto process_bpf_exit; 17469 } else if (err < 0) { 17470 return err; 17471 } else if (err == PROCESS_BPF_EXIT) { 17472 goto process_bpf_exit; 17473 } else if (err == INSN_IDX_UPDATED) { 17474 } else if (err == 0) { 17475 env->insn_idx++; 17476 } 17477 17478 if (state->speculative && insn_aux->nospec_result) { 17479 /* If we are on a path that performed a jump-op, this 17480 * may skip a nospec patched-in after the jump. This can 17481 * currently never happen because nospec_result is only 17482 * used for the write-ops 17483 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper 17484 * calls. These must never skip the following insn 17485 * (i.e., bpf_insn_successors()'s opcode_info.can_jump 17486 * is false). Still, add a warning to document this in 17487 * case nospec_result is used elsewhere in the future. 17488 * 17489 * All non-branch instructions have a single 17490 * fall-through edge. For these, nospec_result should 17491 * already work. 17492 */ 17493 if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP || 17494 BPF_CLASS(insn->code) == BPF_JMP32) && 17495 BPF_OP(insn->code) != BPF_CALL, env, 17496 "speculation barrier after jump instruction may not have the desired effect")) 17497 return -EFAULT; 17498 process_bpf_exit: 17499 mark_verifier_state_scratched(env); 17500 err = bpf_update_branch_counts(env, env->cur_state); 17501 if (err) 17502 return err; 17503 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 17504 pop_log); 17505 if (err < 0) { 17506 if (err != -ENOENT) 17507 return err; 17508 break; 17509 } else { 17510 do_print_state = true; 17511 continue; 17512 } 17513 } 17514 } 17515 17516 return 0; 17517 } 17518 17519 static int find_btf_percpu_datasec(struct btf *btf) 17520 { 17521 const struct btf_type *t; 17522 const char *tname; 17523 int i, n; 17524 17525 /* 17526 * Both vmlinux and module each have their own ".data..percpu" 17527 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17528 * types to look at only module's own BTF types. 17529 */ 17530 n = btf_nr_types(btf); 17531 for (i = btf_named_start_id(btf, true); i < n; i++) { 17532 t = btf_type_by_id(btf, i); 17533 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17534 continue; 17535 17536 tname = btf_name_by_offset(btf, t->name_off); 17537 if (!strcmp(tname, ".data..percpu")) 17538 return i; 17539 } 17540 17541 return -ENOENT; 17542 } 17543 17544 /* 17545 * Add btf to the env->used_btfs array. If needed, refcount the 17546 * corresponding kernel module. To simplify caller's logic 17547 * in case of error or if btf was added before the function 17548 * decreases the btf refcount. 17549 */ 17550 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 17551 { 17552 struct btf_mod_pair *btf_mod; 17553 int ret = 0; 17554 int i; 17555 17556 /* check whether we recorded this BTF (and maybe module) already */ 17557 for (i = 0; i < env->used_btf_cnt; i++) 17558 if (env->used_btfs[i].btf == btf) 17559 goto ret_put; 17560 17561 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17562 verbose(env, "The total number of btfs per program has reached the limit of %u\n", 17563 MAX_USED_BTFS); 17564 ret = -E2BIG; 17565 goto ret_put; 17566 } 17567 17568 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17569 btf_mod->btf = btf; 17570 btf_mod->module = NULL; 17571 17572 /* if we reference variables from kernel module, bump its refcount */ 17573 if (btf_is_module(btf)) { 17574 btf_mod->module = btf_try_get_module(btf); 17575 if (!btf_mod->module) { 17576 ret = -ENXIO; 17577 goto ret_put; 17578 } 17579 } 17580 17581 env->used_btf_cnt++; 17582 return 0; 17583 17584 ret_put: 17585 /* Either error or this BTF was already added */ 17586 btf_put(btf); 17587 return ret; 17588 } 17589 17590 /* replace pseudo btf_id with kernel symbol address */ 17591 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 17592 struct bpf_insn *insn, 17593 struct bpf_insn_aux_data *aux, 17594 struct btf *btf) 17595 { 17596 const struct btf_var_secinfo *vsi; 17597 const struct btf_type *datasec; 17598 const struct btf_type *t; 17599 const char *sym_name; 17600 bool percpu = false; 17601 u32 type, id = insn->imm; 17602 s32 datasec_id; 17603 u64 addr; 17604 int i; 17605 17606 t = btf_type_by_id(btf, id); 17607 if (!t) { 17608 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17609 return -ENOENT; 17610 } 17611 17612 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17613 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17614 return -EINVAL; 17615 } 17616 17617 sym_name = btf_name_by_offset(btf, t->name_off); 17618 addr = kallsyms_lookup_name(sym_name); 17619 if (!addr) { 17620 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17621 sym_name); 17622 return -ENOENT; 17623 } 17624 insn[0].imm = (u32)addr; 17625 insn[1].imm = addr >> 32; 17626 17627 if (btf_type_is_func(t)) { 17628 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17629 aux->btf_var.mem_size = 0; 17630 return 0; 17631 } 17632 17633 datasec_id = find_btf_percpu_datasec(btf); 17634 if (datasec_id > 0) { 17635 datasec = btf_type_by_id(btf, datasec_id); 17636 for_each_vsi(i, datasec, vsi) { 17637 if (vsi->type == id) { 17638 percpu = true; 17639 break; 17640 } 17641 } 17642 } 17643 17644 type = t->type; 17645 t = btf_type_skip_modifiers(btf, type, NULL); 17646 if (percpu) { 17647 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17648 aux->btf_var.btf = btf; 17649 aux->btf_var.btf_id = type; 17650 } else if (!btf_type_is_struct(t)) { 17651 const struct btf_type *ret; 17652 const char *tname; 17653 u32 tsize; 17654 17655 /* resolve the type size of ksym. */ 17656 ret = btf_resolve_size(btf, t, &tsize); 17657 if (IS_ERR(ret)) { 17658 tname = btf_name_by_offset(btf, t->name_off); 17659 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17660 tname, PTR_ERR(ret)); 17661 return -EINVAL; 17662 } 17663 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17664 aux->btf_var.mem_size = tsize; 17665 } else { 17666 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17667 aux->btf_var.btf = btf; 17668 aux->btf_var.btf_id = type; 17669 } 17670 17671 return 0; 17672 } 17673 17674 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17675 struct bpf_insn *insn, 17676 struct bpf_insn_aux_data *aux) 17677 { 17678 struct btf *btf; 17679 int btf_fd; 17680 int err; 17681 17682 btf_fd = insn[1].imm; 17683 if (btf_fd) { 17684 btf = btf_get_by_fd(btf_fd); 17685 if (IS_ERR(btf)) { 17686 verbose(env, "invalid module BTF object FD specified.\n"); 17687 return -EINVAL; 17688 } 17689 } else { 17690 if (!btf_vmlinux) { 17691 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17692 return -EINVAL; 17693 } 17694 btf_get(btf_vmlinux); 17695 btf = btf_vmlinux; 17696 } 17697 17698 err = __check_pseudo_btf_id(env, insn, aux, btf); 17699 if (err) { 17700 btf_put(btf); 17701 return err; 17702 } 17703 17704 return __add_used_btf(env, btf); 17705 } 17706 17707 static bool is_tracing_prog_type(enum bpf_prog_type type) 17708 { 17709 switch (type) { 17710 case BPF_PROG_TYPE_KPROBE: 17711 case BPF_PROG_TYPE_TRACEPOINT: 17712 case BPF_PROG_TYPE_PERF_EVENT: 17713 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17714 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17715 return true; 17716 default: 17717 return false; 17718 } 17719 } 17720 17721 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17722 { 17723 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17724 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17725 } 17726 17727 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17728 struct bpf_map *map, 17729 struct bpf_prog *prog) 17730 17731 { 17732 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17733 17734 if (map->excl_prog_sha && 17735 memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) { 17736 verbose(env, "program's hash doesn't match map's excl_prog_hash\n"); 17737 return -EACCES; 17738 } 17739 17740 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17741 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17742 if (is_tracing_prog_type(prog_type)) { 17743 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17744 return -EINVAL; 17745 } 17746 } 17747 17748 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 17749 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17750 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17751 return -EINVAL; 17752 } 17753 17754 if (is_tracing_prog_type(prog_type)) { 17755 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17756 return -EINVAL; 17757 } 17758 } 17759 17760 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17761 !bpf_offload_prog_map_match(prog, map)) { 17762 verbose(env, "offload device mismatch between prog and map\n"); 17763 return -EINVAL; 17764 } 17765 17766 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17767 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17768 return -EINVAL; 17769 } 17770 17771 if (prog->sleepable) 17772 switch (map->map_type) { 17773 case BPF_MAP_TYPE_HASH: 17774 case BPF_MAP_TYPE_RHASH: 17775 case BPF_MAP_TYPE_LRU_HASH: 17776 case BPF_MAP_TYPE_ARRAY: 17777 case BPF_MAP_TYPE_PERCPU_HASH: 17778 case BPF_MAP_TYPE_PERCPU_ARRAY: 17779 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17780 case BPF_MAP_TYPE_LPM_TRIE: 17781 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17782 case BPF_MAP_TYPE_HASH_OF_MAPS: 17783 case BPF_MAP_TYPE_RINGBUF: 17784 case BPF_MAP_TYPE_USER_RINGBUF: 17785 case BPF_MAP_TYPE_INODE_STORAGE: 17786 case BPF_MAP_TYPE_SK_STORAGE: 17787 case BPF_MAP_TYPE_TASK_STORAGE: 17788 case BPF_MAP_TYPE_CGRP_STORAGE: 17789 case BPF_MAP_TYPE_QUEUE: 17790 case BPF_MAP_TYPE_STACK: 17791 case BPF_MAP_TYPE_ARENA: 17792 case BPF_MAP_TYPE_INSN_ARRAY: 17793 case BPF_MAP_TYPE_PROG_ARRAY: 17794 break; 17795 default: 17796 verbose(env, 17797 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17798 return -EINVAL; 17799 } 17800 17801 if (bpf_map_is_cgroup_storage(map) && 17802 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17803 verbose(env, "only one cgroup storage of each type is allowed\n"); 17804 return -EBUSY; 17805 } 17806 17807 if (map->map_type == BPF_MAP_TYPE_ARENA) { 17808 if (env->prog->aux->arena) { 17809 verbose(env, "Only one arena per program\n"); 17810 return -EBUSY; 17811 } 17812 if (!env->allow_ptr_leaks || !env->bpf_capable) { 17813 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 17814 return -EPERM; 17815 } 17816 if (!env->prog->jit_requested) { 17817 verbose(env, "JIT is required to use arena\n"); 17818 return -EOPNOTSUPP; 17819 } 17820 if (!bpf_jit_supports_arena()) { 17821 verbose(env, "JIT doesn't support arena\n"); 17822 return -EOPNOTSUPP; 17823 } 17824 env->prog->aux->arena = (void *)map; 17825 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 17826 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 17827 return -EINVAL; 17828 } 17829 } 17830 17831 return 0; 17832 } 17833 17834 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 17835 { 17836 int i, err; 17837 17838 /* check whether we recorded this map already */ 17839 for (i = 0; i < env->used_map_cnt; i++) 17840 if (env->used_maps[i] == map) 17841 return i; 17842 17843 if (env->used_map_cnt >= MAX_USED_MAPS) { 17844 verbose(env, "The total number of maps per program has reached the limit of %u\n", 17845 MAX_USED_MAPS); 17846 return -E2BIG; 17847 } 17848 17849 err = check_map_prog_compatibility(env, map, env->prog); 17850 if (err) 17851 return err; 17852 17853 if (env->prog->sleepable) 17854 atomic64_inc(&map->sleepable_refcnt); 17855 17856 /* hold the map. If the program is rejected by verifier, 17857 * the map will be released by release_maps() or it 17858 * will be used by the valid program until it's unloaded 17859 * and all maps are released in bpf_free_used_maps() 17860 */ 17861 bpf_map_inc(map); 17862 17863 env->used_maps[env->used_map_cnt++] = map; 17864 17865 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 17866 err = bpf_insn_array_init(map, env->prog); 17867 if (err) { 17868 verbose(env, "Failed to properly initialize insn array\n"); 17869 return err; 17870 } 17871 env->insn_array_maps[env->insn_array_map_cnt++] = map; 17872 } 17873 17874 return env->used_map_cnt - 1; 17875 } 17876 17877 /* Add map behind fd to used maps list, if it's not already there, and return 17878 * its index. 17879 * Returns <0 on error, or >= 0 index, on success. 17880 */ 17881 static int add_used_map(struct bpf_verifier_env *env, int fd) 17882 { 17883 struct bpf_map *map; 17884 CLASS(fd, f)(fd); 17885 17886 map = __bpf_map_get(f); 17887 if (IS_ERR(map)) { 17888 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 17889 return PTR_ERR(map); 17890 } 17891 17892 return __add_used_map(env, map); 17893 } 17894 17895 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17896 { 17897 u8 class = BPF_CLASS(insn->code); 17898 u8 opcode = BPF_OP(insn->code); 17899 17900 switch (opcode) { 17901 case BPF_NEG: 17902 if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 || 17903 insn->off != 0 || insn->imm != 0) { 17904 verbose(env, "BPF_NEG uses reserved fields\n"); 17905 return -EINVAL; 17906 } 17907 return 0; 17908 case BPF_END: 17909 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 17910 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 17911 (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) { 17912 verbose(env, "BPF_END uses reserved fields\n"); 17913 return -EINVAL; 17914 } 17915 return 0; 17916 case BPF_MOV: 17917 if (BPF_SRC(insn->code) == BPF_X) { 17918 if (class == BPF_ALU) { 17919 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 17920 insn->imm) { 17921 verbose(env, "BPF_MOV uses reserved fields\n"); 17922 return -EINVAL; 17923 } 17924 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 17925 if (insn->imm != 1 && insn->imm != 1u << 16) { 17926 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 17927 return -EINVAL; 17928 } 17929 } else if ((insn->off != 0 && insn->off != 8 && 17930 insn->off != 16 && insn->off != 32) || insn->imm) { 17931 verbose(env, "BPF_MOV uses reserved fields\n"); 17932 return -EINVAL; 17933 } 17934 } else if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 17935 verbose(env, "BPF_MOV uses reserved fields\n"); 17936 return -EINVAL; 17937 } 17938 return 0; 17939 case BPF_ADD: 17940 case BPF_SUB: 17941 case BPF_AND: 17942 case BPF_OR: 17943 case BPF_XOR: 17944 case BPF_LSH: 17945 case BPF_RSH: 17946 case BPF_ARSH: 17947 case BPF_MUL: 17948 case BPF_DIV: 17949 case BPF_MOD: 17950 if (BPF_SRC(insn->code) == BPF_X) { 17951 if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) || 17952 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 17953 verbose(env, "BPF_ALU uses reserved fields\n"); 17954 return -EINVAL; 17955 } 17956 } else if (insn->src_reg != BPF_REG_0 || 17957 (insn->off != 0 && insn->off != 1) || 17958 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 17959 verbose(env, "BPF_ALU uses reserved fields\n"); 17960 return -EINVAL; 17961 } 17962 return 0; 17963 default: 17964 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 17965 return -EINVAL; 17966 } 17967 } 17968 17969 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17970 { 17971 u8 class = BPF_CLASS(insn->code); 17972 u8 opcode = BPF_OP(insn->code); 17973 17974 switch (opcode) { 17975 case BPF_CALL: 17976 if (BPF_SRC(insn->code) != BPF_K || 17977 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) || 17978 (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL && 17979 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17980 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 17981 verbose(env, "BPF_CALL uses reserved fields\n"); 17982 return -EINVAL; 17983 } 17984 return 0; 17985 case BPF_JA: 17986 if (BPF_SRC(insn->code) == BPF_X) { 17987 if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) { 17988 verbose(env, "BPF_JA|BPF_X uses reserved fields\n"); 17989 return -EINVAL; 17990 } 17991 } else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 17992 (class == BPF_JMP && insn->imm != 0) || 17993 (class == BPF_JMP32 && insn->off != 0)) { 17994 verbose(env, "BPF_JA uses reserved fields\n"); 17995 return -EINVAL; 17996 } 17997 return 0; 17998 case BPF_EXIT: 17999 if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || 18000 insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 18001 class == BPF_JMP32) { 18002 verbose(env, "BPF_EXIT uses reserved fields\n"); 18003 return -EINVAL; 18004 } 18005 return 0; 18006 case BPF_JCOND: 18007 if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO || 18008 insn->dst_reg || insn->imm) { 18009 verbose(env, "invalid may_goto imm %d\n", insn->imm); 18010 return -EINVAL; 18011 } 18012 return 0; 18013 default: 18014 if (BPF_SRC(insn->code) == BPF_X) { 18015 if (insn->imm != 0) { 18016 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18017 return -EINVAL; 18018 } 18019 } else if (insn->src_reg != BPF_REG_0) { 18020 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18021 return -EINVAL; 18022 } 18023 return 0; 18024 } 18025 } 18026 18027 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 18028 { 18029 switch (BPF_CLASS(insn->code)) { 18030 case BPF_ALU: 18031 case BPF_ALU64: 18032 return check_alu_fields(env, insn); 18033 case BPF_LDX: 18034 if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18035 insn->imm != 0) { 18036 verbose(env, "BPF_LDX uses reserved fields\n"); 18037 return -EINVAL; 18038 } 18039 return 0; 18040 case BPF_STX: 18041 if (BPF_MODE(insn->code) == BPF_ATOMIC) 18042 return 0; 18043 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 18044 verbose(env, "BPF_STX uses reserved fields\n"); 18045 return -EINVAL; 18046 } 18047 return 0; 18048 case BPF_ST: 18049 if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { 18050 verbose(env, "BPF_ST uses reserved fields\n"); 18051 return -EINVAL; 18052 } 18053 return 0; 18054 case BPF_JMP: 18055 case BPF_JMP32: 18056 return check_jmp_fields(env, insn); 18057 case BPF_LD: { 18058 u8 mode = BPF_MODE(insn->code); 18059 18060 if (mode == BPF_ABS || mode == BPF_IND) { 18061 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 18062 BPF_SIZE(insn->code) == BPF_DW || 18063 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 18064 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 18065 return -EINVAL; 18066 } 18067 } else if (mode != BPF_IMM) { 18068 verbose(env, "invalid BPF_LD mode\n"); 18069 return -EINVAL; 18070 } 18071 return 0; 18072 } 18073 default: 18074 verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code)); 18075 return -EINVAL; 18076 } 18077 } 18078 18079 /* 18080 * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions: 18081 * 18082 * 1. if it accesses map FD, replace it with actual map pointer. 18083 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18084 * 18085 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18086 */ 18087 static int check_and_resolve_insns(struct bpf_verifier_env *env) 18088 { 18089 struct bpf_insn *insn = env->prog->insnsi; 18090 int insn_cnt = env->prog->len; 18091 int i, err; 18092 18093 err = bpf_prog_calc_tag(env->prog); 18094 if (err) 18095 return err; 18096 18097 for (i = 0; i < insn_cnt; i++, insn++) { 18098 if (insn->dst_reg >= MAX_BPF_REG && 18099 !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) { 18100 verbose(env, "R%d is invalid\n", insn->dst_reg); 18101 return -EINVAL; 18102 } 18103 if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) { 18104 verbose(env, "R%d is invalid\n", insn->src_reg); 18105 return -EINVAL; 18106 } 18107 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18108 struct bpf_insn_aux_data *aux; 18109 struct bpf_map *map; 18110 int map_idx; 18111 u64 addr; 18112 u32 fd; 18113 18114 if (i == insn_cnt - 1 || insn[1].code != 0 || 18115 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18116 insn[1].off != 0) { 18117 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18118 return -EINVAL; 18119 } 18120 18121 if (insn[0].off != 0) { 18122 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 18123 return -EINVAL; 18124 } 18125 18126 if (insn[0].src_reg == 0) 18127 /* valid generic load 64-bit imm */ 18128 goto next_insn; 18129 18130 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18131 aux = &env->insn_aux_data[i]; 18132 err = check_pseudo_btf_id(env, insn, aux); 18133 if (err) 18134 return err; 18135 goto next_insn; 18136 } 18137 18138 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18139 aux = &env->insn_aux_data[i]; 18140 aux->ptr_type = PTR_TO_FUNC; 18141 goto next_insn; 18142 } 18143 18144 /* In final convert_pseudo_ld_imm64() step, this is 18145 * converted into regular 64-bit imm load insn. 18146 */ 18147 switch (insn[0].src_reg) { 18148 case BPF_PSEUDO_MAP_VALUE: 18149 case BPF_PSEUDO_MAP_IDX_VALUE: 18150 break; 18151 case BPF_PSEUDO_MAP_FD: 18152 case BPF_PSEUDO_MAP_IDX: 18153 if (insn[1].imm == 0) 18154 break; 18155 fallthrough; 18156 default: 18157 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18158 return -EINVAL; 18159 } 18160 18161 switch (insn[0].src_reg) { 18162 case BPF_PSEUDO_MAP_IDX_VALUE: 18163 case BPF_PSEUDO_MAP_IDX: 18164 if (bpfptr_is_null(env->fd_array)) { 18165 verbose(env, "fd_idx without fd_array is invalid\n"); 18166 return -EPROTO; 18167 } 18168 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18169 insn[0].imm * sizeof(fd), 18170 sizeof(fd))) 18171 return -EFAULT; 18172 break; 18173 default: 18174 fd = insn[0].imm; 18175 break; 18176 } 18177 18178 map_idx = add_used_map(env, fd); 18179 if (map_idx < 0) 18180 return map_idx; 18181 map = env->used_maps[map_idx]; 18182 18183 aux = &env->insn_aux_data[i]; 18184 aux->map_index = map_idx; 18185 18186 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18187 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18188 addr = (unsigned long)map; 18189 } else { 18190 u32 off = insn[1].imm; 18191 18192 if (!map->ops->map_direct_value_addr) { 18193 verbose(env, "no direct value access support for this map type\n"); 18194 return -EINVAL; 18195 } 18196 18197 err = map->ops->map_direct_value_addr(map, &addr, off); 18198 if (err) { 18199 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18200 map->value_size, off); 18201 return err; 18202 } 18203 18204 aux->map_off = off; 18205 addr += off; 18206 } 18207 18208 insn[0].imm = (u32)addr; 18209 insn[1].imm = addr >> 32; 18210 18211 next_insn: 18212 insn++; 18213 i++; 18214 continue; 18215 } 18216 18217 /* Basic sanity check before we invest more work here. */ 18218 if (!bpf_opcode_in_insntable(insn->code)) { 18219 verbose(env, "unknown opcode %02x\n", insn->code); 18220 return -EINVAL; 18221 } 18222 18223 err = check_insn_fields(env, insn); 18224 if (err) 18225 return err; 18226 } 18227 18228 /* now all pseudo BPF_LD_IMM64 instructions load valid 18229 * 'struct bpf_map *' into a register instead of user map_fd. 18230 * These pointers will be used later by verifier to validate map access. 18231 */ 18232 return 0; 18233 } 18234 18235 /* drop refcnt of maps used by the rejected program */ 18236 static void release_maps(struct bpf_verifier_env *env) 18237 { 18238 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18239 env->used_map_cnt); 18240 } 18241 18242 /* drop refcnt of maps used by the rejected program */ 18243 static void release_btfs(struct bpf_verifier_env *env) 18244 { 18245 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 18246 } 18247 18248 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18249 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18250 { 18251 struct bpf_insn *insn = env->prog->insnsi; 18252 int insn_cnt = env->prog->len; 18253 int i; 18254 18255 for (i = 0; i < insn_cnt; i++, insn++) { 18256 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18257 continue; 18258 if (insn->src_reg == BPF_PSEUDO_FUNC) 18259 continue; 18260 insn->src_reg = 0; 18261 } 18262 } 18263 18264 static void release_insn_arrays(struct bpf_verifier_env *env) 18265 { 18266 int i; 18267 18268 for (i = 0; i < env->insn_array_map_cnt; i++) 18269 bpf_insn_array_release(env->insn_array_maps[i]); 18270 } 18271 18272 18273 18274 /* The verifier does more data flow analysis than llvm and will not 18275 * explore branches that are dead at run time. Malicious programs can 18276 * have dead code too. Therefore replace all dead at-run-time code 18277 * with 'ja -1'. 18278 * 18279 * Just nops are not optimal, e.g. if they would sit at the end of the 18280 * program and through another bug we would manage to jump there, then 18281 * we'd execute beyond program memory otherwise. Returning exception 18282 * code also wouldn't work since we can have subprogs where the dead 18283 * code could be located. 18284 */ 18285 static void sanitize_dead_code(struct bpf_verifier_env *env) 18286 { 18287 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18288 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18289 struct bpf_insn *insn = env->prog->insnsi; 18290 const int insn_cnt = env->prog->len; 18291 int i; 18292 18293 for (i = 0; i < insn_cnt; i++) { 18294 if (aux_data[i].seen) 18295 continue; 18296 memcpy(insn + i, &trap, sizeof(trap)); 18297 aux_data[i].zext_dst = false; 18298 } 18299 } 18300 18301 18302 18303 static void free_states(struct bpf_verifier_env *env) 18304 { 18305 struct bpf_verifier_state_list *sl; 18306 struct list_head *head, *pos, *tmp; 18307 struct bpf_scc_info *info; 18308 int i, j; 18309 18310 bpf_free_verifier_state(env->cur_state, true); 18311 env->cur_state = NULL; 18312 while (!pop_stack(env, NULL, NULL, false)); 18313 18314 list_for_each_safe(pos, tmp, &env->free_list) { 18315 sl = container_of(pos, struct bpf_verifier_state_list, node); 18316 bpf_free_verifier_state(&sl->state, false); 18317 kfree(sl); 18318 } 18319 INIT_LIST_HEAD(&env->free_list); 18320 18321 for (i = 0; i < env->scc_cnt; ++i) { 18322 info = env->scc_info[i]; 18323 if (!info) 18324 continue; 18325 for (j = 0; j < info->num_visits; j++) 18326 bpf_free_backedges(&info->visits[j]); 18327 kvfree(info); 18328 env->scc_info[i] = NULL; 18329 } 18330 18331 if (!env->explored_states) 18332 return; 18333 18334 for (i = 0; i < state_htab_size(env); i++) { 18335 head = &env->explored_states[i]; 18336 18337 list_for_each_safe(pos, tmp, head) { 18338 sl = container_of(pos, struct bpf_verifier_state_list, node); 18339 bpf_free_verifier_state(&sl->state, false); 18340 kfree(sl); 18341 } 18342 INIT_LIST_HEAD(&env->explored_states[i]); 18343 } 18344 } 18345 18346 static int do_check_common(struct bpf_verifier_env *env, int subprog) 18347 { 18348 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18349 struct bpf_subprog_info *sub = subprog_info(env, subprog); 18350 struct bpf_prog_aux *aux = env->prog->aux; 18351 struct bpf_verifier_state *state; 18352 struct bpf_reg_state *regs; 18353 int ret, i; 18354 18355 env->prev_linfo = NULL; 18356 env->pass_cnt++; 18357 18358 state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT); 18359 if (!state) 18360 return -ENOMEM; 18361 state->curframe = 0; 18362 state->speculative = false; 18363 state->branches = 1; 18364 state->in_sleepable = env->prog->sleepable; 18365 state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT); 18366 if (!state->frame[0]) { 18367 kfree(state); 18368 return -ENOMEM; 18369 } 18370 env->cur_state = state; 18371 init_func_state(env, state->frame[0], 18372 BPF_MAIN_FUNC /* callsite */, 18373 0 /* frameno */, 18374 subprog); 18375 state->first_insn_idx = env->subprog_info[subprog].start; 18376 state->last_insn_idx = -1; 18377 18378 regs = state->frame[state->curframe]->regs; 18379 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 18380 const char *sub_name = subprog_name(env, subprog); 18381 struct bpf_subprog_arg_info *arg; 18382 struct bpf_reg_state *reg; 18383 18384 if (env->log.level & BPF_LOG_LEVEL) 18385 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 18386 ret = btf_prepare_func_args(env, subprog); 18387 if (ret) 18388 goto out; 18389 18390 if (subprog_is_exc_cb(env, subprog)) { 18391 state->frame[0]->in_exception_callback_fn = true; 18392 18393 /* 18394 * Global functions are scalar or void, make sure 18395 * we return a scalar. 18396 */ 18397 if (subprog_returns_void(env, subprog)) { 18398 verbose(env, "exception cb cannot return void\n"); 18399 ret = -EINVAL; 18400 goto out; 18401 } 18402 18403 /* Also ensure the callback only has a single scalar argument. */ 18404 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 18405 verbose(env, "exception cb only supports single integer argument\n"); 18406 ret = -EINVAL; 18407 goto out; 18408 } 18409 } 18410 for (i = BPF_REG_1; i <= min_t(u32, sub->arg_cnt, MAX_BPF_FUNC_REG_ARGS); i++) { 18411 arg = &sub->args[i - BPF_REG_1]; 18412 reg = ®s[i]; 18413 18414 if (arg->arg_type == ARG_PTR_TO_CTX) { 18415 reg->type = PTR_TO_CTX; 18416 mark_reg_known_zero(env, regs, i); 18417 } else if (arg->arg_type == ARG_ANYTHING) { 18418 reg->type = SCALAR_VALUE; 18419 mark_reg_unknown(env, regs, i); 18420 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 18421 /* assume unspecial LOCAL dynptr type */ 18422 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen, 0); 18423 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 18424 reg->type = PTR_TO_MEM; 18425 reg->type |= arg->arg_type & 18426 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 18427 mark_reg_known_zero(env, regs, i); 18428 reg->mem_size = arg->mem_size; 18429 if (arg->arg_type & PTR_MAYBE_NULL) 18430 reg->id = ++env->id_gen; 18431 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 18432 reg->type = PTR_TO_BTF_ID; 18433 if (arg->arg_type & PTR_MAYBE_NULL) 18434 reg->type |= PTR_MAYBE_NULL; 18435 if (arg->arg_type & PTR_UNTRUSTED) 18436 reg->type |= PTR_UNTRUSTED; 18437 if (arg->arg_type & PTR_TRUSTED) 18438 reg->type |= PTR_TRUSTED; 18439 mark_reg_known_zero(env, regs, i); 18440 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 18441 reg->btf_id = arg->btf_id; 18442 reg->id = ++env->id_gen; 18443 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 18444 /* caller can pass either PTR_TO_ARENA or SCALAR */ 18445 mark_reg_unknown(env, regs, i); 18446 } else { 18447 verifier_bug(env, "unhandled arg#%d type %d", 18448 i - BPF_REG_1 + 1, arg->arg_type); 18449 ret = -EFAULT; 18450 goto out; 18451 } 18452 } 18453 if (env->prog->type == BPF_PROG_TYPE_EXT && sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS) { 18454 verbose(env, "freplace programs with >%d args not supported yet\n", 18455 MAX_BPF_FUNC_REG_ARGS); 18456 ret = -EINVAL; 18457 goto out; 18458 } 18459 } else { 18460 /* if main BPF program has associated BTF info, validate that 18461 * it's matching expected signature, and otherwise mark BTF 18462 * info for main program as unreliable 18463 */ 18464 if (env->prog->aux->func_info_aux) { 18465 ret = btf_prepare_func_args(env, 0); 18466 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) { 18467 env->prog->aux->func_info_aux[0].unreliable = true; 18468 sub->arg_cnt = 1; 18469 sub->stack_arg_cnt = 0; 18470 } 18471 } 18472 18473 /* 1st arg to a function */ 18474 regs[BPF_REG_1].type = PTR_TO_CTX; 18475 mark_reg_known_zero(env, regs, BPF_REG_1); 18476 } 18477 18478 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 18479 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 18480 for (i = 0; i < aux->ctx_arg_info_size; i++) { 18481 ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0; 18482 if (ret < 0) 18483 goto out; 18484 18485 aux->ctx_arg_info[i].ref_id = ret; 18486 } 18487 } 18488 18489 ret = do_check(env); 18490 out: 18491 if (!ret && pop_log) 18492 bpf_vlog_reset(&env->log, 0); 18493 free_states(env); 18494 return ret; 18495 } 18496 18497 /* Lazily verify all global functions based on their BTF, if they are called 18498 * from main BPF program or any of subprograms transitively. 18499 * BPF global subprogs called from dead code are not validated. 18500 * All callable global functions must pass verification. 18501 * Otherwise the whole program is rejected. 18502 * Consider: 18503 * int bar(int); 18504 * int foo(int f) 18505 * { 18506 * return bar(f); 18507 * } 18508 * int bar(int b) 18509 * { 18510 * ... 18511 * } 18512 * foo() will be verified first for R1=any_scalar_value. During verification it 18513 * will be assumed that bar() already verified successfully and call to bar() 18514 * from foo() will be checked for type match only. Later bar() will be verified 18515 * independently to check that it's safe for R1=any_scalar_value. 18516 */ 18517 static int do_check_subprogs(struct bpf_verifier_env *env) 18518 { 18519 struct bpf_prog_aux *aux = env->prog->aux; 18520 struct bpf_func_info_aux *sub_aux; 18521 int i, ret, new_cnt; 18522 u32 insn_processed; 18523 18524 if (!aux->func_info) 18525 return 0; 18526 18527 /* exception callback is presumed to be always called */ 18528 if (env->exception_callback_subprog) 18529 subprog_aux(env, env->exception_callback_subprog)->called = true; 18530 18531 again: 18532 new_cnt = 0; 18533 for (i = 1; i < env->subprog_cnt; i++) { 18534 if (!bpf_subprog_is_global(env, i)) 18535 continue; 18536 18537 insn_processed = env->insn_processed; 18538 18539 sub_aux = subprog_aux(env, i); 18540 if (!sub_aux->called || sub_aux->verified) 18541 continue; 18542 18543 env->insn_idx = env->subprog_info[i].start; 18544 WARN_ON_ONCE(env->insn_idx == 0); 18545 ret = do_check_common(env, i); 18546 env->subprog_info[i].insn_processed = env->insn_processed - insn_processed; 18547 if (ret) { 18548 return ret; 18549 } else if (env->log.level & BPF_LOG_LEVEL) { 18550 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 18551 i, subprog_name(env, i)); 18552 } 18553 18554 /* We verified new global subprog, it might have called some 18555 * more global subprogs that we haven't verified yet, so we 18556 * need to do another pass over subprogs to verify those. 18557 */ 18558 sub_aux->verified = true; 18559 new_cnt++; 18560 } 18561 18562 /* We can't loop forever as we verify at least one global subprog on 18563 * each pass. 18564 */ 18565 if (new_cnt) 18566 goto again; 18567 18568 return 0; 18569 } 18570 18571 static int do_check_main(struct bpf_verifier_env *env) 18572 { 18573 u32 insn_processed = env->insn_processed; 18574 int ret; 18575 18576 env->insn_idx = 0; 18577 ret = do_check_common(env, 0); 18578 env->subprog_info[0].insn_processed = env->insn_processed - insn_processed; 18579 if (!ret) 18580 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18581 return ret; 18582 } 18583 18584 18585 static void print_verification_stats(struct bpf_verifier_env *env) 18586 { 18587 /* Skip over hidden subprogs which are not verified. */ 18588 int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18589 18590 if (env->log.level & BPF_LOG_STATS) { 18591 verbose(env, "verification time %lld usec\n", 18592 div_u64(env->verification_time, 1000)); 18593 verbose(env, "stack depth %d", env->subprog_info[0].stack_depth); 18594 for (i = 1; i < subprog_cnt; i++) 18595 verbose(env, "+%d", env->subprog_info[i].stack_depth); 18596 verbose(env, " max %d\n", env->max_stack_depth); 18597 verbose(env, "insns processed %d", env->subprog_info[0].insn_processed); 18598 for (i = 1; i < subprog_cnt; i++) 18599 if (bpf_subprog_is_global(env, i)) 18600 verbose(env, "+%d", env->subprog_info[i].insn_processed); 18601 verbose(env, "\n"); 18602 } 18603 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 18604 "total_states %d peak_states %d mark_read %d\n", 18605 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 18606 env->max_states_per_insn, env->total_states, 18607 env->peak_states, env->longest_mark_read_walk); 18608 } 18609 18610 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 18611 const struct bpf_ctx_arg_aux *info, u32 cnt) 18612 { 18613 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 18614 prog->aux->ctx_arg_info_size = cnt; 18615 18616 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 18617 } 18618 18619 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 18620 { 18621 const struct btf_type *t, *func_proto; 18622 const struct bpf_struct_ops_desc *st_ops_desc; 18623 const struct bpf_struct_ops *st_ops; 18624 const struct btf_member *member; 18625 struct bpf_prog *prog = env->prog; 18626 bool has_refcounted_arg = false; 18627 u32 btf_id, member_idx, member_off; 18628 struct btf *btf; 18629 const char *mname; 18630 int i, err; 18631 18632 if (!prog->gpl_compatible) { 18633 verbose(env, "struct ops programs must have a GPL compatible license\n"); 18634 return -EINVAL; 18635 } 18636 18637 if (!prog->aux->attach_btf_id) 18638 return -ENOTSUPP; 18639 18640 btf = prog->aux->attach_btf; 18641 if (btf_is_module(btf)) { 18642 /* Make sure st_ops is valid through the lifetime of env */ 18643 env->attach_btf_mod = btf_try_get_module(btf); 18644 if (!env->attach_btf_mod) { 18645 verbose(env, "struct_ops module %s is not found\n", 18646 btf_get_name(btf)); 18647 return -ENOTSUPP; 18648 } 18649 } 18650 18651 btf_id = prog->aux->attach_btf_id; 18652 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 18653 if (!st_ops_desc) { 18654 verbose(env, "attach_btf_id %u is not a supported struct\n", 18655 btf_id); 18656 return -ENOTSUPP; 18657 } 18658 st_ops = st_ops_desc->st_ops; 18659 18660 t = st_ops_desc->type; 18661 member_idx = prog->expected_attach_type; 18662 if (member_idx >= btf_type_vlen(t)) { 18663 verbose(env, "attach to invalid member idx %u of struct %s\n", 18664 member_idx, st_ops->name); 18665 return -EINVAL; 18666 } 18667 18668 member = &btf_type_member(t)[member_idx]; 18669 mname = btf_name_by_offset(btf, member->name_off); 18670 func_proto = btf_type_resolve_func_ptr(btf, member->type, 18671 NULL); 18672 if (!func_proto) { 18673 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 18674 mname, member_idx, st_ops->name); 18675 return -EINVAL; 18676 } 18677 18678 member_off = __btf_member_bit_offset(t, member) / 8; 18679 err = bpf_struct_ops_supported(st_ops, member_off); 18680 if (err) { 18681 verbose(env, "attach to unsupported member %s of struct %s\n", 18682 mname, st_ops->name); 18683 return err; 18684 } 18685 18686 if (st_ops->check_member) { 18687 err = st_ops->check_member(t, member, prog); 18688 18689 if (err) { 18690 verbose(env, "attach to unsupported member %s of struct %s\n", 18691 mname, st_ops->name); 18692 return err; 18693 } 18694 } 18695 18696 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 18697 verbose(env, "Private stack not supported by jit\n"); 18698 return -EACCES; 18699 } 18700 18701 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) { 18702 if (st_ops_desc->arg_info[member_idx].info[i].refcounted) { 18703 has_refcounted_arg = true; 18704 break; 18705 } 18706 } 18707 18708 /* Tail call is not allowed for programs with refcounted arguments since we 18709 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 18710 */ 18711 for (i = 0; i < env->subprog_cnt; i++) { 18712 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 18713 verbose(env, "program with __ref argument cannot tail call\n"); 18714 return -EINVAL; 18715 } 18716 } 18717 18718 prog->aux->st_ops = st_ops; 18719 prog->aux->attach_st_ops_member_off = member_off; 18720 18721 prog->aux->attach_func_proto = func_proto; 18722 prog->aux->attach_func_name = mname; 18723 env->ops = st_ops->verifier_ops; 18724 18725 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info, 18726 st_ops_desc->arg_info[member_idx].cnt); 18727 } 18728 #define SECURITY_PREFIX "security_" 18729 18730 #ifdef CONFIG_FUNCTION_ERROR_INJECTION 18731 18732 /* list of non-sleepable functions that are otherwise on 18733 * ALLOW_ERROR_INJECTION list 18734 */ 18735 BTF_SET_START(btf_non_sleepable_error_inject) 18736 /* Three functions below can be called from sleepable and non-sleepable context. 18737 * Assume non-sleepable from bpf safety point of view. 18738 */ 18739 BTF_ID(func, __filemap_add_folio) 18740 #ifdef CONFIG_FAIL_PAGE_ALLOC 18741 BTF_ID(func, should_fail_alloc_page) 18742 #endif 18743 #ifdef CONFIG_FAILSLAB 18744 BTF_ID(func, should_failslab) 18745 #endif 18746 BTF_SET_END(btf_non_sleepable_error_inject) 18747 18748 static int check_non_sleepable_error_inject(u32 btf_id) 18749 { 18750 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 18751 } 18752 18753 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18754 { 18755 /* fentry/fexit/fmod_ret progs can be sleepable if they are 18756 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 18757 */ 18758 if (!check_non_sleepable_error_inject(btf_id) && 18759 within_error_injection_list(addr)) 18760 return 0; 18761 18762 return -EINVAL; 18763 } 18764 18765 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18766 { 18767 if (within_error_injection_list(addr) || 18768 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18769 return 0; 18770 18771 return -EINVAL; 18772 } 18773 18774 #else 18775 18776 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code 18777 * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name() 18778 * but that just compares two concrete function names. 18779 */ 18780 static bool has_arch_syscall_prefix(const char *func_name) 18781 { 18782 #if defined(__x86_64__) 18783 return !strncmp(func_name, "__x64_", 6); 18784 #elif defined(__i386__) 18785 return !strncmp(func_name, "__ia32_", 7); 18786 #elif defined(__s390x__) 18787 return !strncmp(func_name, "__s390x_", 8); 18788 #elif defined(__aarch64__) 18789 return !strncmp(func_name, "__arm64_", 8); 18790 #elif defined(__riscv) 18791 return !strncmp(func_name, "__riscv_", 8); 18792 #elif defined(__powerpc__) || defined(__powerpc64__) 18793 return !strncmp(func_name, "sys_", 4); 18794 #elif defined(__loongarch__) 18795 return !strncmp(func_name, "sys_", 4); 18796 #else 18797 return false; 18798 #endif 18799 } 18800 18801 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */ 18802 18803 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18804 { 18805 if (has_arch_syscall_prefix(func_name)) 18806 return 0; 18807 18808 return -EINVAL; 18809 } 18810 18811 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18812 { 18813 if (has_arch_syscall_prefix(func_name) || 18814 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18815 return 0; 18816 18817 return -EINVAL; 18818 } 18819 18820 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */ 18821 18822 static bool is_tracing_multi_id(const struct bpf_prog *prog, u32 btf_id) 18823 { 18824 return is_tracing_multi(prog->expected_attach_type) && bpf_multi_func_btf_id[0] == btf_id; 18825 } 18826 18827 static int btf_id_allow_sleepable(u32 btf_id, unsigned long addr, const struct bpf_prog *prog, 18828 const struct btf *btf) 18829 { 18830 const struct btf_type *t; 18831 const char *tname; 18832 18833 switch (prog->type) { 18834 case BPF_PROG_TYPE_TRACING: 18835 t = btf_type_by_id(btf, btf_id); 18836 if (!t) 18837 return -EINVAL; 18838 tname = btf_name_by_offset(btf, t->name_off); 18839 if (!tname) 18840 return -EINVAL; 18841 18842 /* 18843 * *.multi sleepable programs will pass initial sleepable check, 18844 * the actual attached btf ids are checked later during the link 18845 * attachment. 18846 */ 18847 if (is_tracing_multi_id(prog, btf_id)) 18848 return 0; 18849 if (!check_attach_sleepable(btf_id, addr, tname)) 18850 return 0; 18851 /* 18852 * fentry/fexit/fmod_ret progs can also be sleepable if they are 18853 * in the fmodret id set with the KF_SLEEPABLE flag. 18854 */ 18855 else { 18856 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog); 18857 18858 if (flags && (*flags & KF_SLEEPABLE)) 18859 return 0; 18860 } 18861 break; 18862 case BPF_PROG_TYPE_LSM: 18863 /* 18864 * LSM progs check that they are attached to bpf_lsm_*() funcs. 18865 * Only some of them are sleepable. 18866 */ 18867 if (bpf_lsm_is_sleepable_hook(btf_id)) 18868 return 0; 18869 break; 18870 default: 18871 break; 18872 } 18873 return -EINVAL; 18874 } 18875 18876 int bpf_check_attach_target(struct bpf_verifier_log *log, 18877 const struct bpf_prog *prog, 18878 const struct bpf_prog *tgt_prog, 18879 u32 btf_id, 18880 struct bpf_attach_target_info *tgt_info) 18881 { 18882 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 18883 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 18884 char trace_symbol[KSYM_SYMBOL_LEN]; 18885 const char prefix[] = "btf_trace_"; 18886 struct bpf_raw_event_map *btp; 18887 int ret = 0, subprog = -1, i; 18888 const struct btf_type *t; 18889 bool conservative = true; 18890 const char *tname, *fname; 18891 struct btf *btf; 18892 long addr = 0; 18893 struct module *mod = NULL; 18894 18895 if (!btf_id) { 18896 bpf_log(log, "Tracing programs must provide btf_id\n"); 18897 return -EINVAL; 18898 } 18899 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 18900 if (!btf) { 18901 bpf_log(log, 18902 "Tracing program can only be attached to another program annotated with BTF\n"); 18903 return -EINVAL; 18904 } 18905 t = btf_type_by_id(btf, btf_id); 18906 if (!t) { 18907 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 18908 return -EINVAL; 18909 } 18910 tname = btf_name_by_offset(btf, t->name_off); 18911 if (!tname) { 18912 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 18913 return -EINVAL; 18914 } 18915 if (tgt_prog) { 18916 struct bpf_prog_aux *aux = tgt_prog->aux; 18917 bool tgt_changes_pkt_data; 18918 bool tgt_might_sleep; 18919 18920 if (bpf_prog_is_dev_bound(prog->aux) && 18921 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 18922 bpf_log(log, "Target program bound device mismatch"); 18923 return -EINVAL; 18924 } 18925 18926 for (i = 0; i < aux->func_info_cnt; i++) 18927 if (aux->func_info[i].type_id == btf_id) { 18928 subprog = i; 18929 break; 18930 } 18931 if (subprog == -1) { 18932 bpf_log(log, "Subprog %s doesn't exist\n", tname); 18933 return -EINVAL; 18934 } 18935 if (aux->func && aux->func[subprog]->aux->exception_cb) { 18936 bpf_log(log, 18937 "%s programs cannot attach to exception callback\n", 18938 prog_extension ? "Extension" : "Tracing"); 18939 return -EINVAL; 18940 } 18941 conservative = aux->func_info_aux[subprog].unreliable; 18942 if (prog_extension) { 18943 if (conservative) { 18944 bpf_log(log, 18945 "Cannot replace static functions\n"); 18946 return -EINVAL; 18947 } 18948 if (!prog->jit_requested) { 18949 bpf_log(log, 18950 "Extension programs should be JITed\n"); 18951 return -EINVAL; 18952 } 18953 tgt_changes_pkt_data = aux->func 18954 ? aux->func[subprog]->aux->changes_pkt_data 18955 : aux->changes_pkt_data; 18956 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 18957 bpf_log(log, 18958 "Extension program changes packet data, while original does not\n"); 18959 return -EINVAL; 18960 } 18961 18962 tgt_might_sleep = aux->func 18963 ? aux->func[subprog]->aux->might_sleep 18964 : aux->might_sleep; 18965 if (prog->aux->might_sleep && !tgt_might_sleep) { 18966 bpf_log(log, 18967 "Extension program may sleep, while original does not\n"); 18968 return -EINVAL; 18969 } 18970 } 18971 if (!tgt_prog->jited) { 18972 bpf_log(log, "Can attach to only JITed progs\n"); 18973 return -EINVAL; 18974 } 18975 if (prog_tracing) { 18976 if (aux->attach_tracing_prog) { 18977 /* 18978 * Target program is an fentry/fexit which is already attached 18979 * to another tracing program. More levels of nesting 18980 * attachment are not allowed. 18981 */ 18982 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 18983 return -EINVAL; 18984 } 18985 } else if (tgt_prog->type == prog->type) { 18986 /* 18987 * To avoid potential call chain cycles, prevent attaching of a 18988 * program extension to another extension. It's ok to attach 18989 * fentry/fexit to extension program. 18990 */ 18991 bpf_log(log, "Cannot recursively attach\n"); 18992 return -EINVAL; 18993 } 18994 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 18995 prog_extension && 18996 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 18997 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT || 18998 tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI || 18999 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || 19000 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION || 19001 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19002 /* Program extensions can extend all program types 19003 * except fentry/fexit. The reason is the following. 19004 * The fentry/fexit programs are used for performance 19005 * analysis, stats and can be attached to any program 19006 * type. When extension program is replacing XDP function 19007 * it is necessary to allow performance analysis of all 19008 * functions. Both original XDP program and its program 19009 * extension. Hence attaching fentry/fexit to 19010 * BPF_PROG_TYPE_EXT is allowed. If extending of 19011 * fentry/fexit was allowed it would be possible to create 19012 * long call chain fentry->extension->fentry->extension 19013 * beyond reasonable stack size. Hence extending fentry 19014 * is not allowed. 19015 */ 19016 bpf_log(log, "Cannot extend fentry/fexit/fsession\n"); 19017 return -EINVAL; 19018 } 19019 } else { 19020 if (prog_extension) { 19021 bpf_log(log, "Cannot replace kernel functions\n"); 19022 return -EINVAL; 19023 } 19024 } 19025 19026 switch (prog->expected_attach_type) { 19027 case BPF_TRACE_RAW_TP: 19028 if (tgt_prog) { 19029 bpf_log(log, 19030 "Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n"); 19031 return -EINVAL; 19032 } 19033 if (!btf_type_is_typedef(t)) { 19034 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19035 btf_id); 19036 return -EINVAL; 19037 } 19038 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19039 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19040 btf_id, tname); 19041 return -EINVAL; 19042 } 19043 tname += sizeof(prefix) - 1; 19044 19045 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 19046 * names. Thus using bpf_raw_event_map to get argument names. 19047 */ 19048 btp = bpf_get_raw_tracepoint(tname); 19049 if (!btp) 19050 return -EINVAL; 19051 if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) { 19052 bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n", 19053 tname); 19054 bpf_put_raw_tracepoint(btp); 19055 return -EINVAL; 19056 } 19057 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 19058 trace_symbol); 19059 bpf_put_raw_tracepoint(btp); 19060 19061 if (fname) 19062 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 19063 19064 if (!fname || ret < 0) { 19065 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 19066 prefix, tname); 19067 t = btf_type_by_id(btf, t->type); 19068 if (!btf_type_is_ptr(t)) 19069 /* should never happen in valid vmlinux build */ 19070 return -EINVAL; 19071 } else { 19072 t = btf_type_by_id(btf, ret); 19073 if (!btf_type_is_func(t)) 19074 /* should never happen in valid vmlinux build */ 19075 return -EINVAL; 19076 } 19077 19078 t = btf_type_by_id(btf, t->type); 19079 if (!btf_type_is_func_proto(t)) 19080 /* should never happen in valid vmlinux build */ 19081 return -EINVAL; 19082 19083 break; 19084 case BPF_TRACE_ITER: 19085 if (!btf_type_is_func(t)) { 19086 bpf_log(log, "attach_btf_id %u is not a function\n", 19087 btf_id); 19088 return -EINVAL; 19089 } 19090 t = btf_type_by_id(btf, t->type); 19091 if (!btf_type_is_func_proto(t)) 19092 return -EINVAL; 19093 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19094 if (ret) 19095 return ret; 19096 break; 19097 default: 19098 if (!prog_extension) 19099 return -EINVAL; 19100 fallthrough; 19101 case BPF_MODIFY_RETURN: 19102 case BPF_LSM_MAC: 19103 case BPF_LSM_CGROUP: 19104 case BPF_TRACE_FENTRY: 19105 case BPF_TRACE_FEXIT: 19106 case BPF_TRACE_FSESSION: 19107 case BPF_TRACE_FSESSION_MULTI: 19108 case BPF_TRACE_FENTRY_MULTI: 19109 case BPF_TRACE_FEXIT_MULTI: 19110 if ((prog->expected_attach_type == BPF_TRACE_FSESSION || 19111 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) && 19112 !bpf_jit_supports_fsession()) { 19113 bpf_log(log, "JIT does not support fsession\n"); 19114 return -EOPNOTSUPP; 19115 } 19116 if (!btf_type_is_func(t)) { 19117 bpf_log(log, "attach_btf_id %u is not a function\n", 19118 btf_id); 19119 return -EINVAL; 19120 } 19121 if (prog_extension && 19122 btf_check_type_match(log, prog, btf, t)) 19123 return -EINVAL; 19124 t = btf_type_by_id(btf, t->type); 19125 if (!btf_type_is_func_proto(t)) 19126 return -EINVAL; 19127 19128 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 19129 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 19130 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 19131 return -EINVAL; 19132 19133 if (tgt_prog && conservative) 19134 t = NULL; 19135 19136 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19137 if (ret < 0) 19138 return ret; 19139 19140 /* 19141 * *.multi programs don't need an address during program 19142 * verification, we just take the module ref if needed. 19143 */ 19144 if (is_tracing_multi_id(prog, btf_id)) { 19145 if (btf_is_module(btf)) { 19146 mod = btf_try_get_module(btf); 19147 if (!mod) 19148 return -ENOENT; 19149 } 19150 addr = 0; 19151 } else if (tgt_prog) { 19152 if (subprog == 0) 19153 addr = (long) tgt_prog->bpf_func; 19154 else 19155 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 19156 } else { 19157 if (btf_is_module(btf)) { 19158 mod = btf_try_get_module(btf); 19159 if (mod) 19160 addr = find_kallsyms_symbol_value(mod, tname); 19161 else 19162 addr = 0; 19163 } else { 19164 addr = kallsyms_lookup_name(tname); 19165 } 19166 if (!addr) { 19167 module_put(mod); 19168 bpf_log(log, 19169 "The address of function %s cannot be found\n", 19170 tname); 19171 return -ENOENT; 19172 } 19173 } 19174 19175 if (prog->sleepable) { 19176 ret = btf_id_allow_sleepable(btf_id, addr, prog, btf); 19177 if (ret) { 19178 module_put(mod); 19179 bpf_log(log, "%s is not sleepable\n", tname); 19180 return ret; 19181 } 19182 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19183 if (tgt_prog) { 19184 module_put(mod); 19185 bpf_log(log, "can't modify return codes of BPF programs\n"); 19186 return -EINVAL; 19187 } 19188 ret = -EINVAL; 19189 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19190 !check_attach_modify_return(addr, tname)) 19191 ret = 0; 19192 if (ret) { 19193 module_put(mod); 19194 bpf_log(log, "%s() is not modifiable\n", tname); 19195 return ret; 19196 } 19197 } 19198 19199 break; 19200 } 19201 tgt_info->tgt_addr = addr; 19202 tgt_info->tgt_name = tname; 19203 tgt_info->tgt_type = t; 19204 tgt_info->tgt_mod = mod; 19205 return 0; 19206 } 19207 19208 BTF_SET_START(btf_id_deny) 19209 BTF_ID_UNUSED 19210 #ifdef CONFIG_SMP 19211 BTF_ID(func, ___migrate_enable) 19212 BTF_ID(func, migrate_disable) 19213 BTF_ID(func, migrate_enable) 19214 #endif 19215 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19216 BTF_ID(func, rcu_read_unlock_strict) 19217 #endif 19218 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19219 BTF_ID(func, preempt_count_add) 19220 BTF_ID(func, preempt_count_sub) 19221 #endif 19222 #ifdef CONFIG_PREEMPT_RCU 19223 BTF_ID(func, __rcu_read_lock) 19224 BTF_ID(func, __rcu_read_unlock) 19225 #endif 19226 BTF_SET_END(btf_id_deny) 19227 19228 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 19229 * Currently, we must manually list all __noreturn functions here. Once a more 19230 * robust solution is implemented, this workaround can be removed. 19231 */ 19232 BTF_SET_START(noreturn_deny) 19233 #ifdef CONFIG_IA32_EMULATION 19234 BTF_ID(func, __ia32_sys_exit) 19235 BTF_ID(func, __ia32_sys_exit_group) 19236 #endif 19237 #ifdef CONFIG_KUNIT 19238 BTF_ID(func, __kunit_abort) 19239 BTF_ID(func, kunit_try_catch_throw) 19240 #endif 19241 #ifdef CONFIG_MODULES 19242 BTF_ID(func, __module_put_and_kthread_exit) 19243 #endif 19244 #ifdef CONFIG_X86_64 19245 BTF_ID(func, __x64_sys_exit) 19246 BTF_ID(func, __x64_sys_exit_group) 19247 #endif 19248 BTF_ID(func, do_exit) 19249 BTF_ID(func, do_group_exit) 19250 BTF_ID(func, kthread_complete_and_exit) 19251 BTF_ID(func, make_task_dead) 19252 BTF_SET_END(noreturn_deny) 19253 19254 static bool can_be_sleepable(struct bpf_prog *prog) 19255 { 19256 if (prog->type == BPF_PROG_TYPE_TRACING) { 19257 switch (prog->expected_attach_type) { 19258 case BPF_TRACE_FENTRY: 19259 case BPF_TRACE_FEXIT: 19260 case BPF_MODIFY_RETURN: 19261 case BPF_TRACE_ITER: 19262 case BPF_TRACE_FSESSION: 19263 case BPF_TRACE_RAW_TP: 19264 case BPF_TRACE_FENTRY_MULTI: 19265 case BPF_TRACE_FEXIT_MULTI: 19266 case BPF_TRACE_FSESSION_MULTI: 19267 return true; 19268 default: 19269 return false; 19270 } 19271 } 19272 if (prog->type == BPF_PROG_TYPE_LSM) 19273 return prog->expected_attach_type != BPF_LSM_CGROUP; 19274 19275 return prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 19276 prog->type == BPF_PROG_TYPE_STRUCT_OPS || 19277 prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT || 19278 prog->type == BPF_PROG_TYPE_TRACEPOINT; 19279 } 19280 19281 static int check_attach_btf_id(struct bpf_verifier_env *env) 19282 { 19283 struct bpf_prog *prog = env->prog; 19284 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 19285 struct bpf_attach_target_info tgt_info = {}; 19286 u32 btf_id = prog->aux->attach_btf_id; 19287 struct bpf_trampoline *tr; 19288 int ret; 19289 u64 key; 19290 19291 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 19292 if (prog->sleepable) 19293 /* attach_btf_id checked to be zero already */ 19294 return 0; 19295 verbose(env, "Syscall programs can only be sleepable\n"); 19296 return -EINVAL; 19297 } 19298 19299 if (prog->sleepable && !can_be_sleepable(prog)) { 19300 verbose(env, "Program of this type cannot be sleepable\n"); 19301 return -EINVAL; 19302 } 19303 19304 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 19305 return check_struct_ops_btf_id(env); 19306 19307 if (prog->type != BPF_PROG_TYPE_TRACING && 19308 prog->type != BPF_PROG_TYPE_LSM && 19309 prog->type != BPF_PROG_TYPE_EXT) 19310 return 0; 19311 19312 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 19313 if (ret) 19314 return ret; 19315 19316 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 19317 /* to make freplace equivalent to their targets, they need to 19318 * inherit env->ops and expected_attach_type for the rest of the 19319 * verification 19320 */ 19321 env->ops = bpf_verifier_ops[tgt_prog->type]; 19322 prog->expected_attach_type = tgt_prog->expected_attach_type; 19323 } 19324 19325 /* store info about the attachment target that will be used later */ 19326 prog->aux->attach_func_proto = tgt_info.tgt_type; 19327 prog->aux->attach_func_name = tgt_info.tgt_name; 19328 prog->aux->mod = tgt_info.tgt_mod; 19329 19330 if (tgt_prog) { 19331 prog->aux->saved_dst_prog_type = tgt_prog->type; 19332 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 19333 } 19334 19335 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 19336 prog->aux->attach_btf_trace = true; 19337 return 0; 19338 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 19339 return bpf_iter_prog_supported(prog); 19340 } 19341 19342 if (prog->type == BPF_PROG_TYPE_LSM) { 19343 ret = bpf_lsm_verify_prog(&env->log, prog); 19344 if (ret < 0) 19345 return ret; 19346 } else if (prog->type == BPF_PROG_TYPE_TRACING && 19347 btf_id_set_contains(&btf_id_deny, btf_id)) { 19348 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 19349 tgt_info.tgt_name); 19350 return -EINVAL; 19351 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 19352 prog->expected_attach_type == BPF_TRACE_FSESSION || 19353 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI || 19354 prog->expected_attach_type == BPF_MODIFY_RETURN) && 19355 btf_id_set_contains(&noreturn_deny, btf_id)) { 19356 verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n", 19357 tgt_info.tgt_name); 19358 return -EINVAL; 19359 } 19360 19361 /* 19362 * We don't get trampoline for tracing_multi programs at this point, 19363 * it's done when tracing_multi link is created. 19364 */ 19365 if (prog->type == BPF_PROG_TYPE_TRACING && 19366 is_tracing_multi(prog->expected_attach_type)) 19367 return 0; 19368 19369 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 19370 tr = bpf_trampoline_get(key, &tgt_info); 19371 if (!tr) 19372 return -ENOMEM; 19373 19374 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 19375 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 19376 19377 prog->aux->dst_trampoline = tr; 19378 return 0; 19379 } 19380 19381 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id, 19382 struct bpf_attach_target_info *tgt_info) 19383 { 19384 const struct btf_type *t; 19385 unsigned long addr; 19386 const char *tname; 19387 int err; 19388 19389 if (!btf_id || !btf) 19390 return -EINVAL; 19391 19392 /* Check noreturn attachment. */ 19393 if ((prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || 19394 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) && 19395 btf_id_set_contains(&noreturn_deny, btf_id)) 19396 return -EINVAL; 19397 /* Check denied attachment. */ 19398 if (btf_id_set_contains(&btf_id_deny, btf_id)) 19399 return -EINVAL; 19400 19401 /* Check and get function target data. */ 19402 t = btf_type_by_id(btf, btf_id); 19403 if (!t) 19404 return -EINVAL; 19405 tname = btf_name_by_offset(btf, t->name_off); 19406 if (!tname) 19407 return -EINVAL; 19408 if (!btf_type_is_func(t)) 19409 return -EINVAL; 19410 t = btf_type_by_id(btf, t->type); 19411 if (!btf_type_is_func_proto(t)) 19412 return -EINVAL; 19413 err = btf_distill_func_proto(NULL, btf, t, tname, &tgt_info->fmodel); 19414 if (err < 0) 19415 return err; 19416 if (btf_is_module(btf)) { 19417 /* The bpf program already holds reference to module. */ 19418 if (WARN_ON_ONCE(!prog->aux->mod)) 19419 return -EINVAL; 19420 addr = find_kallsyms_symbol_value(prog->aux->mod, tname); 19421 } else { 19422 addr = kallsyms_lookup_name(tname); 19423 } 19424 if (!addr || !ftrace_location(addr)) 19425 return -ENOENT; 19426 19427 /* Check sleepable program attachment. */ 19428 if (prog->sleepable) { 19429 err = btf_id_allow_sleepable(btf_id, addr, prog, btf); 19430 if (err) 19431 return err; 19432 } 19433 tgt_info->tgt_addr = addr; 19434 return 0; 19435 } 19436 19437 struct btf *bpf_get_btf_vmlinux(void) 19438 { 19439 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 19440 mutex_lock(&bpf_verifier_lock); 19441 if (!btf_vmlinux) 19442 btf_vmlinux = btf_parse_vmlinux(); 19443 mutex_unlock(&bpf_verifier_lock); 19444 } 19445 return btf_vmlinux; 19446 } 19447 19448 /* 19449 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 19450 * this case expect that every file descriptor in the array is either a map or 19451 * a BTF. Everything else is considered to be trash. 19452 */ 19453 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) 19454 { 19455 struct bpf_map *map; 19456 struct btf *btf; 19457 CLASS(fd, f)(fd); 19458 int err; 19459 19460 map = __bpf_map_get(f); 19461 if (!IS_ERR(map)) { 19462 err = __add_used_map(env, map); 19463 if (err < 0) 19464 return err; 19465 return 0; 19466 } 19467 19468 btf = __btf_get_by_fd(f); 19469 if (!IS_ERR(btf)) { 19470 btf_get(btf); 19471 return __add_used_btf(env, btf); 19472 } 19473 19474 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 19475 return PTR_ERR(map); 19476 } 19477 19478 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr) 19479 { 19480 size_t size = sizeof(int); 19481 int ret; 19482 int fd; 19483 u32 i; 19484 19485 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 19486 19487 /* 19488 * The only difference between old (no fd_array_cnt is given) and new 19489 * APIs is that in the latter case the fd_array is expected to be 19490 * continuous and is scanned for map fds right away 19491 */ 19492 if (!attr->fd_array_cnt) 19493 return 0; 19494 19495 /* Check for integer overflow */ 19496 if (attr->fd_array_cnt >= (U32_MAX / size)) { 19497 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt); 19498 return -EINVAL; 19499 } 19500 19501 for (i = 0; i < attr->fd_array_cnt; i++) { 19502 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size)) 19503 return -EFAULT; 19504 19505 ret = add_fd_from_fd_array(env, fd); 19506 if (ret) 19507 return ret; 19508 } 19509 19510 return 0; 19511 } 19512 19513 /* replace a generic kfunc with a specialized version if necessary */ 19514 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx) 19515 { 19516 struct bpf_prog *prog = env->prog; 19517 bool seen_direct_write; 19518 void *xdp_kfunc; 19519 bool is_rdonly; 19520 u32 func_id = desc->func_id; 19521 u16 offset = desc->offset; 19522 unsigned long addr = desc->addr; 19523 19524 if (offset) /* return if module BTF is used */ 19525 return 0; 19526 19527 if (bpf_dev_bound_kfunc_id(func_id)) { 19528 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19529 if (xdp_kfunc) 19530 addr = (unsigned long)xdp_kfunc; 19531 /* fallback to default kfunc when not supported by netdev */ 19532 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19533 seen_direct_write = env->seen_direct_write; 19534 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19535 19536 if (is_rdonly) 19537 addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19538 19539 /* restore env->seen_direct_write to its original value, since 19540 * may_access_direct_pkt_data mutates it 19541 */ 19542 env->seen_direct_write = seen_direct_write; 19543 } else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) { 19544 if (bpf_lsm_has_d_inode_locked(prog)) 19545 addr = (unsigned long)bpf_set_dentry_xattr_locked; 19546 } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) { 19547 if (bpf_lsm_has_d_inode_locked(prog)) 19548 addr = (unsigned long)bpf_remove_dentry_xattr_locked; 19549 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 19550 if (!env->insn_aux_data[insn_idx].non_sleepable) 19551 addr = (unsigned long)bpf_dynptr_from_file_sleepable; 19552 } else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) { 19553 if (env->insn_aux_data[insn_idx].non_sleepable) 19554 addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable; 19555 } else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) { 19556 if (env->insn_aux_data[insn_idx].non_sleepable) 19557 addr = (unsigned long)bpf_arena_free_pages_non_sleepable; 19558 } 19559 desc->addr = addr; 19560 return 0; 19561 } 19562 19563 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19564 u16 struct_meta_reg, 19565 u16 node_offset_reg, 19566 struct bpf_insn *insn, 19567 struct bpf_insn *insn_buf, 19568 int *cnt) 19569 { 19570 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19571 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19572 19573 insn_buf[0] = addr[0]; 19574 insn_buf[1] = addr[1]; 19575 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19576 insn_buf[3] = *insn; 19577 *cnt = 4; 19578 } 19579 19580 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19581 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19582 { 19583 struct bpf_kfunc_desc *desc; 19584 int err; 19585 19586 if (!insn->imm) { 19587 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19588 return -EINVAL; 19589 } 19590 19591 *cnt = 0; 19592 19593 /* insn->imm has the btf func_id. Replace it with an offset relative to 19594 * __bpf_call_base, unless the JIT needs to call functions that are 19595 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19596 */ 19597 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19598 if (!desc) { 19599 verifier_bug(env, "kernel function descriptor not found for func_id %u", 19600 insn->imm); 19601 return -EFAULT; 19602 } 19603 19604 err = specialize_kfunc(env, desc, insn_idx); 19605 if (err) 19606 return err; 19607 19608 if (!bpf_jit_supports_far_kfunc_call()) 19609 insn->imm = BPF_CALL_IMM(desc->addr); 19610 19611 if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) { 19612 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19613 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19614 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19615 19616 if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) { 19617 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19618 insn_idx); 19619 return -EFAULT; 19620 } 19621 19622 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19623 insn_buf[1] = addr[0]; 19624 insn_buf[2] = addr[1]; 19625 insn_buf[3] = *insn; 19626 *cnt = 4; 19627 } else if (is_bpf_obj_drop_kfunc(desc->func_id) || 19628 is_bpf_percpu_obj_drop_kfunc(desc->func_id) || 19629 is_bpf_refcount_acquire_kfunc(desc->func_id)) { 19630 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19631 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19632 19633 if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) { 19634 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19635 insn_idx); 19636 return -EFAULT; 19637 } 19638 19639 if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) { 19640 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19641 insn_idx); 19642 return -EFAULT; 19643 } 19644 19645 insn_buf[0] = addr[0]; 19646 insn_buf[1] = addr[1]; 19647 insn_buf[2] = *insn; 19648 *cnt = 3; 19649 } else if (is_bpf_list_push_kfunc(desc->func_id) || 19650 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19651 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19652 int struct_meta_reg = BPF_REG_3; 19653 int node_offset_reg = BPF_REG_4; 19654 19655 /* list_add/rbtree_add have an extra arg (prev/less), 19656 * so args-to-fixup are in diff regs. 19657 */ 19658 if (desc->func_id == special_kfunc_list[KF_bpf_list_add] || 19659 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19660 struct_meta_reg = BPF_REG_4; 19661 node_offset_reg = BPF_REG_5; 19662 } 19663 19664 if (!kptr_struct_meta) { 19665 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19666 insn_idx); 19667 return -EFAULT; 19668 } 19669 19670 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19671 node_offset_reg, insn, insn_buf, cnt); 19672 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19673 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19674 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19675 *cnt = 1; 19676 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] && 19677 (env->prog->expected_attach_type == BPF_TRACE_FSESSION || 19678 env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19679 19680 /* 19681 * inline the bpf_session_is_return() for fsession: 19682 * bool bpf_session_is_return(void *ctx) 19683 * { 19684 * return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1; 19685 * } 19686 */ 19687 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19688 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT); 19689 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1); 19690 *cnt = 3; 19691 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] && 19692 (env->prog->expected_attach_type == BPF_TRACE_FSESSION || 19693 env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19694 /* 19695 * inline bpf_session_cookie() for fsession: 19696 * __u64 *bpf_session_cookie(void *ctx) 19697 * { 19698 * u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF; 19699 * return &((u64 *)ctx)[-off]; 19700 * } 19701 */ 19702 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19703 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT); 19704 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF); 19705 insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19706 insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1); 19707 insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0); 19708 *cnt = 6; 19709 } 19710 19711 if (env->insn_aux_data[insn_idx].arg_prog) { 19712 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 19713 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 19714 int idx = *cnt; 19715 19716 insn_buf[idx++] = ld_addrs[0]; 19717 insn_buf[idx++] = ld_addrs[1]; 19718 insn_buf[idx++] = *insn; 19719 *cnt = idx; 19720 } 19721 return 0; 19722 } 19723 19724 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, 19725 struct bpf_log_attr *attr_log) 19726 { 19727 u64 start_time = ktime_get_ns(); 19728 struct bpf_verifier_env *env; 19729 int i, len, ret = -EINVAL, err; 19730 bool is_priv; 19731 19732 BTF_TYPE_EMIT(enum bpf_features); 19733 19734 /* no program is valid */ 19735 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 19736 return -EINVAL; 19737 19738 /* 'struct bpf_verifier_env' can be global, but since it's not small, 19739 * allocate/free it every time bpf_check() is called 19740 */ 19741 env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT); 19742 if (!env) 19743 return -ENOMEM; 19744 19745 env->bt.env = env; 19746 19747 len = (*prog)->len; 19748 env->insn_aux_data = 19749 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 19750 ret = -ENOMEM; 19751 if (!env->insn_aux_data) 19752 goto err_free_env; 19753 for (i = 0; i < len; i++) 19754 env->insn_aux_data[i].orig_idx = i; 19755 env->succ = bpf_iarray_realloc(NULL, 2); 19756 if (!env->succ) 19757 goto err_free_env; 19758 env->prog = *prog; 19759 env->ops = bpf_verifier_ops[env->prog->type]; 19760 19761 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 19762 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 19763 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 19764 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 19765 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 19766 19767 bpf_get_btf_vmlinux(); 19768 19769 /* grab the mutex to protect few globals used by verifier */ 19770 if (!is_priv) 19771 mutex_lock(&bpf_verifier_lock); 19772 19773 /* user could have requested verbose verifier output 19774 * and supplied buffer to store the verification trace 19775 */ 19776 ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size); 19777 if (ret) 19778 goto err_unlock; 19779 19780 ret = process_fd_array(env, attr, uattr); 19781 if (ret) 19782 goto skip_full_check; 19783 19784 mark_verifier_state_clean(env); 19785 19786 if (IS_ERR(btf_vmlinux)) { 19787 /* Either gcc or pahole or kernel are broken. */ 19788 verbose(env, "in-kernel BTF is malformed\n"); 19789 ret = PTR_ERR(btf_vmlinux); 19790 goto skip_full_check; 19791 } 19792 19793 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 19794 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 19795 env->strict_alignment = true; 19796 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 19797 env->strict_alignment = false; 19798 19799 if (is_priv) 19800 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 19801 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 19802 19803 env->explored_states = kvzalloc_objs(struct list_head, 19804 state_htab_size(env), 19805 GFP_KERNEL_ACCOUNT); 19806 ret = -ENOMEM; 19807 if (!env->explored_states) 19808 goto skip_full_check; 19809 19810 for (i = 0; i < state_htab_size(env); i++) 19811 INIT_LIST_HEAD(&env->explored_states[i]); 19812 INIT_LIST_HEAD(&env->free_list); 19813 19814 ret = bpf_check_btf_info_early(env, attr, uattr); 19815 if (ret < 0) 19816 goto skip_full_check; 19817 19818 ret = add_subprog_and_kfunc(env); 19819 if (ret < 0) 19820 goto skip_full_check; 19821 19822 ret = check_subprogs(env); 19823 if (ret < 0) 19824 goto skip_full_check; 19825 19826 ret = bpf_check_btf_info(env, attr, uattr); 19827 if (ret < 0) 19828 goto skip_full_check; 19829 19830 ret = check_and_resolve_insns(env); 19831 if (ret < 0) 19832 goto skip_full_check; 19833 19834 if (bpf_prog_is_offloaded(env->prog->aux)) { 19835 ret = bpf_prog_offload_verifier_prep(env->prog); 19836 if (ret) 19837 goto skip_full_check; 19838 } 19839 19840 ret = bpf_check_cfg(env); 19841 if (ret < 0) 19842 goto skip_full_check; 19843 19844 ret = bpf_compute_postorder(env); 19845 if (ret < 0) 19846 goto skip_full_check; 19847 19848 ret = bpf_stack_liveness_init(env); 19849 if (ret) 19850 goto skip_full_check; 19851 19852 ret = check_attach_btf_id(env); 19853 if (ret) 19854 goto skip_full_check; 19855 19856 ret = bpf_compute_const_regs(env); 19857 if (ret < 0) 19858 goto skip_full_check; 19859 19860 ret = bpf_prune_dead_branches(env); 19861 if (ret < 0) 19862 goto skip_full_check; 19863 19864 ret = sort_subprogs_topo(env); 19865 if (ret < 0) 19866 goto skip_full_check; 19867 19868 ret = bpf_compute_scc(env); 19869 if (ret < 0) 19870 goto skip_full_check; 19871 19872 ret = bpf_compute_live_registers(env); 19873 if (ret < 0) 19874 goto skip_full_check; 19875 19876 ret = mark_fastcall_patterns(env); 19877 if (ret < 0) 19878 goto skip_full_check; 19879 19880 ret = do_check_main(env); 19881 ret = ret ?: do_check_subprogs(env); 19882 19883 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 19884 ret = bpf_prog_offload_finalize(env); 19885 19886 skip_full_check: 19887 kvfree(env->explored_states); 19888 19889 /* might decrease stack depth, keep it before passes that 19890 * allocate additional slots. 19891 */ 19892 if (ret == 0) 19893 ret = bpf_remove_fastcall_spills_fills(env); 19894 19895 if (ret == 0) 19896 ret = check_max_stack_depth(env); 19897 19898 /* instruction rewrites happen after this point */ 19899 if (ret == 0) 19900 ret = bpf_optimize_bpf_loop(env); 19901 19902 if (is_priv) { 19903 if (ret == 0) 19904 bpf_opt_hard_wire_dead_code_branches(env); 19905 if (ret == 0) 19906 ret = bpf_opt_remove_dead_code(env); 19907 if (ret == 0) 19908 ret = bpf_opt_remove_nops(env); 19909 } else { 19910 if (ret == 0) 19911 sanitize_dead_code(env); 19912 } 19913 19914 if (ret == 0) 19915 /* program is valid, convert *(u32*)(ctx + off) accesses */ 19916 ret = bpf_convert_ctx_accesses(env); 19917 19918 if (ret == 0) 19919 ret = bpf_do_misc_fixups(env); 19920 19921 /* do 32-bit optimization after insn patching has done so those patched 19922 * insns could be handled correctly. 19923 */ 19924 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 19925 ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr); 19926 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 19927 : false; 19928 } 19929 19930 if (ret == 0) 19931 ret = bpf_fixup_call_args(env); 19932 19933 env->verification_time = ktime_get_ns() - start_time; 19934 print_verification_stats(env); 19935 env->prog->aux->verified_insns = env->insn_processed; 19936 19937 /* preserve original error even if log finalization is successful */ 19938 err = bpf_log_attr_finalize(attr_log, &env->log); 19939 if (err) 19940 ret = err; 19941 19942 if (ret) 19943 goto err_release_maps; 19944 19945 if (env->used_map_cnt) { 19946 /* if program passed verifier, update used_maps in bpf_prog_info */ 19947 env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0], 19948 env->used_map_cnt, 19949 GFP_KERNEL_ACCOUNT); 19950 19951 if (!env->prog->aux->used_maps) { 19952 ret = -ENOMEM; 19953 goto err_release_maps; 19954 } 19955 19956 memcpy(env->prog->aux->used_maps, env->used_maps, 19957 sizeof(env->used_maps[0]) * env->used_map_cnt); 19958 env->prog->aux->used_map_cnt = env->used_map_cnt; 19959 } 19960 if (env->used_btf_cnt) { 19961 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 19962 env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0], 19963 env->used_btf_cnt, 19964 GFP_KERNEL_ACCOUNT); 19965 if (!env->prog->aux->used_btfs) { 19966 ret = -ENOMEM; 19967 goto err_release_maps; 19968 } 19969 19970 memcpy(env->prog->aux->used_btfs, env->used_btfs, 19971 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 19972 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 19973 } 19974 if (env->used_map_cnt || env->used_btf_cnt) { 19975 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 19976 * bpf_ld_imm64 instructions 19977 */ 19978 convert_pseudo_ld_imm64(env); 19979 } 19980 19981 adjust_btf_func(env); 19982 19983 /* extension progs temporarily inherit the attach_type of their targets 19984 for verification purposes, so set it back to zero before returning 19985 */ 19986 if (env->prog->type == BPF_PROG_TYPE_EXT) 19987 env->prog->expected_attach_type = 0; 19988 19989 env->prog = __bpf_prog_select_runtime(env, env->prog, &ret); 19990 19991 err_release_maps: 19992 if (ret) 19993 release_insn_arrays(env); 19994 if (!env->prog->aux->used_maps) 19995 /* if we didn't copy map pointers into bpf_prog_info, release 19996 * them now. Otherwise free_used_maps() will release them. 19997 */ 19998 release_maps(env); 19999 if (!env->prog->aux->used_btfs) 20000 release_btfs(env); 20001 20002 *prog = env->prog; 20003 20004 module_put(env->attach_btf_mod); 20005 err_unlock: 20006 if (!is_priv) 20007 mutex_unlock(&bpf_verifier_lock); 20008 bpf_clear_insn_aux_data(env, 0, env->prog->len); 20009 err_free_env: 20010 bpf_stack_liveness_free(env); 20011 kvfree(env->cfg.insn_postorder); 20012 kvfree(env->scc_info); 20013 kvfree(env->succ); 20014 kvfree(env->gotox_tmp_buf); 20015 vfree(env->insn_aux_data); 20016 kvfree(env); 20017 return ret; 20018 } 20019