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 /* check if register is a constant scalar value */ 3308 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 3309 { 3310 return reg->type == SCALAR_VALUE && 3311 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 3312 } 3313 3314 /* assuming is_reg_const() is true, return constant value of a register */ 3315 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 3316 { 3317 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 3318 } 3319 3320 static bool is_pointer_regtype(enum bpf_reg_type type) 3321 { 3322 return type != SCALAR_VALUE && type != NOT_INIT; 3323 } 3324 3325 static bool __is_pointer_value(bool allow_ptr_leaks, 3326 const struct bpf_reg_state *reg) 3327 { 3328 if (allow_ptr_leaks) 3329 return false; 3330 3331 return is_pointer_regtype(reg->type); 3332 } 3333 3334 static void clear_scalar_id(struct bpf_reg_state *reg) 3335 { 3336 reg->id = 0; 3337 reg->delta = 0; 3338 } 3339 3340 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 3341 struct bpf_reg_state *src_reg) 3342 { 3343 if (src_reg->type != SCALAR_VALUE) 3344 return; 3345 /* 3346 * The verifier is processing rX = rY insn and 3347 * rY->id has special linked register already. 3348 * Cleared it, since multiple rX += const are not supported. 3349 */ 3350 if (src_reg->id & BPF_ADD_CONST) 3351 clear_scalar_id(src_reg); 3352 /* 3353 * Ensure that src_reg has a valid ID that will be copied to 3354 * dst_reg and then will be used by sync_linked_regs() to 3355 * propagate min/max range. 3356 */ 3357 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 3358 src_reg->id = ++env->id_gen; 3359 } 3360 3361 static void save_register_state(struct bpf_verifier_env *env, 3362 struct bpf_func_state *state, 3363 int spi, struct bpf_reg_state *reg, 3364 int size) 3365 { 3366 int i; 3367 3368 state->stack[spi].spilled_ptr = *reg; 3369 3370 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3371 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 3372 3373 /* size < 8 bytes spill */ 3374 for (; i; i--) 3375 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 3376 } 3377 3378 static bool is_bpf_st_mem(struct bpf_insn *insn) 3379 { 3380 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 3381 } 3382 3383 static int get_reg_width(struct bpf_reg_state *reg) 3384 { 3385 return fls64(reg_umax(reg)); 3386 } 3387 3388 /* See comment for mark_fastcall_pattern_for_call() */ 3389 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 3390 struct bpf_func_state *state, int insn_idx, int off) 3391 { 3392 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 3393 struct bpf_insn_aux_data *aux = env->insn_aux_data; 3394 int i; 3395 3396 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 3397 return; 3398 /* access to the region [max_stack_depth .. fastcall_stack_off) 3399 * from something that is not a part of the fastcall pattern, 3400 * disable fastcall rewrites for current subprogram by setting 3401 * fastcall_stack_off to a value smaller than any possible offset. 3402 */ 3403 subprog->fastcall_stack_off = S16_MIN; 3404 /* reset fastcall aux flags within subprogram, 3405 * happens at most once per subprogram 3406 */ 3407 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 3408 aux[i].fastcall_spills_num = 0; 3409 aux[i].fastcall_pattern = 0; 3410 } 3411 } 3412 3413 static void scrub_special_slot(struct bpf_func_state *state, int spi) 3414 { 3415 int i; 3416 3417 /* regular write of data into stack destroys any spilled ptr */ 3418 state->stack[spi].spilled_ptr.type = NOT_INIT; 3419 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 3420 if (is_stack_slot_special(&state->stack[spi])) 3421 for (i = 0; i < BPF_REG_SIZE; i++) 3422 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 3423 } 3424 3425 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3426 * stack boundary and alignment are checked in check_mem_access() 3427 */ 3428 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3429 /* stack frame we're writing to */ 3430 struct bpf_func_state *state, 3431 int off, int size, int value_regno, 3432 int insn_idx) 3433 { 3434 struct bpf_func_state *cur; /* state of the current function */ 3435 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3436 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3437 struct bpf_reg_state *reg = NULL; 3438 int insn_flags = INSN_F_STACK_ACCESS; 3439 int hist_spi = spi, hist_frame = state->frameno; 3440 3441 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 3442 * so it's aligned access and [off, off + size) are within stack limits 3443 */ 3444 if (!env->allow_ptr_leaks && 3445 bpf_is_spilled_reg(&state->stack[spi]) && 3446 !bpf_is_spilled_scalar_reg(&state->stack[spi]) && 3447 size != BPF_REG_SIZE) { 3448 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3449 return -EACCES; 3450 } 3451 3452 cur = env->cur_state->frame[env->cur_state->curframe]; 3453 if (value_regno >= 0) 3454 reg = &cur->regs[value_regno]; 3455 if (!env->bypass_spec_v4) { 3456 bool sanitize = reg && is_pointer_regtype(reg->type); 3457 3458 for (i = 0; i < size; i++) { 3459 u8 type = state->stack[spi].slot_type[(slot - i) % 3460 BPF_REG_SIZE]; 3461 3462 if (type != STACK_MISC && type != STACK_ZERO) { 3463 sanitize = true; 3464 break; 3465 } 3466 } 3467 3468 if (sanitize) 3469 env->insn_aux_data[insn_idx].nospec_result = true; 3470 } 3471 3472 err = destroy_if_dynptr_stack_slot(env, state, spi); 3473 if (err) 3474 return err; 3475 3476 check_fastcall_stack_contract(env, state, insn_idx, off); 3477 mark_stack_slot_scratched(env, spi); 3478 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 3479 bool reg_value_fits; 3480 3481 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 3482 /* Make sure that reg had an ID to build a relation on spill. */ 3483 if (reg_value_fits) 3484 assign_scalar_id_before_mov(env, reg); 3485 save_register_state(env, state, spi, reg, size); 3486 /* Break the relation on a narrowing spill. */ 3487 if (!reg_value_fits) 3488 state->stack[spi].spilled_ptr.id = 0; 3489 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 3490 env->bpf_capable) { 3491 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 3492 3493 memset(tmp_reg, 0, sizeof(*tmp_reg)); 3494 __mark_reg_known(tmp_reg, insn->imm); 3495 tmp_reg->type = SCALAR_VALUE; 3496 save_register_state(env, state, spi, tmp_reg, size); 3497 } else if (reg && is_pointer_regtype(reg->type)) { 3498 /* register containing pointer is being spilled into stack */ 3499 if (size != BPF_REG_SIZE) { 3500 verbose_linfo(env, insn_idx, "; "); 3501 verbose(env, "invalid size of register spill\n"); 3502 return -EACCES; 3503 } 3504 if (state != cur && reg->type == PTR_TO_STACK) { 3505 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 3506 return -EINVAL; 3507 } 3508 save_register_state(env, state, spi, reg, size); 3509 } else { 3510 u8 type = STACK_MISC; 3511 3512 scrub_special_slot(state, spi); 3513 3514 /* when we zero initialize stack slots mark them as such */ 3515 if ((reg && bpf_register_is_null(reg)) || 3516 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 3517 /* STACK_ZERO case happened because register spill 3518 * wasn't properly aligned at the stack slot boundary, 3519 * so it's not a register spill anymore; force 3520 * originating register to be precise to make 3521 * STACK_ZERO correct for subsequent states 3522 */ 3523 err = mark_chain_precision(env, value_regno); 3524 if (err) 3525 return err; 3526 type = STACK_ZERO; 3527 } 3528 3529 /* Mark slots affected by this stack write. */ 3530 for (i = 0; i < size; i++) 3531 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 3532 insn_flags = 0; /* not a register spill */ 3533 } 3534 3535 if (insn_flags) 3536 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3537 hist_spi, hist_frame, 0); 3538 return 0; 3539 } 3540 3541 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is 3542 * known to contain a variable offset. 3543 * This function checks whether the write is permitted and conservatively 3544 * tracks the effects of the write, considering that each stack slot in the 3545 * dynamic range is potentially written to. 3546 * 3547 * 'value_regno' can be -1, meaning that an unknown value is being written to 3548 * the stack. 3549 * 3550 * Spilled pointers in range are not marked as written because we don't know 3551 * what's going to be actually written. This means that read propagation for 3552 * future reads cannot be terminated by this write. 3553 * 3554 * For privileged programs, uninitialized stack slots are considered 3555 * initialized by this write (even though we don't know exactly what offsets 3556 * are going to be written to). The idea is that we don't want the verifier to 3557 * reject future reads that access slots written to through variable offsets. 3558 */ 3559 static int check_stack_write_var_off(struct bpf_verifier_env *env, 3560 /* func where register points to */ 3561 struct bpf_func_state *state, 3562 struct bpf_reg_state *ptr_reg, int off, int size, 3563 int value_regno, int insn_idx) 3564 { 3565 struct bpf_func_state *cur; /* state of the current function */ 3566 int min_off, max_off; 3567 int i, err; 3568 struct bpf_reg_state *value_reg = NULL; 3569 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3570 bool writing_zero = false; 3571 /* set if the fact that we're writing a zero is used to let any 3572 * stack slots remain STACK_ZERO 3573 */ 3574 bool zero_used = false; 3575 3576 cur = env->cur_state->frame[env->cur_state->curframe]; 3577 min_off = reg_smin(ptr_reg) + off; 3578 max_off = reg_smax(ptr_reg) + off + size; 3579 if (value_regno >= 0) 3580 value_reg = &cur->regs[value_regno]; 3581 if ((value_reg && bpf_register_is_null(value_reg)) || 3582 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 3583 writing_zero = true; 3584 3585 for (i = min_off; i < max_off; i++) { 3586 int spi; 3587 3588 spi = bpf_get_spi(i); 3589 err = destroy_if_dynptr_stack_slot(env, state, spi); 3590 if (err) 3591 return err; 3592 } 3593 3594 check_fastcall_stack_contract(env, state, insn_idx, min_off); 3595 /* Variable offset writes destroy any spilled pointers in range. */ 3596 for (i = min_off; i < max_off; i++) { 3597 u8 new_type, *stype; 3598 int slot, spi; 3599 3600 slot = -i - 1; 3601 spi = slot / BPF_REG_SIZE; 3602 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 3603 mark_stack_slot_scratched(env, spi); 3604 3605 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 3606 /* Reject the write if range we may write to has not 3607 * been initialized beforehand. If we didn't reject 3608 * here, the ptr status would be erased below (even 3609 * though not all slots are actually overwritten), 3610 * possibly opening the door to leaks. 3611 * 3612 * We do however catch STACK_INVALID case below, and 3613 * only allow reading possibly uninitialized memory 3614 * later for CAP_PERFMON, as the write may not happen to 3615 * that slot. 3616 */ 3617 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 3618 insn_idx, i); 3619 return -EINVAL; 3620 } 3621 3622 /* If writing_zero and the spi slot contains a spill of value 0, 3623 * maintain the spill type. 3624 */ 3625 if (writing_zero && *stype == STACK_SPILL && 3626 bpf_is_spilled_scalar_reg(&state->stack[spi])) { 3627 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 3628 3629 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 3630 zero_used = true; 3631 continue; 3632 } 3633 } 3634 3635 /* 3636 * Scrub slots if variable-offset stack write goes over spilled pointers. 3637 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT 3638 * and valid program is rejected by check_stack_read_fixed_off() 3639 * with obscure "invalid size of register fill" message. 3640 */ 3641 scrub_special_slot(state, spi); 3642 3643 /* Update the slot type. */ 3644 new_type = STACK_MISC; 3645 if (writing_zero && *stype == STACK_ZERO) { 3646 new_type = STACK_ZERO; 3647 zero_used = true; 3648 } 3649 /* If the slot is STACK_INVALID, we check whether it's OK to 3650 * pretend that it will be initialized by this write. The slot 3651 * might not actually be written to, and so if we mark it as 3652 * initialized future reads might leak uninitialized memory. 3653 * For privileged programs, we will accept such reads to slots 3654 * that may or may not be written because, if we're reject 3655 * them, the error would be too confusing. 3656 * Conservatively, treat STACK_POISON in a similar way. 3657 */ 3658 if ((*stype == STACK_INVALID || *stype == STACK_POISON) && 3659 !env->allow_uninit_stack) { 3660 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 3661 insn_idx, i); 3662 return -EINVAL; 3663 } 3664 *stype = new_type; 3665 } 3666 if (zero_used) { 3667 /* backtracking doesn't work for STACK_ZERO yet. */ 3668 err = mark_chain_precision(env, value_regno); 3669 if (err) 3670 return err; 3671 } 3672 return 0; 3673 } 3674 3675 /* When register 'dst_regno' is assigned some values from stack[min_off, 3676 * max_off), we set the register's type according to the types of the 3677 * respective stack slots. If all the stack values are known to be zeros, then 3678 * so is the destination reg. Otherwise, the register is considered to be 3679 * SCALAR. This function does not deal with register filling; the caller must 3680 * ensure that all spilled registers in the stack range have been marked as 3681 * read. 3682 * 3683 * STACK_SPILL bytes backed by spilled scalar const zeroes are also considered 3684 * zero bytes. In that case, mark the contributing stack slots precise so 3685 * pruning cannot reuse a zero-spill state for a later non-zero spill state. 3686 * 3687 * Returns an error if precision backtracking fails. 3688 */ 3689 static int mark_reg_stack_read(struct bpf_verifier_env *env, 3690 /* func where src register points to */ 3691 struct bpf_func_state *ptr_state, 3692 int min_off, int max_off, int dst_regno) 3693 { 3694 struct bpf_verifier_state *vstate = env->cur_state; 3695 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3696 u64 zero_spill_mask = 0; 3697 int i, slot, spi; 3698 u8 *stype; 3699 int zeros = 0; 3700 3701 for (i = min_off; i < max_off; i++) { 3702 slot = -i - 1; 3703 spi = slot / BPF_REG_SIZE; 3704 mark_stack_slot_scratched(env, spi); 3705 stype = ptr_state->stack[spi].slot_type; 3706 if (stype[slot % BPF_REG_SIZE] == STACK_ZERO) { 3707 zeros++; 3708 continue; 3709 } 3710 if (stype[slot % BPF_REG_SIZE] == STACK_SPILL && 3711 bpf_register_is_null(&ptr_state->stack[spi].spilled_ptr)) { 3712 zero_spill_mask |= 1ull << spi; 3713 zeros++; 3714 continue; 3715 } 3716 break; 3717 } 3718 if (zeros == max_off - min_off) { 3719 /* Any access_size read into register is zero extended, 3720 * so the whole register == const_zero. 3721 */ 3722 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3723 if (zero_spill_mask) { 3724 bpf_bt_set_frame_slot_mask(&env->bt, ptr_state->frameno, zero_spill_mask); 3725 return mark_chain_precision_batch(env, env->cur_state); 3726 } 3727 } else { 3728 /* have read misc data from the stack */ 3729 mark_reg_unknown(env, state->regs, dst_regno); 3730 } 3731 3732 return 0; 3733 } 3734 3735 /* Read the stack at 'off' and put the results into the register indicated by 3736 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 3737 * spilled reg. 3738 * 3739 * 'dst_regno' can be -1, meaning that the read value is not going to a 3740 * register. 3741 * 3742 * The access is assumed to be within the current stack bounds. 3743 */ 3744 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 3745 /* func where src register points to */ 3746 struct bpf_func_state *reg_state, 3747 int off, int size, int dst_regno) 3748 { 3749 struct bpf_verifier_state *vstate = env->cur_state; 3750 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3751 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 3752 struct bpf_reg_state *reg; 3753 u8 *stype, type; 3754 int err; 3755 int insn_flags = INSN_F_STACK_ACCESS; 3756 int hist_spi = spi, hist_frame = reg_state->frameno; 3757 3758 stype = reg_state->stack[spi].slot_type; 3759 reg = ®_state->stack[spi].spilled_ptr; 3760 3761 mark_stack_slot_scratched(env, spi); 3762 check_fastcall_stack_contract(env, state, env->insn_idx, off); 3763 3764 if (bpf_is_spilled_reg(®_state->stack[spi])) { 3765 u8 spill_size = 1; 3766 3767 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 3768 spill_size++; 3769 3770 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 3771 if (reg->type != SCALAR_VALUE) { 3772 verbose_linfo(env, env->insn_idx, "; "); 3773 verbose(env, "invalid size of register fill\n"); 3774 return -EACCES; 3775 } 3776 3777 if (dst_regno < 0) 3778 return 0; 3779 3780 if (size <= spill_size && 3781 bpf_stack_narrow_access_ok(off, size, spill_size)) { 3782 /* The earlier check_reg_arg() has decided the 3783 * subreg_def for this insn. Save it first. 3784 */ 3785 s32 subreg_def = state->regs[dst_regno].subreg_def; 3786 3787 if (env->bpf_capable && size == 4 && spill_size == 4 && 3788 get_reg_width(reg) <= 32) 3789 /* Ensure stack slot has an ID to build a relation 3790 * with the destination register on fill. 3791 */ 3792 assign_scalar_id_before_mov(env, reg); 3793 state->regs[dst_regno] = *reg; 3794 state->regs[dst_regno].subreg_def = subreg_def; 3795 3796 /* Break the relation on a narrowing fill. 3797 * coerce_reg_to_size will adjust the boundaries. 3798 */ 3799 if (get_reg_width(reg) > size * BITS_PER_BYTE) 3800 clear_scalar_id(&state->regs[dst_regno]); 3801 } else { 3802 int spill_cnt = 0, zero_cnt = 0; 3803 3804 for (i = 0; i < size; i++) { 3805 type = stype[(slot - i) % BPF_REG_SIZE]; 3806 if (type == STACK_SPILL) { 3807 spill_cnt++; 3808 continue; 3809 } 3810 if (type == STACK_MISC) 3811 continue; 3812 if (type == STACK_ZERO) { 3813 zero_cnt++; 3814 continue; 3815 } 3816 if (type == STACK_INVALID && env->allow_uninit_stack) 3817 continue; 3818 if (type == STACK_POISON) { 3819 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3820 off, i, size); 3821 } else { 3822 verbose(env, "invalid read from stack off %d+%d size %d\n", 3823 off, i, size); 3824 } 3825 return -EACCES; 3826 } 3827 3828 if (spill_cnt == size && 3829 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 3830 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3831 /* this IS register fill, so keep insn_flags */ 3832 } else if (zero_cnt == size) { 3833 /* similarly to mark_reg_stack_read(), preserve zeroes */ 3834 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3835 insn_flags = 0; /* not restoring original register state */ 3836 } else { 3837 err = mark_reg_stack_read(env, reg_state, off, off + size, 3838 dst_regno); 3839 if (err) 3840 return err; 3841 insn_flags = 0; /* not restoring original register state */ 3842 } 3843 } 3844 } else if (dst_regno >= 0) { 3845 /* restore register state from stack */ 3846 if (env->bpf_capable) 3847 /* Ensure stack slot has an ID to build a relation 3848 * with the destination register on fill. 3849 */ 3850 assign_scalar_id_before_mov(env, reg); 3851 state->regs[dst_regno] = *reg; 3852 /* mark reg as written since spilled pointer state likely 3853 * has its liveness marks cleared by is_state_visited() 3854 * which resets stack/reg liveness for state transitions 3855 */ 3856 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 3857 /* If dst_regno==-1, the caller is asking us whether 3858 * it is acceptable to use this value as a SCALAR_VALUE 3859 * (e.g. for XADD). 3860 * We must not allow unprivileged callers to do that 3861 * with spilled pointers. 3862 */ 3863 verbose(env, "leaking pointer from stack off %d\n", 3864 off); 3865 return -EACCES; 3866 } 3867 } else { 3868 for (i = 0; i < size; i++) { 3869 type = stype[(slot - i) % BPF_REG_SIZE]; 3870 if (type == STACK_MISC) 3871 continue; 3872 if (type == STACK_ZERO) 3873 continue; 3874 if (type == STACK_INVALID && env->allow_uninit_stack) 3875 continue; 3876 if (type == STACK_POISON) { 3877 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3878 off, i, size); 3879 } else { 3880 verbose(env, "invalid read from stack off %d+%d size %d\n", 3881 off, i, size); 3882 } 3883 return -EACCES; 3884 } 3885 if (dst_regno >= 0) { 3886 err = mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3887 if (err) 3888 return err; 3889 } 3890 insn_flags = 0; /* we are not restoring spilled register */ 3891 } 3892 if (insn_flags) 3893 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3894 hist_spi, hist_frame, 0); 3895 return 0; 3896 } 3897 3898 enum bpf_access_src { 3899 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3900 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3901 }; 3902 3903 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3904 argno_t argno, int off, int access_size, 3905 bool zero_size_allowed, 3906 enum bpf_access_type type, 3907 struct bpf_call_arg_meta *meta); 3908 3909 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3910 { 3911 return cur_regs(env) + regno; 3912 } 3913 3914 /* Read the stack at 'reg + off' and put the result into the register 3915 * 'dst_regno'. 3916 * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'), 3917 * but not its variable offset. 3918 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3919 * 3920 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3921 * filling registers (i.e. reads of spilled register cannot be detected when 3922 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3923 * SCALAR_VALUE. That's why we assert that the 'reg' has a variable 3924 * offset; for a fixed offset check_stack_read_fixed_off should be used 3925 * instead. 3926 */ 3927 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3928 argno_t ptr_argno, int off, int size, int dst_regno) 3929 { 3930 struct bpf_func_state *ptr_state = bpf_func(env, reg); 3931 int err; 3932 int min_off, max_off; 3933 3934 /* Note that we pass a NULL meta, so raw access will not be permitted. 3935 */ 3936 err = check_stack_range_initialized(env, reg, ptr_argno, off, size, 3937 false, BPF_READ, NULL); 3938 if (err) 3939 return err; 3940 3941 min_off = reg_smin(reg) + off; 3942 max_off = reg_smax(reg) + off; 3943 err = mark_reg_stack_read(env, ptr_state, min_off, max_off + size, 3944 dst_regno); 3945 if (err) 3946 return err; 3947 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 3948 return 0; 3949 } 3950 3951 /* check_stack_read dispatches to check_stack_read_fixed_off or 3952 * check_stack_read_var_off. 3953 * 3954 * The caller must ensure that the offset falls within the allocated stack 3955 * bounds. 3956 * 3957 * 'dst_regno' is a register which will receive the value from the stack. It 3958 * can be -1, meaning that the read value is not going to a register. 3959 */ 3960 static int check_stack_read(struct bpf_verifier_env *env, 3961 struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size, 3962 int dst_regno) 3963 { 3964 struct bpf_func_state *state = bpf_func(env, reg); 3965 int err; 3966 /* Some accesses are only permitted with a static offset. */ 3967 bool var_off = !tnum_is_const(reg->var_off); 3968 3969 /* The offset is required to be static when reads don't go to a 3970 * register, in order to not leak pointers (see 3971 * check_stack_read_fixed_off). 3972 */ 3973 if (dst_regno < 0 && var_off) { 3974 char tn_buf[48]; 3975 3976 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3977 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 3978 tn_buf, off, size); 3979 return -EACCES; 3980 } 3981 /* Variable offset is prohibited for unprivileged mode for simplicity 3982 * since it requires corresponding support in Spectre masking for stack 3983 * ALU. See also retrieve_ptr_limit(). The check in 3984 * check_stack_access_for_ptr_arithmetic() called by 3985 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 3986 * with variable offsets, therefore no check is required here. Further, 3987 * just checking it here would be insufficient as speculative stack 3988 * writes could still lead to unsafe speculative behaviour. 3989 */ 3990 if (!var_off) { 3991 off += reg->var_off.value; 3992 err = check_stack_read_fixed_off(env, state, off, size, 3993 dst_regno); 3994 } else { 3995 /* Variable offset stack reads need more conservative handling 3996 * than fixed offset ones. Note that dst_regno >= 0 on this 3997 * branch. 3998 */ 3999 err = check_stack_read_var_off(env, reg, ptr_argno, off, size, 4000 dst_regno); 4001 } 4002 return err; 4003 } 4004 4005 4006 /* check_stack_write dispatches to check_stack_write_fixed_off or 4007 * check_stack_write_var_off. 4008 * 4009 * 'reg' is the register used as a pointer into the stack. 4010 * 'value_regno' is the register whose value we're writing to the stack. It can 4011 * be -1, meaning that we're not writing from a register. 4012 * 4013 * The caller must ensure that the offset falls within the maximum stack size. 4014 */ 4015 static int check_stack_write(struct bpf_verifier_env *env, 4016 struct bpf_reg_state *reg, int off, int size, 4017 int value_regno, int insn_idx) 4018 { 4019 struct bpf_func_state *state = bpf_func(env, reg); 4020 int err; 4021 4022 if (tnum_is_const(reg->var_off)) { 4023 off += reg->var_off.value; 4024 err = check_stack_write_fixed_off(env, state, off, size, 4025 value_regno, insn_idx); 4026 } else { 4027 /* Variable offset stack reads need more conservative handling 4028 * than fixed offset ones. 4029 */ 4030 err = check_stack_write_var_off(env, state, 4031 reg, off, size, 4032 value_regno, insn_idx); 4033 } 4034 return err; 4035 } 4036 4037 /* 4038 * Write a value to the outgoing stack arg area. 4039 * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7). 4040 */ 4041 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state, 4042 int off, struct bpf_reg_state *value_reg) 4043 { 4044 int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS; 4045 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4046 int spi = -off / BPF_REG_SIZE - 1; 4047 struct bpf_reg_state *arg; 4048 int err; 4049 4050 if (spi >= max_stack_arg_regs) { 4051 verbose(env, "stack arg write offset %d exceeds max %d stack args\n", 4052 off, max_stack_arg_regs); 4053 return -EINVAL; 4054 } 4055 4056 err = grow_stack_arg_slots(env, state, spi + 1); 4057 if (err) 4058 return err; 4059 4060 /* Track the max outgoing stack arg slot count. */ 4061 if (spi + 1 > subprog->max_out_stack_arg_cnt) 4062 subprog->max_out_stack_arg_cnt = spi + 1; 4063 4064 if (value_reg) { 4065 state->stack_arg_regs[spi] = *value_reg; 4066 } else { 4067 /* BPF_ST: store immediate, treat as scalar */ 4068 arg = &state->stack_arg_regs[spi]; 4069 arg->type = SCALAR_VALUE; 4070 __mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm); 4071 } 4072 state->no_stack_arg_load = true; 4073 return bpf_push_jmp_history(env, env->cur_state, 4074 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4075 } 4076 4077 /* 4078 * Read a value from the incoming stack arg area. 4079 * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7). 4080 */ 4081 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state, 4082 int off, int dst_regno) 4083 { 4084 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4085 struct bpf_verifier_state *vstate = env->cur_state; 4086 int spi = off / BPF_REG_SIZE - 1; 4087 struct bpf_func_state *caller, *cur; 4088 struct bpf_reg_state *arg; 4089 4090 if (state->no_stack_arg_load) { 4091 verbose(env, "r11 load must be before any r11 store or call insn\n"); 4092 return -EINVAL; 4093 } 4094 4095 if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) { 4096 verbose(env, "invalid read from stack arg off %d depth %d\n", 4097 off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE); 4098 return -EACCES; 4099 } 4100 4101 caller = vstate->frame[vstate->curframe - 1]; 4102 arg = &caller->stack_arg_regs[spi]; 4103 cur = vstate->frame[vstate->curframe]; 4104 cur->regs[dst_regno] = *arg; 4105 return bpf_push_jmp_history(env, env->cur_state, 4106 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4107 } 4108 4109 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx) 4110 { 4111 struct bpf_func_state *caller = cur_func(env); 4112 int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS; 4113 4114 bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi); 4115 return mark_chain_precision_batch(env, env->cur_state); 4116 } 4117 4118 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller, 4119 int nargs) 4120 { 4121 int i, spi; 4122 4123 for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) { 4124 spi = i - MAX_BPF_FUNC_REG_ARGS; 4125 if (spi >= caller->out_stack_arg_cnt || 4126 caller->stack_arg_regs[spi].type == NOT_INIT) { 4127 verbose(env, "callee expects %d args, stack arg%d is not initialized\n", 4128 nargs, spi + 1); 4129 return -EFAULT; 4130 } 4131 } 4132 4133 return 0; 4134 } 4135 4136 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller, 4137 struct bpf_reg_state *regs, int arg) 4138 { 4139 if (arg < MAX_BPF_FUNC_REG_ARGS) 4140 return ®s[arg + 1]; 4141 4142 return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS]; 4143 } 4144 4145 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4146 int off, int size, enum bpf_access_type type) 4147 { 4148 struct bpf_map *map = reg->map_ptr; 4149 u32 cap = bpf_map_flags_to_cap(map); 4150 4151 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4152 verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n", 4153 map->value_size, reg_smin(reg) + off, size); 4154 return -EACCES; 4155 } 4156 4157 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4158 verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n", 4159 map->value_size, reg_smin(reg) + off, size); 4160 return -EACCES; 4161 } 4162 4163 return 0; 4164 } 4165 4166 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4167 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4168 int off, int size, u32 mem_size, 4169 bool zero_size_allowed) 4170 { 4171 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4172 4173 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4174 return 0; 4175 4176 switch (reg->type) { 4177 case PTR_TO_MAP_KEY: 4178 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4179 mem_size, off, size); 4180 break; 4181 case PTR_TO_MAP_VALUE: 4182 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4183 mem_size, off, size); 4184 break; 4185 case PTR_TO_PACKET: 4186 case PTR_TO_PACKET_META: 4187 case PTR_TO_PACKET_END: 4188 verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n", 4189 off, size, reg_arg_name(env, argno), reg->id, off, mem_size); 4190 break; 4191 case PTR_TO_CTX: 4192 verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n", 4193 mem_size, off, size); 4194 break; 4195 case PTR_TO_MEM: 4196 default: 4197 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4198 mem_size, off, size); 4199 } 4200 4201 return -EACCES; 4202 } 4203 4204 /* check read/write into a memory region with possible variable offset */ 4205 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4206 int off, int size, u32 mem_size, 4207 bool zero_size_allowed) 4208 { 4209 int err; 4210 4211 /* We may have adjusted the register pointing to memory region, so we 4212 * need to try adding each of min_value and max_value to off 4213 * to make sure our theoretical access will be safe. 4214 * 4215 * The minimum value is only important with signed 4216 * comparisons where we can't assume the floor of a 4217 * value is 0. If we are using signed variables for our 4218 * index'es we need to make sure that whatever we use 4219 * will have a set floor within our range. 4220 */ 4221 if (reg_smin(reg) < 0 && 4222 (reg_smin(reg) == S64_MIN || 4223 (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) || 4224 reg_smin(reg) + off < 0)) { 4225 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4226 reg_arg_name(env, argno)); 4227 return -EACCES; 4228 } 4229 err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size, 4230 mem_size, zero_size_allowed); 4231 if (err) { 4232 verbose(env, "%s min value is outside of the allowed memory range\n", 4233 reg_arg_name(env, argno)); 4234 return err; 4235 } 4236 4237 /* If we haven't set a max value then we need to bail since we can't be 4238 * sure we won't do bad things. 4239 * If reg_umax(reg) + off could overflow, treat that as unbounded too. 4240 */ 4241 if (reg_umax(reg) >= BPF_MAX_VAR_OFF) { 4242 verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n", 4243 reg_arg_name(env, argno)); 4244 return -EACCES; 4245 } 4246 err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size, 4247 mem_size, zero_size_allowed); 4248 if (err) { 4249 verbose(env, "%s max value is outside of the allowed memory range\n", 4250 reg_arg_name(env, argno)); 4251 return err; 4252 } 4253 4254 return 0; 4255 } 4256 4257 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4258 const struct bpf_reg_state *reg, argno_t argno, 4259 bool fixed_off_ok) 4260 { 4261 /* Access to this pointer-typed register or passing it to a helper 4262 * is only allowed in its original, unmodified form. 4263 */ 4264 4265 if (!tnum_is_const(reg->var_off)) { 4266 char tn_buf[48]; 4267 4268 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4269 verbose(env, "variable %s access var_off=%s disallowed\n", 4270 reg_type_str(env, reg->type), tn_buf); 4271 return -EACCES; 4272 } 4273 4274 if (reg_smin(reg) < 0) { 4275 verbose(env, "negative offset %s ptr %s off=%lld disallowed\n", 4276 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4277 return -EACCES; 4278 } 4279 4280 if (!fixed_off_ok && reg->var_off.value != 0) { 4281 verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n", 4282 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4283 return -EACCES; 4284 } 4285 4286 return 0; 4287 } 4288 4289 static int check_ptr_off_reg(struct bpf_verifier_env *env, 4290 const struct bpf_reg_state *reg, int regno) 4291 { 4292 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 4293 } 4294 4295 static int map_kptr_match_type(struct bpf_verifier_env *env, 4296 struct btf_field *kptr_field, 4297 struct bpf_reg_state *reg, u32 regno) 4298 { 4299 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4300 int perm_flags; 4301 const char *reg_name = ""; 4302 4303 if (base_type(reg->type) != PTR_TO_BTF_ID) 4304 goto bad_type; 4305 4306 if (btf_is_kernel(reg->btf)) { 4307 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 4308 4309 /* Only unreferenced case accepts untrusted pointers */ 4310 if (kptr_field->type == BPF_KPTR_UNREF) 4311 perm_flags |= PTR_UNTRUSTED; 4312 } else { 4313 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 4314 if (kptr_field->type == BPF_KPTR_PERCPU) 4315 perm_flags |= MEM_PERCPU; 4316 } 4317 4318 if (type_flag(reg->type) & ~perm_flags) 4319 goto bad_type; 4320 4321 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4322 reg_name = btf_type_name(reg->btf, reg->btf_id); 4323 4324 /* For ref_ptr case, release function check should ensure we get one 4325 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4326 * normal store of unreferenced kptr, we must ensure var_off is zero. 4327 * Since ref_ptr cannot be accessed directly by BPF insns, check for 4328 * reg->id is not needed here. 4329 */ 4330 if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true)) 4331 return -EACCES; 4332 4333 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 4334 * we also need to take into account the reg->var_off. 4335 * 4336 * We want to support cases like: 4337 * 4338 * struct foo { 4339 * struct bar br; 4340 * struct baz bz; 4341 * }; 4342 * 4343 * struct foo *v; 4344 * v = func(); // PTR_TO_BTF_ID 4345 * val->foo = v; // reg->var_off is zero, btf and btf_id match type 4346 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with 4347 * // first member type of struct after comparison fails 4348 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked 4349 * // to match type 4350 * 4351 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off 4352 * is zero. We must also ensure that btf_struct_ids_match does not walk 4353 * the struct to match type against first member of struct, i.e. reject 4354 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4355 * strict mode to true for type match. 4356 */ 4357 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value, 4358 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4359 kptr_field->type != BPF_KPTR_UNREF, 4360 !type_is_alloc(reg->type))) 4361 goto bad_type; 4362 return 0; 4363 bad_type: 4364 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4365 reg_type_str(env, reg->type), reg_name); 4366 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4367 if (kptr_field->type == BPF_KPTR_UNREF) 4368 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4369 targ_name); 4370 else 4371 verbose(env, "\n"); 4372 return -EINVAL; 4373 } 4374 4375 static bool in_sleepable(struct bpf_verifier_env *env) 4376 { 4377 return env->cur_state->in_sleepable; 4378 } 4379 4380 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 4381 * can dereference RCU protected pointers and result is PTR_TRUSTED. 4382 */ 4383 static bool in_rcu_cs(struct bpf_verifier_env *env) 4384 { 4385 return env->cur_state->active_rcu_locks || 4386 env->cur_state->active_locks || 4387 !in_sleepable(env); 4388 } 4389 4390 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 4391 BTF_SET_START(rcu_protected_types) 4392 #ifdef CONFIG_NET 4393 BTF_ID(struct, prog_test_ref_kfunc) 4394 #endif 4395 #ifdef CONFIG_CGROUPS 4396 BTF_ID(struct, cgroup) 4397 #endif 4398 #ifdef CONFIG_BPF_JIT 4399 BTF_ID(struct, bpf_cpumask) 4400 #endif 4401 BTF_ID(struct, task_struct) 4402 #ifdef CONFIG_CRYPTO 4403 BTF_ID(struct, bpf_crypto_ctx) 4404 #endif 4405 BTF_SET_END(rcu_protected_types) 4406 4407 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 4408 { 4409 if (!btf_is_kernel(btf)) 4410 return true; 4411 return btf_id_set_contains(&rcu_protected_types, btf_id); 4412 } 4413 4414 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 4415 { 4416 struct btf_struct_meta *meta; 4417 4418 if (btf_is_kernel(kptr_field->kptr.btf)) 4419 return NULL; 4420 4421 meta = btf_find_struct_meta(kptr_field->kptr.btf, 4422 kptr_field->kptr.btf_id); 4423 4424 return meta ? meta->record : NULL; 4425 } 4426 4427 static bool rcu_safe_kptr(const struct btf_field *field) 4428 { 4429 const struct btf_field_kptr *kptr = &field->kptr; 4430 4431 return field->type == BPF_KPTR_PERCPU || 4432 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 4433 } 4434 4435 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 4436 { 4437 struct btf_record *rec; 4438 u32 ret; 4439 4440 ret = PTR_MAYBE_NULL; 4441 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 4442 ret |= MEM_RCU; 4443 if (kptr_field->type == BPF_KPTR_PERCPU) 4444 ret |= MEM_PERCPU; 4445 else if (!btf_is_kernel(kptr_field->kptr.btf)) 4446 ret |= MEM_ALLOC; 4447 4448 rec = kptr_pointee_btf_record(kptr_field); 4449 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 4450 ret |= NON_OWN_REF; 4451 } else { 4452 ret |= PTR_UNTRUSTED; 4453 } 4454 4455 return ret; 4456 } 4457 4458 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 4459 struct btf_field *field) 4460 { 4461 struct bpf_reg_state *reg; 4462 const struct btf_type *t; 4463 4464 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 4465 mark_reg_known_zero(env, cur_regs(env), regno); 4466 reg = reg_state(env, regno); 4467 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 4468 reg->mem_size = t->size; 4469 reg->id = ++env->id_gen; 4470 4471 return 0; 4472 } 4473 4474 static int check_map_kptr_access(struct bpf_verifier_env *env, 4475 int value_regno, int insn_idx, 4476 struct btf_field *kptr_field) 4477 { 4478 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4479 int class = BPF_CLASS(insn->code); 4480 struct bpf_reg_state *val_reg; 4481 int ret; 4482 4483 /* Things we already checked for in check_map_access and caller: 4484 * - Reject cases where variable offset may touch kptr 4485 * - size of access (must be BPF_DW) 4486 * - tnum_is_const(reg->var_off) 4487 * - kptr_field->offset == off + reg->var_off.value 4488 */ 4489 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4490 if (BPF_MODE(insn->code) != BPF_MEM) { 4491 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4492 return -EACCES; 4493 } 4494 4495 /* We only allow loading referenced kptr, since it will be marked as 4496 * untrusted, similar to unreferenced kptr. 4497 */ 4498 if (class != BPF_LDX && 4499 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 4500 verbose(env, "store to referenced kptr disallowed\n"); 4501 return -EACCES; 4502 } 4503 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 4504 verbose(env, "store to uptr disallowed\n"); 4505 return -EACCES; 4506 } 4507 4508 if (class == BPF_LDX) { 4509 if (kptr_field->type == BPF_UPTR) 4510 return mark_uptr_ld_reg(env, value_regno, kptr_field); 4511 4512 /* We can simply mark the value_regno receiving the pointer 4513 * value from map as PTR_TO_BTF_ID, with the correct type. 4514 */ 4515 ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, 4516 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4517 btf_ld_kptr_type(env, kptr_field)); 4518 if (ret < 0) 4519 return ret; 4520 } else if (class == BPF_STX) { 4521 val_reg = reg_state(env, value_regno); 4522 if (!bpf_register_is_null(val_reg) && 4523 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4524 return -EACCES; 4525 } else if (class == BPF_ST) { 4526 if (insn->imm) { 4527 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4528 kptr_field->offset); 4529 return -EACCES; 4530 } 4531 } else { 4532 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4533 return -EACCES; 4534 } 4535 return 0; 4536 } 4537 4538 /* 4539 * Return the size of the memory region accessible from a pointer to map value. 4540 * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible. 4541 */ 4542 static u32 map_mem_size(const struct bpf_map *map) 4543 { 4544 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) 4545 return map->max_entries * sizeof(long); 4546 4547 return map->value_size; 4548 } 4549 4550 /* check read/write into a map element with possible variable offset */ 4551 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4552 int off, int size, bool zero_size_allowed, 4553 enum bpf_access_src src) 4554 { 4555 struct bpf_map *map = reg->map_ptr; 4556 u32 mem_size = map_mem_size(map); 4557 struct btf_record *rec; 4558 int err, i; 4559 4560 err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed); 4561 if (err) 4562 return err; 4563 4564 if (IS_ERR_OR_NULL(map->record)) 4565 return 0; 4566 rec = map->record; 4567 for (i = 0; i < rec->cnt; i++) { 4568 struct btf_field *field = &rec->fields[i]; 4569 u32 p = field->offset; 4570 4571 /* If any part of a field can be touched by load/store, reject 4572 * this program. To check that [x1, x2) overlaps with [y1, y2), 4573 * it is sufficient to check x1 < y2 && y1 < x2. 4574 */ 4575 if (reg_smin(reg) + off < p + field->size && 4576 p < reg_umax(reg) + off + size) { 4577 switch (field->type) { 4578 case BPF_KPTR_UNREF: 4579 case BPF_KPTR_REF: 4580 case BPF_KPTR_PERCPU: 4581 case BPF_UPTR: 4582 if (src != ACCESS_DIRECT) { 4583 verbose(env, "%s cannot be accessed indirectly by helper\n", 4584 btf_field_type_name(field->type)); 4585 return -EACCES; 4586 } 4587 if (!tnum_is_const(reg->var_off)) { 4588 verbose(env, "%s access cannot have variable offset\n", 4589 btf_field_type_name(field->type)); 4590 return -EACCES; 4591 } 4592 if (p != off + reg->var_off.value) { 4593 verbose(env, "%s access misaligned expected=%u off=%llu\n", 4594 btf_field_type_name(field->type), 4595 p, off + reg->var_off.value); 4596 return -EACCES; 4597 } 4598 if (size != bpf_size_to_bytes(BPF_DW)) { 4599 verbose(env, "%s access size must be BPF_DW\n", 4600 btf_field_type_name(field->type)); 4601 return -EACCES; 4602 } 4603 break; 4604 default: 4605 verbose(env, "%s cannot be accessed directly by load/store\n", 4606 btf_field_type_name(field->type)); 4607 return -EACCES; 4608 } 4609 } 4610 } 4611 return 0; 4612 } 4613 4614 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4615 const struct bpf_call_arg_meta *meta, 4616 enum bpf_access_type t) 4617 { 4618 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4619 4620 switch (prog_type) { 4621 /* Program types only with direct read access go here! */ 4622 case BPF_PROG_TYPE_LWT_IN: 4623 case BPF_PROG_TYPE_LWT_OUT: 4624 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4625 case BPF_PROG_TYPE_SK_REUSEPORT: 4626 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4627 case BPF_PROG_TYPE_CGROUP_SKB: 4628 if (t == BPF_WRITE) 4629 return false; 4630 fallthrough; 4631 4632 /* Program types with direct read + write access go here! */ 4633 case BPF_PROG_TYPE_SCHED_CLS: 4634 case BPF_PROG_TYPE_SCHED_ACT: 4635 case BPF_PROG_TYPE_XDP: 4636 case BPF_PROG_TYPE_LWT_XMIT: 4637 case BPF_PROG_TYPE_SK_SKB: 4638 case BPF_PROG_TYPE_SK_MSG: 4639 if (meta) 4640 return meta->pkt_access; 4641 4642 env->seen_direct_write = true; 4643 return true; 4644 4645 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4646 if (t == BPF_WRITE) 4647 env->seen_direct_write = true; 4648 4649 return true; 4650 4651 default: 4652 return false; 4653 } 4654 } 4655 4656 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 4657 int size, bool zero_size_allowed) 4658 { 4659 int err; 4660 4661 if (reg->range < 0) { 4662 verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno)); 4663 return -EINVAL; 4664 } 4665 4666 err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed); 4667 if (err) 4668 return err; 4669 4670 /* __check_mem_access has made sure "off + size - 1" is within u16. 4671 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff, 4672 * otherwise find_good_pkt_pointers would have refused to set range info 4673 * that __check_mem_access would have rejected this pkt access. 4674 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32. 4675 */ 4676 env->prog->aux->max_pkt_offset = 4677 max_t(u32, env->prog->aux->max_pkt_offset, 4678 off + reg_umax(reg) + size - 1); 4679 4680 return 0; 4681 } 4682 4683 static bool is_var_ctx_off_allowed(struct bpf_prog *prog) 4684 { 4685 return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL; 4686 } 4687 4688 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 4689 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 4690 enum bpf_access_type t, struct bpf_insn_access_aux *info) 4691 { 4692 if (env->ops->is_valid_access && 4693 env->ops->is_valid_access(off, size, t, env->prog, info)) { 4694 /* A non zero info.ctx_field_size indicates that this field is a 4695 * candidate for later verifier transformation to load the whole 4696 * field and then apply a mask when accessed with a narrower 4697 * access than actual ctx access size. A zero info.ctx_field_size 4698 * will only allow for whole field access and rejects any other 4699 * type of narrower access. 4700 */ 4701 if (base_type(info->reg_type) == PTR_TO_BTF_ID) { 4702 if (info->ref_id && 4703 !find_reference_state(env->cur_state, info->ref_id)) { 4704 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n", 4705 off); 4706 return -EACCES; 4707 } 4708 } else { 4709 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size; 4710 } 4711 /* remember the offset of last byte accessed in ctx */ 4712 if (env->prog->aux->max_ctx_offset < off + size) 4713 env->prog->aux->max_ctx_offset = off + size; 4714 return 0; 4715 } 4716 4717 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 4718 return -EACCES; 4719 } 4720 4721 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 4722 int off, int access_size, enum bpf_access_type t, 4723 struct bpf_insn_access_aux *info) 4724 { 4725 /* 4726 * Program types that don't rewrite ctx accesses can safely 4727 * dereference ctx pointers with fixed offsets. 4728 */ 4729 bool var_off_ok = is_var_ctx_off_allowed(env->prog); 4730 bool fixed_off_ok = !env->ops->convert_ctx_access; 4731 int err; 4732 4733 if (var_off_ok) 4734 err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false); 4735 else 4736 err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok); 4737 if (err) 4738 return err; 4739 off += reg_umax(reg); 4740 4741 err = __check_ctx_access(env, insn_idx, off, access_size, t, info); 4742 if (err) 4743 verbose_linfo(env, insn_idx, "; "); 4744 return err; 4745 } 4746 4747 static int check_flow_keys_access(struct bpf_verifier_env *env, 4748 struct bpf_reg_state *reg, argno_t argno, 4749 int off, int size) 4750 { 4751 /* Only a constant offset is allowed here; fold it into off. */ 4752 if (!tnum_is_const(reg->var_off)) { 4753 char tn_buf[48]; 4754 4755 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4756 verbose(env, "%s invalid variable offset to flow keys: off=%d, var_off=%s\n", 4757 reg_arg_name(env, argno), off, tn_buf); 4758 return -EACCES; 4759 } 4760 off += reg->var_off.value; 4761 4762 if (size < 0 || off < 0 || 4763 (u64)off + size > sizeof(struct bpf_flow_keys)) { 4764 verbose(env, "invalid access to flow keys off=%d size=%d\n", 4765 off, size); 4766 return -EACCES; 4767 } 4768 return 0; 4769 } 4770 4771 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 4772 struct bpf_reg_state *reg, argno_t argno, int off, int size, 4773 enum bpf_access_type t) 4774 { 4775 struct bpf_insn_access_aux info = {}; 4776 bool valid; 4777 4778 if (reg_smin(reg) < 0) { 4779 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4780 reg_arg_name(env, argno)); 4781 return -EACCES; 4782 } 4783 4784 switch (reg->type) { 4785 case PTR_TO_SOCK_COMMON: 4786 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 4787 break; 4788 case PTR_TO_SOCKET: 4789 valid = bpf_sock_is_valid_access(off, size, t, &info); 4790 break; 4791 case PTR_TO_TCP_SOCK: 4792 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 4793 break; 4794 case PTR_TO_XDP_SOCK: 4795 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 4796 break; 4797 default: 4798 valid = false; 4799 } 4800 4801 4802 if (valid) { 4803 env->insn_aux_data[insn_idx].ctx_field_size = 4804 info.ctx_field_size; 4805 return 0; 4806 } 4807 4808 verbose(env, "%s invalid %s access off=%d size=%d\n", 4809 reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size); 4810 4811 return -EACCES; 4812 } 4813 4814 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 4815 { 4816 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 4817 } 4818 4819 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 4820 { 4821 const struct bpf_reg_state *reg = reg_state(env, regno); 4822 4823 return reg->type == PTR_TO_CTX; 4824 } 4825 4826 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 4827 { 4828 const struct bpf_reg_state *reg = reg_state(env, regno); 4829 4830 return type_is_sk_pointer(reg->type); 4831 } 4832 4833 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 4834 { 4835 const struct bpf_reg_state *reg = reg_state(env, regno); 4836 4837 return type_is_pkt_pointer(reg->type); 4838 } 4839 4840 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 4841 { 4842 const struct bpf_reg_state *reg = reg_state(env, regno); 4843 4844 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 4845 return reg->type == PTR_TO_FLOW_KEYS; 4846 } 4847 4848 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 4849 { 4850 const struct bpf_reg_state *reg = reg_state(env, regno); 4851 4852 return reg->type == PTR_TO_ARENA; 4853 } 4854 4855 /* Return false if @regno contains a pointer whose type isn't supported for 4856 * atomic instruction @insn. 4857 */ 4858 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno, 4859 struct bpf_insn *insn) 4860 { 4861 if (is_ctx_reg(env, regno)) 4862 return false; 4863 if (is_pkt_reg(env, regno)) 4864 return false; 4865 if (is_flow_key_reg(env, regno)) 4866 return false; 4867 if (is_sk_reg(env, regno)) 4868 return false; 4869 if (is_arena_reg(env, regno)) 4870 return bpf_jit_supports_insn(insn, true); 4871 4872 return true; 4873 } 4874 4875 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 4876 #ifdef CONFIG_NET 4877 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 4878 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 4879 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 4880 #endif 4881 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 4882 }; 4883 4884 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 4885 { 4886 /* A referenced register is always trusted. */ 4887 if (reg_is_referenced(env, reg)) 4888 return true; 4889 4890 /* Types listed in the reg2btf_ids are always trusted */ 4891 if (reg2btf_ids[base_type(reg->type)] && 4892 !bpf_type_has_unsafe_modifiers(reg->type)) 4893 return true; 4894 4895 /* If a register is not referenced, it is trusted if it has the 4896 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 4897 * other type modifiers may be safe, but we elect to take an opt-in 4898 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 4899 * not. 4900 * 4901 * Eventually, we should make PTR_TRUSTED the single source of truth 4902 * for whether a register is trusted. 4903 */ 4904 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 4905 !bpf_type_has_unsafe_modifiers(reg->type); 4906 } 4907 4908 static bool is_rcu_reg(const struct bpf_reg_state *reg) 4909 { 4910 return reg->type & MEM_RCU; 4911 } 4912 4913 static void clear_trusted_flags(enum bpf_type_flag *flag) 4914 { 4915 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 4916 } 4917 4918 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 4919 const struct bpf_reg_state *reg, 4920 int off, int size, bool strict) 4921 { 4922 struct tnum reg_off; 4923 int ip_align; 4924 4925 /* Byte size accesses are always allowed. */ 4926 if (!strict || size == 1) 4927 return 0; 4928 4929 /* For platforms that do not have a Kconfig enabling 4930 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 4931 * NET_IP_ALIGN is universally set to '2'. And on platforms 4932 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 4933 * to this code only in strict mode where we want to emulate 4934 * the NET_IP_ALIGN==2 checking. Therefore use an 4935 * unconditional IP align value of '2'. 4936 */ 4937 ip_align = 2; 4938 4939 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off)); 4940 if (!tnum_is_aligned(reg_off, size)) { 4941 char tn_buf[48]; 4942 4943 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4944 verbose(env, 4945 "misaligned packet access off %d+%s+%d size %d\n", 4946 ip_align, tn_buf, off, size); 4947 return -EACCES; 4948 } 4949 4950 return 0; 4951 } 4952 4953 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 4954 const struct bpf_reg_state *reg, 4955 const char *pointer_desc, 4956 int off, int size, bool strict) 4957 { 4958 struct tnum reg_off; 4959 4960 /* Byte size accesses are always allowed. */ 4961 if (!strict || size == 1) 4962 return 0; 4963 4964 reg_off = tnum_add(reg->var_off, tnum_const(off)); 4965 if (!tnum_is_aligned(reg_off, size)) { 4966 char tn_buf[48]; 4967 4968 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4969 verbose(env, "misaligned %saccess off %s+%d size %d\n", 4970 pointer_desc, tn_buf, off, size); 4971 return -EACCES; 4972 } 4973 4974 return 0; 4975 } 4976 4977 static int check_ptr_alignment(struct bpf_verifier_env *env, 4978 const struct bpf_reg_state *reg, int off, 4979 int size, bool strict_alignment_once) 4980 { 4981 bool strict = env->strict_alignment || strict_alignment_once; 4982 const char *pointer_desc = ""; 4983 4984 switch (reg->type) { 4985 case PTR_TO_PACKET: 4986 case PTR_TO_PACKET_META: 4987 /* Special case, because of NET_IP_ALIGN. Given metadata sits 4988 * right in front, treat it the very same way. 4989 */ 4990 return check_pkt_ptr_alignment(env, reg, off, size, strict); 4991 case PTR_TO_FLOW_KEYS: 4992 pointer_desc = "flow keys "; 4993 break; 4994 case PTR_TO_MAP_KEY: 4995 pointer_desc = "key "; 4996 break; 4997 case PTR_TO_MAP_VALUE: 4998 pointer_desc = "value "; 4999 if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY) 5000 strict = true; 5001 break; 5002 case PTR_TO_CTX: 5003 pointer_desc = "context "; 5004 break; 5005 case PTR_TO_STACK: 5006 pointer_desc = "stack "; 5007 /* The stack spill tracking logic in check_stack_write_fixed_off() 5008 * and check_stack_read_fixed_off() relies on stack accesses being 5009 * aligned. 5010 */ 5011 strict = true; 5012 break; 5013 case PTR_TO_SOCKET: 5014 pointer_desc = "sock "; 5015 break; 5016 case PTR_TO_SOCK_COMMON: 5017 pointer_desc = "sock_common "; 5018 break; 5019 case PTR_TO_TCP_SOCK: 5020 pointer_desc = "tcp_sock "; 5021 break; 5022 case PTR_TO_XDP_SOCK: 5023 pointer_desc = "xdp_sock "; 5024 break; 5025 case PTR_TO_ARENA: 5026 return 0; 5027 default: 5028 break; 5029 } 5030 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5031 strict); 5032 } 5033 5034 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 5035 { 5036 if (!bpf_jit_supports_private_stack()) 5037 return NO_PRIV_STACK; 5038 5039 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 5040 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 5041 * explicitly. 5042 */ 5043 switch (prog->type) { 5044 case BPF_PROG_TYPE_KPROBE: 5045 case BPF_PROG_TYPE_TRACEPOINT: 5046 case BPF_PROG_TYPE_PERF_EVENT: 5047 case BPF_PROG_TYPE_RAW_TRACEPOINT: 5048 return PRIV_STACK_ADAPTIVE; 5049 case BPF_PROG_TYPE_TRACING: 5050 case BPF_PROG_TYPE_LSM: 5051 case BPF_PROG_TYPE_STRUCT_OPS: 5052 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 5053 return PRIV_STACK_ADAPTIVE; 5054 fallthrough; 5055 default: 5056 break; 5057 } 5058 5059 return NO_PRIV_STACK; 5060 } 5061 5062 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5063 { 5064 if (env->prog->jit_requested) 5065 return round_up(stack_depth, 16); 5066 5067 /* round up to 32-bytes, since this is granularity 5068 * of interpreter stack size 5069 */ 5070 return round_up(max_t(u32, stack_depth, 1), 32); 5071 } 5072 5073 /* temporary state used for call frame depth calculation */ 5074 struct bpf_subprog_call_depth_info { 5075 int ret_insn; /* caller instruction where we return to. */ 5076 int caller; /* caller subprogram idx */ 5077 int frame; /* # of consecutive static call stack frames on top of stack */ 5078 }; 5079 5080 /* starting from main bpf function walk all instructions of the function 5081 * and recursively walk all callees that given function can call. 5082 * Ignore jump and exit insns. 5083 */ 5084 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 5085 struct bpf_subprog_call_depth_info *dinfo, 5086 bool priv_stack_supported) 5087 { 5088 struct bpf_subprog_info *subprog = env->subprog_info; 5089 struct bpf_insn *insn = env->prog->insnsi; 5090 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 5091 bool tail_call_reachable = false; 5092 int total; 5093 int tmp; 5094 5095 /* no caller idx */ 5096 dinfo[idx].caller = -1; 5097 5098 i = subprog[idx].start; 5099 if (!priv_stack_supported) 5100 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5101 process_func: 5102 /* protect against potential stack overflow that might happen when 5103 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5104 * depth for such case down to 256 so that the worst case scenario 5105 * would result in 8k stack size (32 which is tailcall limit * 256 = 5106 * 8k). 5107 * 5108 * To get the idea what might happen, see an example: 5109 * func1 -> sub rsp, 128 5110 * subfunc1 -> sub rsp, 256 5111 * tailcall1 -> add rsp, 256 5112 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5113 * subfunc2 -> sub rsp, 64 5114 * subfunc22 -> sub rsp, 128 5115 * tailcall2 -> add rsp, 128 5116 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5117 * 5118 * tailcall will unwind the current stack frame but it will not get rid 5119 * of caller's stack as shown on the example above. 5120 */ 5121 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5122 verbose(env, 5123 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5124 depth); 5125 return -EACCES; 5126 } 5127 5128 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 5129 if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) { 5130 /* x86-64 uses R9 for both private stack frame pointer and arg6. */ 5131 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5132 } else if (priv_stack_supported) { 5133 /* Request private stack support only if the subprog stack 5134 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 5135 * avoid jit penalty if the stack usage is small. 5136 */ 5137 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 5138 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 5139 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 5140 } 5141 5142 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5143 if (subprog_depth > env->max_stack_depth) 5144 env->max_stack_depth = subprog_depth; 5145 if (subprog_depth > MAX_BPF_STACK) { 5146 verbose(env, "stack size of subprog %d is %d. Too large\n", 5147 idx, subprog_depth); 5148 return -EACCES; 5149 } 5150 } else { 5151 depth += subprog_depth; 5152 if (depth > env->max_stack_depth) 5153 env->max_stack_depth = depth; 5154 if (depth > MAX_BPF_STACK) { 5155 total = 0; 5156 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) 5157 total++; 5158 5159 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5160 total, depth); 5161 return -EACCES; 5162 } 5163 } 5164 continue_func: 5165 subprog_end = subprog[idx + 1].start; 5166 for (; i < subprog_end; i++) { 5167 int next_insn, sidx; 5168 5169 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5170 bool err = false; 5171 5172 if (!bpf_is_throw_kfunc(insn + i)) 5173 continue; 5174 for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) { 5175 if (subprog[tmp].is_cb) { 5176 err = true; 5177 break; 5178 } 5179 } 5180 if (!err) 5181 continue; 5182 verbose(env, 5183 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5184 i, idx); 5185 return -EINVAL; 5186 } 5187 5188 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5189 continue; 5190 /* remember insn and function to return to */ 5191 5192 /* find the callee */ 5193 next_insn = i + insn[i].imm + 1; 5194 sidx = bpf_find_subprog(env, next_insn); 5195 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn)) 5196 return -EFAULT; 5197 if (subprog[sidx].is_async_cb) { 5198 if (subprog[sidx].has_tail_call) { 5199 verifier_bug(env, "subprog has tail_call and async cb"); 5200 return -EFAULT; 5201 } 5202 /* async callbacks don't increase bpf prog stack size unless called directly */ 5203 if (!bpf_pseudo_call(insn + i)) 5204 continue; 5205 if (subprog[sidx].is_exception_cb) { 5206 verbose(env, "insn %d cannot call exception cb directly", i); 5207 return -EINVAL; 5208 } 5209 } 5210 5211 /* store caller info for after we return from callee */ 5212 dinfo[idx].frame = frame; 5213 dinfo[idx].ret_insn = i + 1; 5214 5215 /* push caller idx into callee's dinfo */ 5216 dinfo[sidx].caller = idx; 5217 5218 i = next_insn; 5219 5220 idx = sidx; 5221 if (!priv_stack_supported) 5222 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5223 5224 if (subprog[idx].has_tail_call) 5225 tail_call_reachable = true; 5226 5227 frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1; 5228 if (frame >= MAX_CALL_FRAMES) { 5229 verbose(env, "the call stack of %d frames is too deep !\n", 5230 frame); 5231 return -E2BIG; 5232 } 5233 goto process_func; 5234 } 5235 /* if tail call got detected across bpf2bpf calls then mark each of the 5236 * currently present subprog frames as tail call reachable subprogs; 5237 * this info will be utilized by JIT so that we will be preserving the 5238 * tail call counter throughout bpf2bpf calls combined with tailcalls 5239 */ 5240 if (tail_call_reachable) { 5241 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) { 5242 if (subprog[tmp].is_exception_cb) { 5243 verbose(env, "cannot tail call within exception cb\n"); 5244 return -EINVAL; 5245 } 5246 if (subprog[tmp].stack_arg_cnt) { 5247 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5248 return -EINVAL; 5249 } 5250 subprog[tmp].tail_call_reachable = true; 5251 } 5252 } else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) { 5253 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5254 return -EINVAL; 5255 } 5256 5257 if (subprog[0].tail_call_reachable) 5258 env->prog->aux->tail_call_reachable = true; 5259 5260 /* end of for() loop means the last insn of the 'subprog' 5261 * was reached. Doesn't matter whether it was JA or EXIT 5262 */ 5263 if (frame == 0 && dinfo[idx].caller < 0) 5264 return 0; 5265 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 5266 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 5267 5268 /* pop caller idx from callee */ 5269 idx = dinfo[idx].caller; 5270 5271 /* retrieve caller state from its frame */ 5272 frame = dinfo[idx].frame; 5273 i = dinfo[idx].ret_insn; 5274 5275 /* reset tail_call_reachable to the parent's actual state */ 5276 tail_call_reachable = subprog[idx].tail_call_reachable; 5277 5278 goto continue_func; 5279 } 5280 5281 static int check_max_stack_depth(struct bpf_verifier_env *env) 5282 { 5283 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 5284 struct bpf_subprog_call_depth_info *dinfo; 5285 struct bpf_subprog_info *si = env->subprog_info; 5286 bool priv_stack_supported; 5287 int ret; 5288 5289 dinfo = kvcalloc(env->subprog_cnt, sizeof(*dinfo), GFP_KERNEL_ACCOUNT); 5290 if (!dinfo) 5291 return -ENOMEM; 5292 5293 for (int i = 0; i < env->subprog_cnt; i++) { 5294 if (si[i].has_tail_call) { 5295 priv_stack_mode = NO_PRIV_STACK; 5296 break; 5297 } 5298 } 5299 5300 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 5301 priv_stack_mode = bpf_enable_priv_stack(env->prog); 5302 5303 /* All async_cb subprogs use normal kernel stack. If a particular 5304 * subprog appears in both main prog and async_cb subtree, that 5305 * subprog will use normal kernel stack to avoid potential nesting. 5306 * The reverse subprog traversal ensures when main prog subtree is 5307 * checked, the subprogs appearing in async_cb subtrees are already 5308 * marked as using normal kernel stack, so stack size checking can 5309 * be done properly. 5310 */ 5311 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 5312 if (!i || si[i].is_async_cb) { 5313 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 5314 ret = check_max_stack_depth_subprog(env, i, dinfo, 5315 priv_stack_supported); 5316 if (ret < 0) { 5317 kvfree(dinfo); 5318 return ret; 5319 } 5320 } 5321 } 5322 5323 for (int i = 0; i < env->subprog_cnt; i++) { 5324 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5325 env->prog->aux->jits_use_priv_stack = true; 5326 break; 5327 } 5328 } 5329 5330 kvfree(dinfo); 5331 5332 return 0; 5333 } 5334 5335 static int __check_buffer_access(struct bpf_verifier_env *env, 5336 const char *buf_info, 5337 const struct bpf_reg_state *reg, 5338 argno_t argno, int off, int size) 5339 { 5340 if (off < 0) { 5341 verbose(env, 5342 "%s invalid %s buffer access: off=%d, size=%d\n", 5343 reg_arg_name(env, argno), buf_info, off, size); 5344 return -EACCES; 5345 } 5346 if (!tnum_is_const(reg->var_off)) { 5347 char tn_buf[48]; 5348 5349 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5350 verbose(env, 5351 "%s invalid variable buffer offset: off=%d, var_off=%s\n", 5352 reg_arg_name(env, argno), off, tn_buf); 5353 return -EACCES; 5354 } 5355 5356 return 0; 5357 } 5358 5359 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5360 const struct bpf_reg_state *reg, 5361 argno_t argno, int off, int size) 5362 { 5363 int err; 5364 5365 err = __check_buffer_access(env, "tracepoint", reg, argno, off, size); 5366 if (err) 5367 return err; 5368 5369 env->prog->aux->max_tp_access = max(reg->var_off.value + off + size, 5370 env->prog->aux->max_tp_access); 5371 5372 return 0; 5373 } 5374 5375 static int check_buffer_access(struct bpf_verifier_env *env, 5376 const struct bpf_reg_state *reg, 5377 argno_t argno, int off, int size, 5378 bool zero_size_allowed, 5379 u32 *max_access) 5380 { 5381 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5382 int err; 5383 5384 err = __check_buffer_access(env, buf_info, reg, argno, off, size); 5385 if (err) 5386 return err; 5387 5388 *max_access = max(reg->var_off.value + off + size, *max_access); 5389 5390 return 0; 5391 } 5392 5393 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5394 static void zext_32_to_64(struct bpf_reg_state *reg) 5395 { 5396 reg->var_off = tnum_subreg(reg->var_off); 5397 reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg)); 5398 } 5399 5400 /* truncate register to smaller size (in bytes) 5401 * must be called with size < BPF_REG_SIZE 5402 */ 5403 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5404 { 5405 u64 mask; 5406 5407 /* clear high bits in bit representation */ 5408 reg->var_off = tnum_cast(reg->var_off, size); 5409 5410 /* fix arithmetic bounds */ 5411 mask = ((u64)1 << (size * 8)) - 1; 5412 if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask)) 5413 reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask); 5414 else 5415 reg_set_urange64(reg, 0, mask); 5416 5417 /* If size is smaller than 32bit register the 32bit register 5418 * values are also truncated so we push 64-bit bounds into 5419 * 32-bit bounds. Above were truncated < 32-bits already. 5420 */ 5421 if (size < 4) 5422 __mark_reg32_unbounded(reg); 5423 5424 reg_bounds_sync(reg); 5425 } 5426 5427 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 5428 { 5429 if (size == 1) { 5430 reg_set_srange64(reg, S8_MIN, S8_MAX); 5431 reg_set_srange32(reg, S8_MIN, S8_MAX); 5432 } else if (size == 2) { 5433 reg_set_srange64(reg, S16_MIN, S16_MAX); 5434 reg_set_srange32(reg, S16_MIN, S16_MAX); 5435 } else { 5436 /* size == 4 */ 5437 reg_set_srange64(reg, S32_MIN, S32_MAX); 5438 reg_set_srange32(reg, S32_MIN, S32_MAX); 5439 } 5440 reg->var_off = tnum_unknown; 5441 } 5442 5443 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 5444 { 5445 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 5446 u64 top_smax_value, top_smin_value; 5447 u64 num_bits = size * 8; 5448 5449 if (tnum_is_const(reg->var_off)) { 5450 u64_cval = reg->var_off.value; 5451 if (size == 1) 5452 reg->var_off = tnum_const((s8)u64_cval); 5453 else if (size == 2) 5454 reg->var_off = tnum_const((s16)u64_cval); 5455 else 5456 /* size == 4 */ 5457 reg->var_off = tnum_const((s32)u64_cval); 5458 5459 u64_cval = reg->var_off.value; 5460 reg->r64 = cnum64_from_urange(u64_cval, u64_cval); 5461 reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval); 5462 return; 5463 } 5464 5465 top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits; 5466 top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits; 5467 5468 if (top_smax_value != top_smin_value) 5469 goto out; 5470 5471 /* find the s64_min and s64_min after sign extension */ 5472 if (size == 1) { 5473 init_s64_max = (s8)reg_smax(reg); 5474 init_s64_min = (s8)reg_smin(reg); 5475 } else if (size == 2) { 5476 init_s64_max = (s16)reg_smax(reg); 5477 init_s64_min = (s16)reg_smin(reg); 5478 } else { 5479 init_s64_max = (s32)reg_smax(reg); 5480 init_s64_min = (s32)reg_smin(reg); 5481 } 5482 5483 s64_max = max(init_s64_max, init_s64_min); 5484 s64_min = min(init_s64_max, init_s64_min); 5485 5486 /* both of s64_max/s64_min positive or negative */ 5487 if ((s64_max >= 0) == (s64_min >= 0)) { 5488 reg_set_srange64(reg, s64_min, s64_max); 5489 reg_set_srange32(reg, s64_min, s64_max); 5490 reg->var_off = tnum_range(s64_min, s64_max); 5491 return; 5492 } 5493 5494 out: 5495 set_sext64_default_val(reg, size); 5496 } 5497 5498 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 5499 { 5500 if (size == 1) 5501 reg_set_srange32(reg, S8_MIN, S8_MAX); 5502 else 5503 /* size == 2 */ 5504 reg_set_srange32(reg, S16_MIN, S16_MAX); 5505 reg->var_off = tnum_subreg(tnum_unknown); 5506 } 5507 5508 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 5509 { 5510 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 5511 u32 top_smax_value, top_smin_value; 5512 u32 num_bits = size * 8; 5513 5514 if (tnum_is_const(reg->var_off)) { 5515 u32_val = reg->var_off.value; 5516 if (size == 1) 5517 reg->var_off = tnum_const((s8)u32_val); 5518 else 5519 reg->var_off = tnum_const((s16)u32_val); 5520 5521 u32_val = reg->var_off.value; 5522 reg_set_srange32(reg, u32_val, u32_val); 5523 return; 5524 } 5525 5526 top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits; 5527 top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits; 5528 5529 if (top_smax_value != top_smin_value) 5530 goto out; 5531 5532 /* find the s32_min and s32_min after sign extension */ 5533 if (size == 1) { 5534 init_s32_max = (s8)reg_s32_max(reg); 5535 init_s32_min = (s8)reg_s32_min(reg); 5536 } else { 5537 /* size == 2 */ 5538 init_s32_max = (s16)reg_s32_max(reg); 5539 init_s32_min = (s16)reg_s32_min(reg); 5540 } 5541 s32_max = max(init_s32_max, init_s32_min); 5542 s32_min = min(init_s32_max, init_s32_min); 5543 5544 if ((s32_min >= 0) == (s32_max >= 0)) { 5545 reg_set_srange32(reg, s32_min, s32_max); 5546 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 5547 return; 5548 } 5549 5550 out: 5551 set_sext32_default_val(reg, size); 5552 } 5553 5554 bool bpf_map_is_rdonly(const struct bpf_map *map) 5555 { 5556 /* A map is considered read-only if the following condition are true: 5557 * 5558 * 1) BPF program side cannot change any of the map content. The 5559 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 5560 * and was set at map creation time. 5561 * 2) The map value(s) have been initialized from user space by a 5562 * loader and then "frozen", such that no new map update/delete 5563 * operations from syscall side are possible for the rest of 5564 * the map's lifetime from that point onwards. 5565 * 3) Any parallel/pending map update/delete operations from syscall 5566 * side have been completed. Only after that point, it's safe to 5567 * assume that map value(s) are immutable. 5568 */ 5569 return (map->map_flags & BPF_F_RDONLY_PROG) && 5570 READ_ONCE(map->frozen) && 5571 !bpf_map_write_active(map); 5572 } 5573 5574 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 5575 bool is_ldsx) 5576 { 5577 void *ptr; 5578 u64 addr; 5579 int err; 5580 5581 err = map->ops->map_direct_value_addr(map, &addr, off); 5582 if (err) 5583 return err; 5584 ptr = (void *)(long)addr + off; 5585 5586 switch (size) { 5587 case sizeof(u8): 5588 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 5589 break; 5590 case sizeof(u16): 5591 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 5592 break; 5593 case sizeof(u32): 5594 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 5595 break; 5596 case sizeof(u64): 5597 *val = *(u64 *)ptr; 5598 break; 5599 default: 5600 return -EINVAL; 5601 } 5602 return 0; 5603 } 5604 5605 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 5606 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 5607 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 5608 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 5609 5610 /* 5611 * Allow list few fields as RCU trusted or full trusted. 5612 * This logic doesn't allow mix tagging and will be removed once GCC supports 5613 * btf_type_tag. 5614 */ 5615 5616 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 5617 BTF_TYPE_SAFE_RCU(struct task_struct) { 5618 const cpumask_t *cpus_ptr; 5619 struct css_set __rcu *cgroups; 5620 struct task_struct __rcu *real_parent; 5621 struct task_struct *group_leader; 5622 }; 5623 5624 BTF_TYPE_SAFE_RCU(struct cgroup) { 5625 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 5626 struct kernfs_node *kn; 5627 }; 5628 5629 BTF_TYPE_SAFE_RCU(struct css_set) { 5630 struct cgroup *dfl_cgrp; 5631 }; 5632 5633 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) { 5634 struct cgroup *cgroup; 5635 }; 5636 5637 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 5638 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 5639 struct file __rcu *exe_file; 5640 #ifdef CONFIG_MEMCG 5641 struct task_struct __rcu *owner; 5642 #endif 5643 }; 5644 5645 /* skb->sk, req->sk are not RCU protected, but we mark them as such 5646 * because bpf prog accessible sockets are SOCK_RCU_FREE. 5647 */ 5648 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 5649 struct sock *sk; 5650 }; 5651 5652 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 5653 struct sock *sk; 5654 }; 5655 5656 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 5657 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 5658 struct seq_file *seq; 5659 }; 5660 5661 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 5662 struct bpf_iter_meta *meta; 5663 struct task_struct *task; 5664 }; 5665 5666 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 5667 struct file *file; 5668 }; 5669 5670 BTF_TYPE_SAFE_TRUSTED(struct file) { 5671 struct inode *f_inode; 5672 }; 5673 5674 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) { 5675 struct inode *d_inode; 5676 }; 5677 5678 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 5679 struct sock *sk; 5680 }; 5681 5682 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) { 5683 struct mm_struct *vm_mm; 5684 struct file *vm_file; 5685 }; 5686 5687 static bool type_is_rcu(struct bpf_verifier_env *env, 5688 struct bpf_reg_state *reg, 5689 const char *field_name, u32 btf_id) 5690 { 5691 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 5692 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 5693 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 5694 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)); 5695 5696 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 5697 } 5698 5699 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 5700 struct bpf_reg_state *reg, 5701 const char *field_name, u32 btf_id) 5702 { 5703 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 5704 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 5705 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 5706 5707 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 5708 } 5709 5710 static bool type_is_trusted(struct bpf_verifier_env *env, 5711 struct bpf_reg_state *reg, 5712 const char *field_name, u32 btf_id) 5713 { 5714 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 5715 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 5716 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 5717 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 5718 5719 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 5720 } 5721 5722 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 5723 struct bpf_reg_state *reg, 5724 const char *field_name, u32 btf_id) 5725 { 5726 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 5727 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)); 5728 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct)); 5729 5730 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 5731 "__safe_trusted_or_null"); 5732 } 5733 5734 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 5735 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5736 argno_t argno, int off, int size, 5737 enum bpf_access_type atype, 5738 int value_regno) 5739 { 5740 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 5741 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 5742 const char *field_name = NULL; 5743 enum bpf_type_flag flag = 0; 5744 u32 btf_id = 0; 5745 int ret; 5746 5747 if (!env->allow_ptr_leaks) { 5748 verbose(env, 5749 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5750 tname); 5751 return -EPERM; 5752 } 5753 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 5754 verbose(env, 5755 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 5756 tname); 5757 return -EINVAL; 5758 } 5759 5760 if (!tnum_is_const(reg->var_off)) { 5761 char tn_buf[48]; 5762 5763 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5764 verbose(env, 5765 "%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 5766 reg_arg_name(env, argno), tname, off, tn_buf); 5767 return -EACCES; 5768 } 5769 5770 off += reg->var_off.value; 5771 5772 if (off < 0) { 5773 verbose(env, 5774 "%s is ptr_%s invalid negative access: off=%d\n", 5775 reg_arg_name(env, argno), tname, off); 5776 return -EACCES; 5777 } 5778 5779 if (reg->type & MEM_USER) { 5780 verbose(env, 5781 "%s is ptr_%s access user memory: off=%d\n", 5782 reg_arg_name(env, argno), tname, off); 5783 return -EACCES; 5784 } 5785 5786 if (reg->type & MEM_PERCPU) { 5787 verbose(env, 5788 "%s is ptr_%s access percpu memory: off=%d\n", 5789 reg_arg_name(env, argno), tname, off); 5790 return -EACCES; 5791 } 5792 5793 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 5794 if (!btf_is_kernel(reg->btf)) { 5795 verifier_bug(env, "reg->btf must be kernel btf"); 5796 return -EFAULT; 5797 } 5798 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 5799 if (ret < 0) 5800 verbose(env, 5801 "%s cannot write into ptr_%s at off=%d size=%d\n", 5802 reg_arg_name(env, argno), tname, off, size); 5803 } else { 5804 /* Writes are permitted with default btf_struct_access for 5805 * program allocated objects (which always have id > 0), 5806 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 5807 */ 5808 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 5809 verbose(env, "only read is supported\n"); 5810 return -EACCES; 5811 } 5812 5813 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 5814 !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) { 5815 verifier_bug(env, "allocated object must have a referenced id"); 5816 return -EFAULT; 5817 } 5818 5819 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 5820 } 5821 5822 if (ret < 0) 5823 return ret; 5824 5825 if (ret != PTR_TO_BTF_ID) { 5826 /* just mark; */ 5827 5828 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 5829 /* If this is an untrusted pointer, all pointers formed by walking it 5830 * also inherit the untrusted flag. 5831 */ 5832 flag = PTR_UNTRUSTED; 5833 5834 } else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) { 5835 /* By default any pointer obtained from walking a trusted pointer is no 5836 * longer trusted, unless the field being accessed has explicitly been 5837 * marked as inheriting its parent's state of trust (either full or RCU). 5838 * For example: 5839 * 'cgroups' pointer is untrusted if task->cgroups dereference 5840 * happened in a sleepable program outside of bpf_rcu_read_lock() 5841 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 5842 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 5843 * 5844 * A regular RCU-protected pointer with __rcu tag can also be deemed 5845 * trusted if we are in an RCU CS. Such pointer can be NULL. 5846 */ 5847 if (type_is_trusted(env, reg, field_name, btf_id)) { 5848 flag |= PTR_TRUSTED; 5849 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 5850 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 5851 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 5852 if (type_is_rcu(env, reg, field_name, btf_id)) { 5853 /* ignore __rcu tag and mark it MEM_RCU */ 5854 flag |= MEM_RCU; 5855 } else if (flag & MEM_RCU || 5856 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 5857 /* __rcu tagged pointers can be NULL */ 5858 flag |= MEM_RCU | PTR_MAYBE_NULL; 5859 5860 /* We always trust them */ 5861 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 5862 flag & PTR_UNTRUSTED) 5863 flag &= ~PTR_UNTRUSTED; 5864 } else if (flag & (MEM_PERCPU | MEM_USER)) { 5865 /* keep as-is */ 5866 } else { 5867 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 5868 clear_trusted_flags(&flag); 5869 } 5870 } else { 5871 /* 5872 * If not in RCU CS or MEM_RCU pointer can be NULL then 5873 * aggressively mark as untrusted otherwise such 5874 * pointers will be plain PTR_TO_BTF_ID without flags 5875 * and will be allowed to be passed into helpers for 5876 * compat reasons. 5877 */ 5878 flag = PTR_UNTRUSTED; 5879 } 5880 } else { 5881 /* Old compat. Deprecated */ 5882 clear_trusted_flags(&flag); 5883 } 5884 5885 if (atype == BPF_READ && value_regno >= 0) { 5886 ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5887 if (ret < 0) 5888 return ret; 5889 } 5890 5891 return 0; 5892 } 5893 5894 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5895 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5896 argno_t argno, int off, int size, 5897 enum bpf_access_type atype, 5898 int value_regno) 5899 { 5900 struct bpf_map *map = reg->map_ptr; 5901 struct bpf_reg_state map_reg; 5902 enum bpf_type_flag flag = 0; 5903 const struct btf_type *t; 5904 const char *tname; 5905 u32 btf_id; 5906 int ret; 5907 5908 if (!btf_vmlinux) { 5909 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5910 return -ENOTSUPP; 5911 } 5912 5913 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5914 verbose(env, "map_ptr access not supported for map type %d\n", 5915 map->map_type); 5916 return -ENOTSUPP; 5917 } 5918 5919 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5920 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5921 5922 if (!env->allow_ptr_leaks) { 5923 verbose(env, 5924 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5925 tname); 5926 return -EPERM; 5927 } 5928 5929 if (off < 0) { 5930 verbose(env, "%s is %s invalid negative access: off=%d\n", 5931 reg_arg_name(env, argno), tname, off); 5932 return -EACCES; 5933 } 5934 5935 if (atype != BPF_READ) { 5936 verbose(env, "only read from %s is supported\n", tname); 5937 return -EACCES; 5938 } 5939 5940 /* Simulate access to a PTR_TO_BTF_ID */ 5941 memset(&map_reg, 0, sizeof(map_reg)); 5942 ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, 5943 btf_vmlinux, *map->ops->map_btf_id, 0); 5944 if (ret < 0) 5945 return ret; 5946 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 5947 if (ret < 0) 5948 return ret; 5949 5950 if (value_regno >= 0) { 5951 ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 5952 if (ret < 0) 5953 return ret; 5954 } 5955 5956 return 0; 5957 } 5958 5959 /* Check that the stack access at the given offset is within bounds. The 5960 * maximum valid offset is -1. 5961 * 5962 * The minimum valid offset is -MAX_BPF_STACK for writes, and 5963 * -state->allocated_stack for reads. 5964 */ 5965 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 5966 s64 off, 5967 struct bpf_func_state *state, 5968 enum bpf_access_type t) 5969 { 5970 int min_valid_off; 5971 5972 if (t == BPF_WRITE || env->allow_uninit_stack) 5973 min_valid_off = -MAX_BPF_STACK; 5974 else 5975 min_valid_off = -state->allocated_stack; 5976 5977 if (off < min_valid_off || off > -1) 5978 return -EACCES; 5979 return 0; 5980 } 5981 5982 /* Check that the stack access at 'regno + off' falls within the maximum stack 5983 * bounds. 5984 * 5985 * 'off' includes `regno->offset`, but not its dynamic part (if any). 5986 */ 5987 static int check_stack_access_within_bounds( 5988 struct bpf_verifier_env *env, struct bpf_reg_state *reg, 5989 argno_t argno, int off, int access_size, 5990 enum bpf_access_type type) 5991 { 5992 struct bpf_func_state *state = bpf_func(env, reg); 5993 s64 min_off, max_off; 5994 int err; 5995 char *err_extra; 5996 5997 if (type == BPF_READ) 5998 err_extra = " read from"; 5999 else 6000 err_extra = " write to"; 6001 6002 if (tnum_is_const(reg->var_off)) { 6003 min_off = (s64)reg->var_off.value + off; 6004 max_off = min_off + access_size; 6005 } else { 6006 if (reg_smax(reg) >= BPF_MAX_VAR_OFF || 6007 reg_smin(reg) <= -BPF_MAX_VAR_OFF) { 6008 verbose(env, "invalid unbounded variable-offset%s stack %s\n", 6009 err_extra, reg_arg_name(env, argno)); 6010 return -EACCES; 6011 } 6012 min_off = reg_smin(reg) + off; 6013 max_off = reg_smax(reg) + off + access_size; 6014 } 6015 6016 err = check_stack_slot_within_bounds(env, min_off, state, type); 6017 if (!err && max_off > 0) 6018 err = -EINVAL; /* out of stack access into non-negative offsets */ 6019 if (!err && access_size < 0) 6020 /* access_size should not be negative (or overflow an int); others checks 6021 * along the way should have prevented such an access. 6022 */ 6023 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6024 6025 if (err) { 6026 if (tnum_is_const(reg->var_off)) { 6027 verbose(env, "invalid%s stack %s off=%lld size=%d\n", 6028 err_extra, reg_arg_name(env, argno), min_off, access_size); 6029 } else { 6030 char tn_buf[48]; 6031 6032 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6033 verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n", 6034 err_extra, reg_arg_name(env, argno), tn_buf, off, access_size); 6035 } 6036 return err; 6037 } 6038 6039 /* Note that there is no stack access with offset zero, so the needed stack 6040 * size is -min_off, not -min_off+1. 6041 */ 6042 return grow_stack_state(env, state, -min_off /* size */); 6043 } 6044 6045 static bool get_func_retval_range(struct bpf_prog *prog, 6046 struct bpf_retval_range *range) 6047 { 6048 if (prog->type == BPF_PROG_TYPE_LSM && 6049 prog->expected_attach_type == BPF_LSM_MAC && 6050 !bpf_lsm_get_retval_range(prog, range)) { 6051 return true; 6052 } 6053 return false; 6054 } 6055 6056 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val) 6057 { 6058 struct bpf_reg_state fake_reg; 6059 6060 if (!val) 6061 return; 6062 6063 fake_reg.type = SCALAR_VALUE; 6064 __mark_reg_known(&fake_reg, val); 6065 6066 scalar32_min_max_add(dst_reg, &fake_reg); 6067 scalar_min_max_add(dst_reg, &fake_reg); 6068 dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off); 6069 6070 reg_bounds_sync(dst_reg); 6071 } 6072 6073 /* check whether memory at (regno + off) is accessible for t = (read | write) 6074 * if t==write, value_regno is a register which value is stored into memory 6075 * if t==read, value_regno is a register which will receive the value from memory 6076 * if t==write && value_regno==-1, some unknown value is stored into memory 6077 * if t==read && value_regno==-1, don't care what we read from memory 6078 */ 6079 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 6080 int off, int bpf_size, enum bpf_access_type t, 6081 int value_regno, bool strict_alignment_once, bool is_ldsx) 6082 { 6083 struct bpf_reg_state *regs = cur_regs(env); 6084 int size, err = 0; 6085 6086 size = bpf_size_to_bytes(bpf_size); 6087 if (size < 0) 6088 return size; 6089 6090 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6091 if (err) 6092 return err; 6093 6094 if (reg->type == PTR_TO_MAP_KEY) { 6095 if (t == BPF_WRITE) { 6096 verbose(env, "write to change key %s not allowed\n", 6097 reg_arg_name(env, argno)); 6098 return -EACCES; 6099 } 6100 6101 err = check_mem_region_access(env, reg, argno, off, size, 6102 reg->map_ptr->key_size, false); 6103 if (err) 6104 return err; 6105 if (value_regno >= 0) 6106 mark_reg_unknown(env, regs, value_regno); 6107 } else if (reg->type == PTR_TO_MAP_VALUE) { 6108 struct btf_field *kptr_field = NULL; 6109 6110 if (t == BPF_WRITE && value_regno >= 0 && 6111 is_pointer_value(env, value_regno)) { 6112 verbose(env, "R%d leaks addr into map\n", value_regno); 6113 return -EACCES; 6114 } 6115 err = check_map_access_type(env, reg, off, size, t); 6116 if (err) 6117 return err; 6118 err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT); 6119 if (err) 6120 return err; 6121 if (tnum_is_const(reg->var_off)) 6122 kptr_field = btf_record_find(reg->map_ptr->record, 6123 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 6124 if (kptr_field) { 6125 err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field); 6126 } else if (t == BPF_READ && value_regno >= 0) { 6127 struct bpf_map *map = reg->map_ptr; 6128 6129 /* 6130 * If map is read-only, track its contents as scalars, 6131 * unless it is an insn array (see the special case below) 6132 */ 6133 if (tnum_is_const(reg->var_off) && 6134 bpf_map_is_rdonly(map) && 6135 map->ops->map_direct_value_addr && 6136 map->map_type != BPF_MAP_TYPE_INSN_ARRAY) { 6137 int map_off = off + reg->var_off.value; 6138 u64 val = 0; 6139 6140 err = bpf_map_direct_read(map, map_off, size, 6141 &val, is_ldsx); 6142 if (err) 6143 return err; 6144 6145 regs[value_regno].type = SCALAR_VALUE; 6146 __mark_reg_known(®s[value_regno], val); 6147 } else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 6148 if (bpf_size != BPF_DW) { 6149 verbose(env, "Invalid read of %d bytes from insn_array\n", 6150 size); 6151 return -EACCES; 6152 } 6153 regs[value_regno] = *reg; 6154 add_scalar_to_reg(®s[value_regno], off); 6155 regs[value_regno].type = PTR_TO_INSN; 6156 } else { 6157 mark_reg_unknown(env, regs, value_regno); 6158 } 6159 } 6160 } else if (base_type(reg->type) == PTR_TO_MEM) { 6161 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6162 bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED); 6163 6164 if (type_may_be_null(reg->type)) { 6165 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6166 reg_type_str(env, reg->type)); 6167 return -EACCES; 6168 } 6169 6170 if (t == BPF_WRITE && rdonly_mem) { 6171 verbose(env, "%s cannot write into %s\n", 6172 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6173 return -EACCES; 6174 } 6175 6176 if (t == BPF_WRITE && value_regno >= 0 && 6177 is_pointer_value(env, value_regno)) { 6178 verbose(env, "R%d leaks addr into mem\n", value_regno); 6179 return -EACCES; 6180 } 6181 6182 /* 6183 * Accesses to untrusted PTR_TO_MEM are done through probe 6184 * instructions, hence no need to check bounds in that case. 6185 */ 6186 if (!rdonly_untrusted) 6187 err = check_mem_region_access(env, reg, argno, off, size, 6188 reg->mem_size, false); 6189 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6190 mark_reg_unknown(env, regs, value_regno); 6191 } else if (reg->type == PTR_TO_CTX) { 6192 struct bpf_insn_access_aux info = { 6193 .reg_type = SCALAR_VALUE, 6194 .is_ldsx = is_ldsx, 6195 .log = &env->log, 6196 }; 6197 struct bpf_retval_range range; 6198 6199 if (t == BPF_WRITE && value_regno >= 0 && 6200 is_pointer_value(env, value_regno)) { 6201 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6202 return -EACCES; 6203 } 6204 6205 err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info); 6206 if (!err && t == BPF_READ && value_regno >= 0) { 6207 /* ctx access returns either a scalar, or a 6208 * PTR_TO_PACKET[_META,_END]. In the latter 6209 * case, we know the offset is zero. 6210 */ 6211 if (info.reg_type == SCALAR_VALUE) { 6212 if (info.is_retval && get_func_retval_range(env->prog, &range)) { 6213 mark_reg_unknown(env, regs, value_regno); 6214 err = __mark_reg_s32_range(env, regs, value_regno, 6215 range.minval, range.maxval); 6216 if (err) 6217 return err; 6218 } else { 6219 mark_reg_unknown(env, regs, value_regno); 6220 } 6221 } else { 6222 mark_reg_known_zero(env, regs, 6223 value_regno); 6224 /* A load of ctx field could have different 6225 * actual load size with the one encoded in the 6226 * insn. When the dst is PTR, it is for sure not 6227 * a sub-register. 6228 */ 6229 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6230 if (base_type(info.reg_type) == PTR_TO_BTF_ID) { 6231 regs[value_regno].btf = info.btf; 6232 regs[value_regno].btf_id = info.btf_id; 6233 regs[value_regno].id = info.ref_id; 6234 } 6235 if (type_may_be_null(info.reg_type) && !regs[value_regno].id) 6236 regs[value_regno].id = ++env->id_gen; 6237 } 6238 regs[value_regno].type = info.reg_type; 6239 } 6240 6241 } else if (reg->type == PTR_TO_STACK) { 6242 /* Basic bounds checks. */ 6243 err = check_stack_access_within_bounds(env, reg, argno, off, size, t); 6244 if (err) 6245 return err; 6246 6247 if (t == BPF_READ) 6248 err = check_stack_read(env, reg, argno, off, size, 6249 value_regno); 6250 else 6251 err = check_stack_write(env, reg, off, size, 6252 value_regno, insn_idx); 6253 } else if (reg_is_pkt_pointer(reg)) { 6254 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6255 verbose(env, "cannot write into packet\n"); 6256 return -EACCES; 6257 } 6258 if (t == BPF_WRITE && value_regno >= 0 && 6259 is_pointer_value(env, value_regno)) { 6260 verbose(env, "R%d leaks addr into packet\n", 6261 value_regno); 6262 return -EACCES; 6263 } 6264 err = check_packet_access(env, reg, argno, off, size, false); 6265 if (!err && t == BPF_READ && value_regno >= 0) 6266 mark_reg_unknown(env, regs, value_regno); 6267 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6268 if (t == BPF_WRITE && value_regno >= 0 && 6269 is_pointer_value(env, value_regno)) { 6270 verbose(env, "R%d leaks addr into flow keys\n", 6271 value_regno); 6272 return -EACCES; 6273 } 6274 6275 err = check_flow_keys_access(env, reg, argno, off, size); 6276 if (!err && t == BPF_READ && value_regno >= 0) 6277 mark_reg_unknown(env, regs, value_regno); 6278 } else if (type_is_sk_pointer(reg->type)) { 6279 if (t == BPF_WRITE) { 6280 verbose(env, "%s cannot write into %s\n", 6281 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6282 return -EACCES; 6283 } 6284 err = check_sock_access(env, insn_idx, reg, argno, off, size, t); 6285 if (!err && value_regno >= 0) 6286 mark_reg_unknown(env, regs, value_regno); 6287 } else if (reg->type == PTR_TO_TP_BUFFER) { 6288 err = check_tp_buffer_access(env, reg, argno, off, size); 6289 if (!err && t == BPF_READ && value_regno >= 0) 6290 mark_reg_unknown(env, regs, value_regno); 6291 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6292 !type_may_be_null(reg->type)) { 6293 err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t, 6294 value_regno); 6295 } else if (reg->type == CONST_PTR_TO_MAP) { 6296 err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t, 6297 value_regno); 6298 } else if (base_type(reg->type) == PTR_TO_BUF && 6299 !type_may_be_null(reg->type)) { 6300 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6301 u32 *max_access; 6302 6303 if (rdonly_mem) { 6304 if (t == BPF_WRITE) { 6305 verbose(env, "%s cannot write into %s\n", 6306 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6307 return -EACCES; 6308 } 6309 max_access = &env->prog->aux->max_rdonly_access; 6310 } else { 6311 max_access = &env->prog->aux->max_rdwr_access; 6312 } 6313 6314 err = check_buffer_access(env, reg, argno, off, size, false, 6315 max_access); 6316 6317 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6318 mark_reg_unknown(env, regs, value_regno); 6319 } else if (reg->type == PTR_TO_ARENA) { 6320 if (t == BPF_READ && value_regno >= 0) 6321 mark_reg_unknown(env, regs, value_regno); 6322 } else { 6323 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6324 reg_type_str(env, reg->type)); 6325 return -EACCES; 6326 } 6327 6328 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6329 regs[value_regno].type == SCALAR_VALUE) { 6330 if (!is_ldsx) 6331 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6332 coerce_reg_to_size(®s[value_regno], size); 6333 else 6334 coerce_reg_to_size_sx(®s[value_regno], size); 6335 } 6336 return err; 6337 } 6338 6339 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 6340 bool allow_trust_mismatch); 6341 6342 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn, 6343 bool strict_alignment_once, bool is_ldsx, 6344 bool allow_trust_mismatch, const char *ctx) 6345 { 6346 struct bpf_verifier_state *vstate = env->cur_state; 6347 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6348 struct bpf_reg_state *regs = cur_regs(env); 6349 enum bpf_reg_type src_reg_type; 6350 int err; 6351 6352 /* Handle stack arg read */ 6353 if (is_stack_arg_ldx(insn)) { 6354 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6355 if (err) 6356 return err; 6357 return check_stack_arg_read(env, state, insn->off, insn->dst_reg); 6358 } 6359 6360 /* check src operand */ 6361 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6362 if (err) 6363 return err; 6364 6365 /* check dst operand */ 6366 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6367 if (err) 6368 return err; 6369 6370 src_reg_type = regs[insn->src_reg].type; 6371 6372 /* Check if (src_reg + off) is readable. The state of dst_reg will be 6373 * updated by this call. 6374 */ 6375 err = check_mem_access(env, env->insn_idx, regs + insn->src_reg, argno_from_reg(insn->src_reg), insn->off, 6376 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg, 6377 strict_alignment_once, is_ldsx); 6378 err = err ?: save_aux_ptr_type(env, src_reg_type, 6379 allow_trust_mismatch); 6380 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx); 6381 6382 return err; 6383 } 6384 6385 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn, 6386 bool strict_alignment_once) 6387 { 6388 struct bpf_verifier_state *vstate = env->cur_state; 6389 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6390 struct bpf_reg_state *regs = cur_regs(env); 6391 enum bpf_reg_type dst_reg_type; 6392 int err; 6393 6394 /* Handle stack arg write */ 6395 if (is_stack_arg_stx(insn)) { 6396 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6397 if (err) 6398 return err; 6399 return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg); 6400 } 6401 6402 /* check src1 operand */ 6403 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6404 if (err) 6405 return err; 6406 6407 /* check src2 operand */ 6408 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6409 if (err) 6410 return err; 6411 6412 dst_reg_type = regs[insn->dst_reg].type; 6413 6414 /* Check if (dst_reg + off) is writeable. */ 6415 err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6416 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg, 6417 strict_alignment_once, false); 6418 err = err ?: save_aux_ptr_type(env, dst_reg_type, false); 6419 6420 return err; 6421 } 6422 6423 static int check_atomic_rmw(struct bpf_verifier_env *env, 6424 struct bpf_insn *insn) 6425 { 6426 struct bpf_reg_state *dst_reg; 6427 int load_reg; 6428 int err; 6429 6430 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6431 verbose(env, "invalid atomic operand size\n"); 6432 return -EINVAL; 6433 } 6434 6435 /* check src1 operand */ 6436 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6437 if (err) 6438 return err; 6439 6440 /* check src2 operand */ 6441 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6442 if (err) 6443 return err; 6444 6445 if (insn->imm == BPF_CMPXCHG) { 6446 /* Check comparison of R0 with memory location */ 6447 const u32 aux_reg = BPF_REG_0; 6448 6449 err = check_reg_arg(env, aux_reg, SRC_OP); 6450 if (err) 6451 return err; 6452 6453 if (is_pointer_value(env, aux_reg)) { 6454 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6455 return -EACCES; 6456 } 6457 } 6458 6459 if (is_pointer_value(env, insn->src_reg)) { 6460 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6461 return -EACCES; 6462 } 6463 6464 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6465 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6466 insn->dst_reg, 6467 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6468 return -EACCES; 6469 } 6470 6471 if (insn->imm & BPF_FETCH) { 6472 if (insn->imm == BPF_CMPXCHG) 6473 load_reg = BPF_REG_0; 6474 else 6475 load_reg = insn->src_reg; 6476 6477 /* check and record load of old value */ 6478 err = check_reg_arg(env, load_reg, DST_OP); 6479 if (err) 6480 return err; 6481 } else { 6482 /* This instruction accesses a memory location but doesn't 6483 * actually load it into a register. 6484 */ 6485 load_reg = -1; 6486 } 6487 6488 dst_reg = cur_regs(env) + insn->dst_reg; 6489 6490 /* Check whether we can read the memory, with second call for fetch 6491 * case to simulate the register fill. 6492 */ 6493 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6494 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6495 if (!err && load_reg >= 0) 6496 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), 6497 insn->off, BPF_SIZE(insn->code), 6498 BPF_READ, load_reg, true, false); 6499 if (err) 6500 return err; 6501 6502 if (is_arena_reg(env, insn->dst_reg)) { 6503 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 6504 if (err) 6505 return err; 6506 } 6507 /* Check whether we can write into the same memory. */ 6508 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6509 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6510 if (err) 6511 return err; 6512 return 0; 6513 } 6514 6515 static int check_atomic_load(struct bpf_verifier_env *env, 6516 struct bpf_insn *insn) 6517 { 6518 int err; 6519 6520 err = check_load_mem(env, insn, true, false, false, "atomic_load"); 6521 if (err) 6522 return err; 6523 6524 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) { 6525 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n", 6526 insn->src_reg, 6527 reg_type_str(env, reg_state(env, insn->src_reg)->type)); 6528 return -EACCES; 6529 } 6530 6531 return 0; 6532 } 6533 6534 static int check_atomic_store(struct bpf_verifier_env *env, 6535 struct bpf_insn *insn) 6536 { 6537 int err; 6538 6539 err = check_store_reg(env, insn, true); 6540 if (err) 6541 return err; 6542 6543 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6544 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6545 insn->dst_reg, 6546 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6547 return -EACCES; 6548 } 6549 6550 return 0; 6551 } 6552 6553 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn) 6554 { 6555 switch (insn->imm) { 6556 case BPF_ADD: 6557 case BPF_ADD | BPF_FETCH: 6558 case BPF_AND: 6559 case BPF_AND | BPF_FETCH: 6560 case BPF_OR: 6561 case BPF_OR | BPF_FETCH: 6562 case BPF_XOR: 6563 case BPF_XOR | BPF_FETCH: 6564 case BPF_XCHG: 6565 case BPF_CMPXCHG: 6566 return check_atomic_rmw(env, insn); 6567 case BPF_LOAD_ACQ: 6568 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6569 verbose(env, 6570 "64-bit load-acquires are only supported on 64-bit arches\n"); 6571 return -EOPNOTSUPP; 6572 } 6573 return check_atomic_load(env, insn); 6574 case BPF_STORE_REL: 6575 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6576 verbose(env, 6577 "64-bit store-releases are only supported on 64-bit arches\n"); 6578 return -EOPNOTSUPP; 6579 } 6580 return check_atomic_store(env, insn); 6581 default: 6582 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", 6583 insn->imm); 6584 return -EINVAL; 6585 } 6586 } 6587 6588 /* When register 'regno' is used to read the stack (either directly or through 6589 * a helper function) make sure that it's within stack boundary and, depending 6590 * on the access type and privileges, that all elements of the stack are 6591 * initialized. 6592 * 6593 * All registers that have been spilled on the stack in the slots within the 6594 * read offsets are marked as read. 6595 */ 6596 static int check_stack_range_initialized( 6597 struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 6598 int access_size, bool zero_size_allowed, 6599 enum bpf_access_type type, struct bpf_call_arg_meta *meta) 6600 { 6601 struct bpf_func_state *state = bpf_func(env, reg); 6602 int err, min_off, max_off, i, j, slot, spi; 6603 /* Some accesses can write anything into the stack, others are 6604 * read-only. 6605 */ 6606 bool clobber = type == BPF_WRITE; 6607 /* 6608 * Negative access_size signals global subprog/kfunc arg check where 6609 * STACK_POISON slots are acceptable. static stack liveness 6610 * might have determined that subprog doesn't read them, 6611 * but BTF based global subprog validation isn't accurate enough. 6612 */ 6613 bool allow_poison = access_size < 0 || clobber; 6614 6615 access_size = abs(access_size); 6616 6617 if (access_size == 0 && !zero_size_allowed) { 6618 verbose(env, "invalid zero-sized read\n"); 6619 return -EACCES; 6620 } 6621 6622 err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type); 6623 if (err) 6624 return err; 6625 6626 6627 if (tnum_is_const(reg->var_off)) { 6628 min_off = max_off = reg->var_off.value + off; 6629 } else { 6630 /* Variable offset is prohibited for unprivileged mode for 6631 * simplicity since it requires corresponding support in 6632 * Spectre masking for stack ALU. 6633 * See also retrieve_ptr_limit(). 6634 */ 6635 if (!env->bypass_spec_v1) { 6636 char tn_buf[48]; 6637 6638 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6639 verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n", 6640 reg_arg_name(env, argno), tn_buf); 6641 return -EACCES; 6642 } 6643 /* Only initialized buffer on stack is allowed to be accessed 6644 * with variable offset. With uninitialized buffer it's hard to 6645 * guarantee that whole memory is marked as initialized on 6646 * helper return since specific bounds are unknown what may 6647 * cause uninitialized stack leaking. 6648 */ 6649 if (meta && meta->raw_mode) 6650 meta = NULL; 6651 6652 min_off = reg_smin(reg) + off; 6653 max_off = reg_smax(reg) + off; 6654 } 6655 6656 if (meta && meta->raw_mode) { 6657 /* Ensure we won't be overwriting dynptrs when simulating byte 6658 * by byte access in check_helper_call using meta.access_size. 6659 * This would be a problem if we have a helper in the future 6660 * which takes: 6661 * 6662 * helper(uninit_mem, len, dynptr) 6663 * 6664 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 6665 * may end up writing to dynptr itself when touching memory from 6666 * arg 1. This can be relaxed on a case by case basis for known 6667 * safe cases, but reject due to the possibilitiy of aliasing by 6668 * default. 6669 */ 6670 for (i = min_off; i < max_off + access_size; i++) { 6671 int stack_off = -i - 1; 6672 6673 spi = bpf_get_spi(i); 6674 /* raw_mode may write past allocated_stack */ 6675 if (state->allocated_stack <= stack_off) 6676 continue; 6677 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 6678 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 6679 return -EACCES; 6680 } 6681 } 6682 meta->access_size = access_size; 6683 meta->regno = reg_from_argno(argno); 6684 return 0; 6685 } 6686 6687 for (i = min_off; i < max_off + access_size; i++) { 6688 u8 *stype; 6689 6690 slot = -i - 1; 6691 spi = slot / BPF_REG_SIZE; 6692 if (state->allocated_stack <= slot) { 6693 verbose(env, "allocated_stack too small\n"); 6694 return -EFAULT; 6695 } 6696 6697 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 6698 if (*stype == STACK_MISC) 6699 goto mark; 6700 if ((*stype == STACK_ZERO) || 6701 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 6702 if (clobber) { 6703 /* helper can write anything into the stack */ 6704 *stype = STACK_MISC; 6705 } 6706 goto mark; 6707 } 6708 6709 if (bpf_is_spilled_reg(&state->stack[spi]) && 6710 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 6711 env->allow_ptr_leaks)) { 6712 if (clobber) { 6713 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 6714 for (j = 0; j < BPF_REG_SIZE; j++) 6715 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 6716 } 6717 goto mark; 6718 } 6719 6720 if (*stype == STACK_POISON) { 6721 if (allow_poison) 6722 goto mark; 6723 verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n", 6724 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6725 } else if (tnum_is_const(reg->var_off)) { 6726 verbose(env, "invalid read from stack %s off %d+%d size %d\n", 6727 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6728 } else { 6729 char tn_buf[48]; 6730 6731 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6732 verbose(env, "invalid read from stack %s var_off %s+%d size %d\n", 6733 reg_arg_name(env, argno), tn_buf, i - min_off, access_size); 6734 } 6735 return -EACCES; 6736 mark: 6737 ; 6738 } 6739 return 0; 6740 } 6741 6742 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 6743 int access_size, enum bpf_access_type access_type, 6744 bool zero_size_allowed, 6745 struct bpf_call_arg_meta *meta) 6746 { 6747 struct bpf_reg_state *regs = cur_regs(env); 6748 u32 *max_access; 6749 6750 switch (base_type(reg->type)) { 6751 case PTR_TO_PACKET: 6752 case PTR_TO_PACKET_META: 6753 return check_packet_access(env, reg, argno, 0, access_size, 6754 zero_size_allowed); 6755 case PTR_TO_MAP_KEY: 6756 if (access_type == BPF_WRITE) { 6757 verbose(env, "%s cannot write into %s\n", 6758 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6759 return -EACCES; 6760 } 6761 return check_mem_region_access(env, reg, argno, 0, access_size, 6762 reg->map_ptr->key_size, false); 6763 case PTR_TO_MAP_VALUE: 6764 if (check_map_access_type(env, reg, 0, access_size, access_type)) 6765 return -EACCES; 6766 return check_map_access(env, reg, argno, 0, access_size, 6767 zero_size_allowed, ACCESS_HELPER); 6768 case PTR_TO_MEM: 6769 if (type_is_rdonly_mem(reg->type)) { 6770 if (access_type == BPF_WRITE) { 6771 verbose(env, "%s cannot write into %s\n", 6772 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6773 return -EACCES; 6774 } 6775 } 6776 return check_mem_region_access(env, reg, argno, 0, 6777 access_size, reg->mem_size, 6778 zero_size_allowed); 6779 case PTR_TO_BUF: 6780 if (type_is_rdonly_mem(reg->type)) { 6781 if (access_type == BPF_WRITE) { 6782 verbose(env, "%s cannot write into %s\n", 6783 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6784 return -EACCES; 6785 } 6786 6787 max_access = &env->prog->aux->max_rdonly_access; 6788 } else { 6789 max_access = &env->prog->aux->max_rdwr_access; 6790 } 6791 return check_buffer_access(env, reg, argno, 0, 6792 access_size, zero_size_allowed, 6793 max_access); 6794 case PTR_TO_STACK: 6795 return check_stack_range_initialized( 6796 env, reg, 6797 argno, 0, access_size, 6798 zero_size_allowed, access_type, meta); 6799 case PTR_TO_BTF_ID: 6800 return check_ptr_to_btf_access(env, regs, reg, argno, 0, 6801 access_size, access_type, -1); 6802 case PTR_TO_CTX: 6803 /* Only permit reading or writing syscall context using helper calls. */ 6804 if (is_var_ctx_off_allowed(env->prog)) { 6805 int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX, 6806 zero_size_allowed); 6807 if (err) 6808 return err; 6809 if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size) 6810 env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size; 6811 return 0; 6812 } 6813 fallthrough; 6814 default: /* scalar_value or invalid ptr */ 6815 /* Allow zero-byte read from NULL, regardless of pointer type */ 6816 if (zero_size_allowed && access_size == 0 && 6817 bpf_register_is_null(reg)) 6818 return 0; 6819 6820 verbose(env, "%s type=%s ", reg_arg_name(env, argno), 6821 reg_type_str(env, reg->type)); 6822 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 6823 return -EACCES; 6824 } 6825 } 6826 6827 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 6828 * size. 6829 * 6830 * @mem_reg contains the pointer, @size_reg contains the access size. 6831 */ 6832 static int check_mem_size_reg(struct bpf_verifier_env *env, 6833 struct bpf_reg_state *mem_reg, 6834 struct bpf_reg_state *size_reg, argno_t mem_argno, 6835 argno_t size_argno, enum bpf_access_type access_type, 6836 bool zero_size_allowed, 6837 struct bpf_call_arg_meta *meta) 6838 { 6839 int err; 6840 6841 /* This is used to refine r0 return value bounds for helpers 6842 * that enforce this value as an upper bound on return values. 6843 * See do_refine_retval_range() for helpers that can refine 6844 * the return value. C type of helper is u32 so we pull register 6845 * bound from umax_value however, if negative verifier errors 6846 * out. Only upper bounds can be learned because retval is an 6847 * int type and negative retvals are allowed. 6848 */ 6849 meta->msize_max_value = reg_umax(size_reg); 6850 6851 /* The register is SCALAR_VALUE; the access check happens using 6852 * its boundaries. For unprivileged variable accesses, disable 6853 * raw mode so that the program is required to initialize all 6854 * the memory that the helper could just partially fill up. 6855 */ 6856 if (!tnum_is_const(size_reg->var_off)) 6857 meta = NULL; 6858 6859 if (reg_smin(size_reg) < 0) { 6860 verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n", 6861 reg_arg_name(env, size_argno)); 6862 return -EACCES; 6863 } 6864 6865 if (reg_umin(size_reg) == 0 && !zero_size_allowed) { 6866 verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n", 6867 reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg)); 6868 return -EACCES; 6869 } 6870 6871 if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) { 6872 verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 6873 reg_arg_name(env, size_argno)); 6874 return -EACCES; 6875 } 6876 err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg), 6877 access_type, zero_size_allowed, meta); 6878 if (!err) { 6879 int regno = reg_from_argno(size_argno); 6880 6881 if (regno >= 0) 6882 err = mark_chain_precision(env, regno); 6883 else 6884 err = mark_stack_arg_precision(env, arg_idx_from_argno(size_argno)); 6885 } 6886 return err; 6887 } 6888 6889 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6890 argno_t argno, u32 mem_size) 6891 { 6892 bool may_be_null = type_may_be_null(reg->type); 6893 struct bpf_reg_state saved_reg; 6894 int err; 6895 6896 if (bpf_register_is_null(reg)) 6897 return 0; 6898 6899 if (mem_size > S32_MAX) { 6900 verbose(env, "%s memory size %u is too large\n", 6901 reg_arg_name(env, argno), mem_size); 6902 return -EACCES; 6903 } 6904 6905 /* Assuming that the register contains a value check if the memory 6906 * access is safe. Temporarily save and restore the register's state as 6907 * the conversion shouldn't be visible to a caller. 6908 */ 6909 if (may_be_null) { 6910 saved_reg = *reg; 6911 mark_ptr_not_null_reg(reg); 6912 } 6913 6914 int size = base_type(reg->type) == PTR_TO_STACK ? -(int)mem_size : mem_size; 6915 6916 err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, NULL); 6917 err = err ?: check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, NULL); 6918 6919 if (may_be_null) 6920 *reg = saved_reg; 6921 6922 return err; 6923 } 6924 6925 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *mem_reg, 6926 struct bpf_reg_state *size_reg, argno_t mem_argno, argno_t size_argno) 6927 { 6928 bool may_be_null = type_may_be_null(mem_reg->type); 6929 struct bpf_reg_state saved_reg; 6930 struct bpf_call_arg_meta meta; 6931 int err; 6932 6933 memset(&meta, 0, sizeof(meta)); 6934 6935 if (may_be_null) { 6936 saved_reg = *mem_reg; 6937 mark_ptr_not_null_reg(mem_reg); 6938 } 6939 6940 err = check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_READ, true, &meta); 6941 err = err ?: check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_WRITE, true, &meta); 6942 6943 if (may_be_null) 6944 *mem_reg = saved_reg; 6945 6946 return err; 6947 } 6948 6949 enum { 6950 PROCESS_SPIN_LOCK = (1 << 0), 6951 PROCESS_RES_LOCK = (1 << 1), 6952 PROCESS_LOCK_IRQ = (1 << 2), 6953 }; 6954 6955 /* Implementation details: 6956 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 6957 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 6958 * Two bpf_map_lookups (even with the same key) will have different reg->id. 6959 * Two separate bpf_obj_new will also have different reg->id. 6960 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 6961 * clears reg->id after value_or_null->value transition, since the verifier only 6962 * cares about the range of access to valid map value pointer and doesn't care 6963 * about actual address of the map element. 6964 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 6965 * reg->id > 0 after value_or_null->value transition. By doing so 6966 * two bpf_map_lookups will be considered two different pointers that 6967 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 6968 * returned from bpf_obj_new. 6969 * The verifier allows taking only one bpf_spin_lock at a time to avoid 6970 * dead-locks. 6971 * Since only one bpf_spin_lock is allowed the checks are simpler than 6972 * reg_is_refcounted() logic. The verifier needs to remember only 6973 * one spin_lock instead of array of acquired_refs. 6974 * env->cur_state->active_locks remembers which map value element or allocated 6975 * object got locked and clears it after bpf_spin_unlock. 6976 */ 6977 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags) 6978 { 6979 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK; 6980 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin"; 6981 struct bpf_verifier_state *cur = env->cur_state; 6982 bool is_const = tnum_is_const(reg->var_off); 6983 bool is_irq = flags & PROCESS_LOCK_IRQ; 6984 u64 val = reg->var_off.value; 6985 struct bpf_map *map = NULL; 6986 struct btf *btf = NULL; 6987 struct btf_record *rec; 6988 u32 spin_lock_off; 6989 int err; 6990 6991 if (!is_const) { 6992 verbose(env, 6993 "%s doesn't have constant offset. %s_lock has to be at the constant offset\n", 6994 reg_arg_name(env, argno), lock_str); 6995 return -EINVAL; 6996 } 6997 if (reg->type == PTR_TO_MAP_VALUE) { 6998 map = reg->map_ptr; 6999 if (!map->btf) { 7000 verbose(env, 7001 "map '%s' has to have BTF in order to use %s_lock\n", 7002 map->name, lock_str); 7003 return -EINVAL; 7004 } 7005 } else { 7006 btf = reg->btf; 7007 } 7008 7009 rec = reg_btf_record(reg); 7010 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) { 7011 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local", 7012 map ? map->name : "kptr", lock_str); 7013 return -EINVAL; 7014 } 7015 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off; 7016 if (spin_lock_off != val) { 7017 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n", 7018 val, lock_str, spin_lock_off); 7019 return -EINVAL; 7020 } 7021 if (is_lock) { 7022 void *ptr; 7023 int type; 7024 7025 if (map) 7026 ptr = map; 7027 else 7028 ptr = btf; 7029 7030 if (!is_res_lock && cur->active_locks) { 7031 if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) { 7032 verbose(env, 7033 "Locking two bpf_spin_locks are not allowed\n"); 7034 return -EINVAL; 7035 } 7036 } else if (is_res_lock && cur->active_locks) { 7037 if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) { 7038 verbose(env, "Acquiring the same lock again, AA deadlock detected\n"); 7039 return -EINVAL; 7040 } 7041 } 7042 7043 if (is_res_lock && is_irq) 7044 type = REF_TYPE_RES_LOCK_IRQ; 7045 else if (is_res_lock) 7046 type = REF_TYPE_RES_LOCK; 7047 else 7048 type = REF_TYPE_LOCK; 7049 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr); 7050 if (err < 0) { 7051 verbose(env, "Failed to acquire lock state\n"); 7052 return err; 7053 } 7054 } else { 7055 void *ptr; 7056 int type; 7057 7058 if (map) 7059 ptr = map; 7060 else 7061 ptr = btf; 7062 7063 if (!cur->active_locks) { 7064 verbose(env, "%s_unlock without taking a lock\n", lock_str); 7065 return -EINVAL; 7066 } 7067 7068 if (is_res_lock && is_irq) 7069 type = REF_TYPE_RES_LOCK_IRQ; 7070 else if (is_res_lock) 7071 type = REF_TYPE_RES_LOCK; 7072 else 7073 type = REF_TYPE_LOCK; 7074 if (!find_lock_state(cur, type, reg->id, ptr)) { 7075 verbose(env, "%s_unlock of different lock\n", lock_str); 7076 return -EINVAL; 7077 } 7078 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) { 7079 verbose(env, "%s_unlock cannot be out of order\n", lock_str); 7080 return -EINVAL; 7081 } 7082 if (release_lock_state(cur, type, reg->id, ptr)) { 7083 verbose(env, "%s_unlock of different lock\n", lock_str); 7084 return -EINVAL; 7085 } 7086 7087 invalidate_non_owning_refs(env); 7088 } 7089 return 0; 7090 } 7091 7092 /* Check if @regno is a pointer to a specific field in a map value */ 7093 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7094 enum btf_field_type field_type, 7095 struct bpf_map_desc *map_desc) 7096 { 7097 bool is_const = tnum_is_const(reg->var_off); 7098 struct bpf_map *map = reg->map_ptr; 7099 u64 val = reg->var_off.value; 7100 const char *struct_name = btf_field_type_name(field_type); 7101 int field_off = -1; 7102 7103 if (!is_const) { 7104 verbose(env, 7105 "%s doesn't have constant offset. %s has to be at the constant offset\n", 7106 reg_arg_name(env, argno), struct_name); 7107 return -EINVAL; 7108 } 7109 if (!map->btf) { 7110 verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name, 7111 struct_name); 7112 return -EINVAL; 7113 } 7114 if (!btf_record_has_field(map->record, field_type)) { 7115 verbose(env, "map '%s' has no valid %s\n", map->name, struct_name); 7116 return -EINVAL; 7117 } 7118 switch (field_type) { 7119 case BPF_TIMER: 7120 field_off = map->record->timer_off; 7121 break; 7122 case BPF_TASK_WORK: 7123 field_off = map->record->task_work_off; 7124 break; 7125 case BPF_WORKQUEUE: 7126 field_off = map->record->wq_off; 7127 break; 7128 default: 7129 verifier_bug(env, "unsupported BTF field type: %s\n", struct_name); 7130 return -EINVAL; 7131 } 7132 if (field_off != val) { 7133 verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n", 7134 val, struct_name, field_off); 7135 return -EINVAL; 7136 } 7137 if (map_desc->ptr) { 7138 verifier_bug(env, "Two map pointers in a %s helper", struct_name); 7139 return -EFAULT; 7140 } 7141 map_desc->uid = reg->map_uid; 7142 map_desc->ptr = map; 7143 return 0; 7144 } 7145 7146 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7147 struct bpf_map_desc *map) 7148 { 7149 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 7150 verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n"); 7151 return -EOPNOTSUPP; 7152 } 7153 return check_map_field_pointer(env, reg, argno, BPF_TIMER, map); 7154 } 7155 7156 static int process_timer_helper(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7157 struct bpf_call_arg_meta *meta) 7158 { 7159 return process_timer_func(env, reg, argno, &meta->map); 7160 } 7161 7162 static int process_timer_kfunc(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7163 struct bpf_kfunc_call_arg_meta *meta) 7164 { 7165 return process_timer_func(env, reg, argno, &meta->map); 7166 } 7167 7168 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7169 struct bpf_call_arg_meta *meta) 7170 { 7171 struct bpf_reg_state *reg = reg_state(env, regno); 7172 struct btf_field *kptr_field; 7173 struct bpf_map *map_ptr; 7174 struct btf_record *rec; 7175 u32 kptr_off; 7176 7177 if (type_is_ptr_alloc_obj(reg->type)) { 7178 rec = reg_btf_record(reg); 7179 } else { /* PTR_TO_MAP_VALUE */ 7180 map_ptr = reg->map_ptr; 7181 if (!map_ptr->btf) { 7182 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7183 map_ptr->name); 7184 return -EINVAL; 7185 } 7186 rec = map_ptr->record; 7187 meta->map.ptr = map_ptr; 7188 } 7189 7190 if (!tnum_is_const(reg->var_off)) { 7191 verbose(env, 7192 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7193 regno); 7194 return -EINVAL; 7195 } 7196 7197 if (!btf_record_has_field(rec, BPF_KPTR)) { 7198 verbose(env, "R%d has no valid kptr\n", regno); 7199 return -EINVAL; 7200 } 7201 7202 kptr_off = reg->var_off.value; 7203 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 7204 if (!kptr_field) { 7205 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7206 return -EACCES; 7207 } 7208 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7209 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7210 return -EACCES; 7211 } 7212 meta->kptr_field = kptr_field; 7213 return 0; 7214 } 7215 7216 /* 7217 * Validate dynptr arguments for helper, kfunc and subprog. 7218 * 7219 * @dynptr is both input and output. It is populated when the argument is 7220 * tagged with MEM_UNINIT (i.e., the dynptr argument that will be constructed) 7221 * and consumed when the argument is expecting to be an initialized dynptr. 7222 * @parent_id is used to track the referenced parent object (e.g., file or skb in 7223 * qdisc program) when constructing a dynptr. 7224 * 7225 * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7226 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7227 * 7228 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7229 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7230 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7231 * 7232 * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the 7233 * dynptr points to. At the first level, the verifier will make sure a 7234 * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of 7235 * a dynptr's view (i.e., start and offset) is not tracked as there is not such 7236 * use case. The second level is tracked using the upper bit of bpf_dynptr->size 7237 * and checked dynamically during runtime. 7238 */ 7239 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7240 argno_t argno, int insn_idx, enum bpf_arg_type arg_type, 7241 struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr) 7242 { 7243 int spi, err = 0; 7244 7245 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 7246 verbose(env, 7247 "%s expected pointer to stack or const struct bpf_dynptr\n", 7248 reg_arg_name(env, argno)); 7249 return -EINVAL; 7250 } 7251 7252 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7253 * constructing a mutable bpf_dynptr object. 7254 * 7255 * Currently, this is only possible with PTR_TO_STACK 7256 * pointing to a region of at least 16 bytes which doesn't 7257 * contain an existing bpf_dynptr. 7258 * 7259 * OBJ_RELEASE - Points to a initialized bpf_dynptr that will be 7260 * destroyed. 7261 * 7262 * None - Points to a initialized dynptr that cannot be 7263 * reinitialized or destroyed. However, the view of the 7264 * dynptr and the memory it points to may be mutated. 7265 */ 7266 if (arg_type & MEM_UNINIT) { 7267 int i; 7268 7269 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7270 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7271 return -EINVAL; 7272 } 7273 7274 /* we write BPF_DW bits (8 bytes) at a time */ 7275 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7276 err = check_mem_access(env, insn_idx, reg, argno, 7277 i, BPF_DW, BPF_WRITE, -1, false, false); 7278 if (err) 7279 return err; 7280 } 7281 7282 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, ref_obj, dynptr); 7283 } else /* OBJ_RELEASE and None case from above */ { 7284 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7285 if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) { 7286 verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n"); 7287 return -EINVAL; 7288 } 7289 7290 if (!is_dynptr_reg_valid_init(env, reg)) { 7291 verbose(env, "Expected an initialized dynptr as %s\n", 7292 reg_arg_name(env, argno)); 7293 return -EINVAL; 7294 } 7295 7296 /* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */ 7297 if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) { 7298 verbose(env, 7299 "Expected a dynptr of type %s as %s\n", 7300 dynptr_type_str(arg_to_dynptr_type(arg_type)), 7301 reg_arg_name(env, argno)); 7302 return -EINVAL; 7303 } 7304 7305 if (reg->type != CONST_PTR_TO_DYNPTR) { 7306 struct bpf_func_state *state = bpf_func(env, reg); 7307 7308 spi = dynptr_get_spi(env, reg); 7309 if (spi < 0) 7310 return spi; 7311 7312 /* 7313 * For CONST_PTR_TO_DYNPTR, reg is already scratched by check_reg_arg 7314 * in check_helper_call and mark_btf_func_reg_size in check_kfunc_call. 7315 */ 7316 mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS); 7317 7318 reg = &state->stack[spi].spilled_ptr; 7319 } 7320 7321 if (dynptr) { 7322 dynptr->type = reg->dynptr.type; 7323 dynptr->id = reg->id; 7324 dynptr->parent_id = reg->parent_id; 7325 } 7326 } 7327 return err; 7328 } 7329 7330 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7331 { 7332 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7333 } 7334 7335 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7336 { 7337 return meta->kfunc_flags & KF_ITER_NEW; 7338 } 7339 7340 7341 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7342 { 7343 return meta->kfunc_flags & KF_ITER_DESTROY; 7344 } 7345 7346 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 7347 const struct btf_param *arg) 7348 { 7349 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7350 * kfunc is iter state pointer 7351 */ 7352 if (is_iter_kfunc(meta)) 7353 return arg_idx == 0; 7354 7355 /* iter passed as an argument to a generic kfunc */ 7356 return btf_param_match_suffix(meta->btf, arg, "__iter"); 7357 } 7358 7359 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx, 7360 struct bpf_kfunc_call_arg_meta *meta) 7361 { 7362 struct bpf_func_state *state = bpf_func(env, reg); 7363 const struct btf_type *t; 7364 u32 arg_idx = arg_idx_from_argno(argno); 7365 int spi, err, i, nr_slots, btf_id; 7366 7367 if (reg->type != PTR_TO_STACK) { 7368 verbose(env, "%s expected pointer to an iterator on stack\n", 7369 reg_arg_name(env, argno)); 7370 return -EINVAL; 7371 } 7372 7373 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 7374 * ensures struct convention, so we wouldn't need to do any BTF 7375 * validation here. But given iter state can be passed as a parameter 7376 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 7377 * conservative here. 7378 */ 7379 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg_idx); 7380 if (btf_id < 0) { 7381 verbose(env, "expected valid iter pointer as %s\n", 7382 reg_arg_name(env, argno)); 7383 return -EINVAL; 7384 } 7385 t = btf_type_by_id(meta->btf, btf_id); 7386 nr_slots = t->size / BPF_REG_SIZE; 7387 7388 if (is_iter_new_kfunc(meta)) { 7389 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7390 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7391 verbose(env, "expected uninitialized iter_%s as %s\n", 7392 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7393 return -EINVAL; 7394 } 7395 7396 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7397 err = check_mem_access(env, insn_idx, reg, argno, 7398 i, BPF_DW, BPF_WRITE, -1, false, false); 7399 if (err) 7400 return err; 7401 } 7402 7403 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7404 if (err) 7405 return err; 7406 } else { 7407 /* iter_next() or iter_destroy(), as well as any kfunc 7408 * accepting iter argument, expect initialized iter state 7409 */ 7410 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7411 switch (err) { 7412 case 0: 7413 break; 7414 case -EINVAL: 7415 verbose(env, "expected an initialized iter_%s as %s\n", 7416 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7417 return err; 7418 case -EPROTO: 7419 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7420 return err; 7421 default: 7422 return err; 7423 } 7424 7425 spi = iter_get_spi(env, reg, nr_slots); 7426 if (spi < 0) 7427 return spi; 7428 7429 mark_stack_slots_scratched(env, spi, nr_slots); 7430 7431 /* remember meta->iter info for process_iter_next_call() */ 7432 meta->iter.spi = spi; 7433 meta->iter.frameno = reg->frameno; 7434 update_ref_obj(&meta->ref_obj, &state->stack[spi].spilled_ptr); 7435 7436 if (is_iter_destroy_kfunc(meta)) { 7437 err = unmark_stack_slots_iter(env, reg, nr_slots); 7438 if (err) 7439 return err; 7440 } 7441 } 7442 7443 return 0; 7444 } 7445 7446 /* Look for a previous loop entry at insn_idx: nearest parent state 7447 * stopped at insn_idx with callsites matching those in cur->frame. 7448 */ 7449 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7450 struct bpf_verifier_state *cur, 7451 int insn_idx) 7452 { 7453 struct bpf_verifier_state_list *sl; 7454 struct bpf_verifier_state *st; 7455 struct list_head *pos, *head; 7456 7457 /* Explored states are pushed in stack order, most recent states come first */ 7458 head = bpf_explored_state(env, insn_idx); 7459 list_for_each(pos, head) { 7460 sl = container_of(pos, struct bpf_verifier_state_list, node); 7461 /* If st->branches != 0 state is a part of current DFS verification path, 7462 * hence cur & st for a loop. 7463 */ 7464 st = &sl->state; 7465 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7466 st->dfs_depth < cur->dfs_depth) 7467 return st; 7468 } 7469 7470 return NULL; 7471 } 7472 7473 /* 7474 * Check if scalar registers are exact for the purpose of not widening. 7475 * More lenient than regs_exact() 7476 */ 7477 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold, 7478 const struct bpf_reg_state *rcur) 7479 { 7480 return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)); 7481 } 7482 7483 static void maybe_widen_reg(struct bpf_verifier_env *env, 7484 struct bpf_reg_state *rold, struct bpf_reg_state *rcur) 7485 { 7486 if (rold->type != SCALAR_VALUE) 7487 return; 7488 if (rold->type != rcur->type) 7489 return; 7490 if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur)) 7491 return; 7492 __mark_reg_unknown(env, rcur); 7493 } 7494 7495 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7496 struct bpf_verifier_state *old, 7497 struct bpf_verifier_state *cur) 7498 { 7499 struct bpf_func_state *fold, *fcur; 7500 int i, fr, num_slots; 7501 7502 for (fr = old->curframe; fr >= 0; fr--) { 7503 fold = old->frame[fr]; 7504 fcur = cur->frame[fr]; 7505 7506 for (i = 0; i < MAX_BPF_REG; i++) 7507 maybe_widen_reg(env, 7508 &fold->regs[i], 7509 &fcur->regs[i]); 7510 7511 num_slots = min(fold->allocated_stack / BPF_REG_SIZE, 7512 fcur->allocated_stack / BPF_REG_SIZE); 7513 for (i = 0; i < num_slots; i++) { 7514 if (!bpf_is_spilled_reg(&fold->stack[i]) || 7515 !bpf_is_spilled_reg(&fcur->stack[i])) 7516 continue; 7517 7518 maybe_widen_reg(env, 7519 &fold->stack[i].spilled_ptr, 7520 &fcur->stack[i].spilled_ptr); 7521 } 7522 } 7523 return 0; 7524 } 7525 7526 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 7527 struct bpf_kfunc_call_arg_meta *meta) 7528 { 7529 int iter_frameno = meta->iter.frameno; 7530 int iter_spi = meta->iter.spi; 7531 7532 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7533 } 7534 7535 /* process_iter_next_call() is called when verifier gets to iterator's next 7536 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7537 * to it as just "iter_next()" in comments below. 7538 * 7539 * BPF verifier relies on a crucial contract for any iter_next() 7540 * implementation: it should *eventually* return NULL, and once that happens 7541 * it should keep returning NULL. That is, once iterator exhausts elements to 7542 * iterate, it should never reset or spuriously return new elements. 7543 * 7544 * With the assumption of such contract, process_iter_next_call() simulates 7545 * a fork in the verifier state to validate loop logic correctness and safety 7546 * without having to simulate infinite amount of iterations. 7547 * 7548 * In current state, we first assume that iter_next() returned NULL and 7549 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7550 * conditions we should not form an infinite loop and should eventually reach 7551 * exit. 7552 * 7553 * Besides that, we also fork current state and enqueue it for later 7554 * verification. In a forked state we keep iterator state as ACTIVE 7555 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7556 * also bump iteration depth to prevent erroneous infinite loop detection 7557 * later on (see iter_active_depths_differ() comment for details). In this 7558 * state we assume that we'll eventually loop back to another iter_next() 7559 * calls (it could be in exactly same location or in some other instruction, 7560 * it doesn't matter, we don't make any unnecessary assumptions about this, 7561 * everything revolves around iterator state in a stack slot, not which 7562 * instruction is calling iter_next()). When that happens, we either will come 7563 * to iter_next() with equivalent state and can conclude that next iteration 7564 * will proceed in exactly the same way as we just verified, so it's safe to 7565 * assume that loop converges. If not, we'll go on another iteration 7566 * simulation with a different input state, until all possible starting states 7567 * are validated or we reach maximum number of instructions limit. 7568 * 7569 * This way, we will either exhaustively discover all possible input states 7570 * that iterator loop can start with and eventually will converge, or we'll 7571 * effectively regress into bounded loop simulation logic and either reach 7572 * maximum number of instructions if loop is not provably convergent, or there 7573 * is some statically known limit on number of iterations (e.g., if there is 7574 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7575 * 7576 * Iteration convergence logic in is_state_visited() relies on exact 7577 * states comparison, which ignores read and precision marks. 7578 * This is necessary because read and precision marks are not finalized 7579 * while in the loop. Exact comparison might preclude convergence for 7580 * simple programs like below: 7581 * 7582 * i = 0; 7583 * while(iter_next(&it)) 7584 * i++; 7585 * 7586 * At each iteration step i++ would produce a new distinct state and 7587 * eventually instruction processing limit would be reached. 7588 * 7589 * To avoid such behavior speculatively forget (widen) range for 7590 * imprecise scalar registers, if those registers were not precise at the 7591 * end of the previous iteration and do not match exactly. 7592 * 7593 * This is a conservative heuristic that allows to verify wide range of programs, 7594 * however it precludes verification of programs that conjure an 7595 * imprecise value on the first loop iteration and use it as precise on a second. 7596 * For example, the following safe program would fail to verify: 7597 * 7598 * struct bpf_num_iter it; 7599 * int arr[10]; 7600 * int i = 0, a = 0; 7601 * bpf_iter_num_new(&it, 0, 10); 7602 * while (bpf_iter_num_next(&it)) { 7603 * if (a == 0) { 7604 * a = 1; 7605 * i = 7; // Because i changed verifier would forget 7606 * // it's range on second loop entry. 7607 * } else { 7608 * arr[i] = 42; // This would fail to verify. 7609 * } 7610 * } 7611 * bpf_iter_num_destroy(&it); 7612 */ 7613 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7614 struct bpf_kfunc_call_arg_meta *meta) 7615 { 7616 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7617 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7618 struct bpf_reg_state *cur_iter, *queued_iter; 7619 7620 BTF_TYPE_EMIT(struct bpf_iter); 7621 7622 cur_iter = get_iter_from_state(cur_st, meta); 7623 7624 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7625 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7626 verifier_bug(env, "unexpected iterator state %d (%s)", 7627 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7628 return -EFAULT; 7629 } 7630 7631 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7632 /* Because iter_next() call is a checkpoint is_state_visitied() 7633 * should guarantee parent state with same call sites and insn_idx. 7634 */ 7635 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7636 !same_callsites(cur_st->parent, cur_st)) { 7637 verifier_bug(env, "bad parent state for iter next call"); 7638 return -EFAULT; 7639 } 7640 /* Note cur_st->parent in the call below, it is necessary to skip 7641 * checkpoint created for cur_st by is_state_visited() 7642 * right at this instruction. 7643 */ 7644 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7645 /* branch out active iter state */ 7646 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7647 if (IS_ERR(queued_st)) 7648 return PTR_ERR(queued_st); 7649 7650 queued_iter = get_iter_from_state(queued_st, meta); 7651 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7652 queued_iter->iter.depth++; 7653 if (prev_st) 7654 widen_imprecise_scalars(env, prev_st, queued_st); 7655 7656 queued_fr = queued_st->frame[queued_st->curframe]; 7657 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7658 } 7659 7660 /* switch to DRAINED state, but keep the depth unchanged */ 7661 /* mark current iter state as drained and assume returned NULL */ 7662 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7663 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7664 7665 return 0; 7666 } 7667 7668 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7669 { 7670 return type == ARG_CONST_SIZE || 7671 type == ARG_CONST_SIZE_OR_ZERO; 7672 } 7673 7674 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 7675 { 7676 return base_type(type) == ARG_PTR_TO_MEM && 7677 type & MEM_UNINIT; 7678 } 7679 7680 static bool arg_type_is_release(enum bpf_arg_type type) 7681 { 7682 return type & OBJ_RELEASE; 7683 } 7684 7685 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7686 { 7687 return base_type(type) == ARG_PTR_TO_DYNPTR; 7688 } 7689 7690 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7691 const struct bpf_call_arg_meta *meta, 7692 enum bpf_arg_type *arg_type) 7693 { 7694 if (!meta->map.ptr) { 7695 /* kernel subsystem misconfigured verifier */ 7696 verifier_bug(env, "invalid map_ptr to access map->type"); 7697 return -EFAULT; 7698 } 7699 7700 switch (meta->map.ptr->map_type) { 7701 case BPF_MAP_TYPE_SOCKMAP: 7702 case BPF_MAP_TYPE_SOCKHASH: 7703 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7704 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7705 } else { 7706 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7707 return -EINVAL; 7708 } 7709 break; 7710 case BPF_MAP_TYPE_BLOOM_FILTER: 7711 if (meta->func_id == BPF_FUNC_map_peek_elem) 7712 *arg_type = ARG_PTR_TO_MAP_VALUE; 7713 break; 7714 default: 7715 break; 7716 } 7717 return 0; 7718 } 7719 7720 struct bpf_reg_types { 7721 const enum bpf_reg_type types[10]; 7722 u32 *btf_id; 7723 }; 7724 7725 static const struct bpf_reg_types sock_types = { 7726 .types = { 7727 PTR_TO_SOCK_COMMON, 7728 PTR_TO_SOCKET, 7729 PTR_TO_TCP_SOCK, 7730 PTR_TO_XDP_SOCK, 7731 }, 7732 }; 7733 7734 #ifdef CONFIG_NET 7735 static const struct bpf_reg_types btf_id_sock_common_types = { 7736 .types = { 7737 PTR_TO_SOCK_COMMON, 7738 PTR_TO_SOCKET, 7739 PTR_TO_TCP_SOCK, 7740 PTR_TO_XDP_SOCK, 7741 PTR_TO_BTF_ID, 7742 PTR_TO_BTF_ID | PTR_TRUSTED, 7743 }, 7744 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7745 }; 7746 #endif 7747 7748 static const struct bpf_reg_types mem_types = { 7749 .types = { 7750 PTR_TO_STACK, 7751 PTR_TO_PACKET, 7752 PTR_TO_PACKET_META, 7753 PTR_TO_MAP_KEY, 7754 PTR_TO_MAP_VALUE, 7755 PTR_TO_MEM, 7756 PTR_TO_MEM | MEM_RINGBUF, 7757 PTR_TO_BUF, 7758 PTR_TO_BTF_ID | PTR_TRUSTED, 7759 PTR_TO_CTX, 7760 }, 7761 }; 7762 7763 static const struct bpf_reg_types spin_lock_types = { 7764 .types = { 7765 PTR_TO_MAP_VALUE, 7766 PTR_TO_BTF_ID | MEM_ALLOC, 7767 } 7768 }; 7769 7770 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7771 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7772 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7773 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7774 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7775 static const struct bpf_reg_types btf_ptr_types = { 7776 .types = { 7777 PTR_TO_BTF_ID, 7778 PTR_TO_BTF_ID | PTR_TRUSTED, 7779 PTR_TO_BTF_ID | MEM_RCU, 7780 }, 7781 }; 7782 static const struct bpf_reg_types percpu_btf_ptr_types = { 7783 .types = { 7784 PTR_TO_BTF_ID | MEM_PERCPU, 7785 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 7786 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7787 } 7788 }; 7789 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7790 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7791 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7792 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7793 static const struct bpf_reg_types kptr_xchg_dest_types = { 7794 .types = { 7795 PTR_TO_MAP_VALUE, 7796 PTR_TO_BTF_ID | MEM_ALLOC, 7797 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF, 7798 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU, 7799 } 7800 }; 7801 static const struct bpf_reg_types dynptr_types = { 7802 .types = { 7803 PTR_TO_STACK, 7804 CONST_PTR_TO_DYNPTR, 7805 } 7806 }; 7807 7808 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7809 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7810 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7811 [ARG_CONST_SIZE] = &scalar_types, 7812 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7813 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7814 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7815 [ARG_PTR_TO_CTX] = &context_types, 7816 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7817 #ifdef CONFIG_NET 7818 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7819 #endif 7820 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7821 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7822 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7823 [ARG_PTR_TO_MEM] = &mem_types, 7824 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7825 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7826 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7827 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7828 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7829 [ARG_PTR_TO_TIMER] = &timer_types, 7830 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 7831 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7832 }; 7833 7834 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7835 enum bpf_arg_type arg_type, 7836 const u32 *arg_btf_id, 7837 struct bpf_call_arg_meta *meta) 7838 { 7839 enum bpf_reg_type expected, type = reg->type; 7840 const struct bpf_reg_types *compatible; 7841 int i, j, err; 7842 7843 compatible = compatible_reg_types[base_type(arg_type)]; 7844 if (!compatible) { 7845 verifier_bug(env, "unsupported arg type %d", arg_type); 7846 return -EFAULT; 7847 } 7848 7849 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7850 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7851 * 7852 * Same for MAYBE_NULL: 7853 * 7854 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7855 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7856 * 7857 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 7858 * 7859 * Therefore we fold these flags depending on the arg_type before comparison. 7860 */ 7861 if (arg_type & MEM_RDONLY) 7862 type &= ~MEM_RDONLY; 7863 if (arg_type & PTR_MAYBE_NULL) 7864 type &= ~PTR_MAYBE_NULL; 7865 if (base_type(arg_type) == ARG_PTR_TO_MEM) 7866 type &= ~DYNPTR_TYPE_FLAG_MASK; 7867 7868 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 7869 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && reg_from_argno(argno) == BPF_REG_2) { 7870 type &= ~MEM_ALLOC; 7871 type &= ~MEM_PERCPU; 7872 } 7873 7874 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7875 expected = compatible->types[i]; 7876 if (expected == NOT_INIT) 7877 break; 7878 7879 if (type == expected) 7880 goto found; 7881 } 7882 7883 verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7884 for (j = 0; j + 1 < i; j++) 7885 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7886 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7887 return -EACCES; 7888 7889 found: 7890 if (base_type(reg->type) != PTR_TO_BTF_ID) 7891 return 0; 7892 7893 if (compatible == &mem_types) { 7894 if (!(arg_type & MEM_RDONLY)) { 7895 verbose(env, 7896 "%s() may write into memory pointed by %s type=%s\n", 7897 func_id_name(meta->func_id), 7898 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7899 return -EACCES; 7900 } 7901 return 0; 7902 } 7903 7904 switch ((int)reg->type) { 7905 case PTR_TO_BTF_ID: 7906 case PTR_TO_BTF_ID | PTR_TRUSTED: 7907 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 7908 case PTR_TO_BTF_ID | MEM_RCU: 7909 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 7910 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 7911 { 7912 /* For bpf_sk_release, it needs to match against first member 7913 * 'struct sock_common', hence make an exception for it. This 7914 * allows bpf_sk_release to work for multiple socket types. 7915 */ 7916 bool strict_type_match = arg_type_is_release(arg_type) && 7917 meta->func_id != BPF_FUNC_sk_release; 7918 7919 if (type_may_be_null(reg->type) && 7920 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 7921 verbose(env, "Possibly NULL pointer passed to helper %s\n", 7922 reg_arg_name(env, argno)); 7923 return -EACCES; 7924 } 7925 7926 if (!arg_btf_id) { 7927 if (!compatible->btf_id) { 7928 verifier_bug(env, "missing arg compatible BTF ID"); 7929 return -EFAULT; 7930 } 7931 arg_btf_id = compatible->btf_id; 7932 } 7933 7934 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7935 if (map_kptr_match_type(env, meta->kptr_field, reg, reg_from_argno(argno))) 7936 return -EACCES; 7937 } else { 7938 if (arg_btf_id == BPF_PTR_POISON) { 7939 verbose(env, "verifier internal error:"); 7940 verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n", 7941 reg_arg_name(env, argno)); 7942 return -EACCES; 7943 } 7944 7945 err = __check_ptr_off_reg(env, reg, argno, true); 7946 if (err) 7947 return err; 7948 7949 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 7950 reg->var_off.value, btf_vmlinux, *arg_btf_id, 7951 strict_type_match, !type_is_alloc(reg->type))) { 7952 verbose(env, "%s is of type %s but %s is expected\n", 7953 reg_arg_name(env, argno), 7954 btf_type_name(reg->btf, reg->btf_id), 7955 btf_type_name(btf_vmlinux, *arg_btf_id)); 7956 return -EACCES; 7957 } 7958 } 7959 break; 7960 } 7961 case PTR_TO_BTF_ID | MEM_ALLOC: 7962 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 7963 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 7964 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 7965 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 7966 meta->func_id != BPF_FUNC_kptr_xchg) { 7967 verifier_bug(env, "unimplemented handling of MEM_ALLOC"); 7968 return -EFAULT; 7969 } 7970 /* Check if local kptr in src arg matches kptr in dst arg */ 7971 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7972 int regno = reg_from_argno(argno); 7973 7974 if (regno == BPF_REG_2 && 7975 map_kptr_match_type(env, meta->kptr_field, reg, regno)) 7976 return -EACCES; 7977 } 7978 break; 7979 case PTR_TO_BTF_ID | MEM_PERCPU: 7980 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 7981 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 7982 /* Handled by helper specific checks */ 7983 break; 7984 default: 7985 verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match"); 7986 return -EFAULT; 7987 } 7988 return 0; 7989 } 7990 7991 static struct btf_field * 7992 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 7993 { 7994 struct btf_field *field; 7995 struct btf_record *rec; 7996 7997 rec = reg_btf_record(reg); 7998 if (!rec) 7999 return NULL; 8000 8001 field = btf_record_find(rec, off, fields); 8002 if (!field) 8003 return NULL; 8004 8005 return field; 8006 } 8007 8008 static int __check_func_arg_reg_off(struct bpf_verifier_env *env, 8009 const struct bpf_reg_state *reg, argno_t argno, 8010 enum bpf_arg_type arg_type, 8011 bool btf_id_fixed_off_ok) 8012 { 8013 u32 type = reg->type; 8014 8015 /* When referenced register is passed to release function, its fixed 8016 * offset must be 0. 8017 * 8018 * We will check arg_type_is_release reg has id when storing 8019 * meta->release_regno. 8020 */ 8021 if (arg_type_is_release(arg_type)) { 8022 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8023 * may not directly point to the object being released, but to 8024 * dynptr pointing to such object, which might be at some offset 8025 * on the stack. In that case, we simply to fallback to the 8026 * default handling. 8027 */ 8028 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8029 return 0; 8030 8031 /* Doing check_ptr_off_reg check for the offset will catch this 8032 * because fixed_off_ok is false, but checking here allows us 8033 * to give the user a better error message. 8034 */ 8035 if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) { 8036 verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n", 8037 reg_arg_name(env, argno)); 8038 return -EINVAL; 8039 } 8040 } 8041 8042 switch (type) { 8043 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8044 case PTR_TO_STACK: 8045 case PTR_TO_PACKET: 8046 case PTR_TO_PACKET_META: 8047 case PTR_TO_MAP_KEY: 8048 case PTR_TO_MAP_VALUE: 8049 case PTR_TO_MEM: 8050 case PTR_TO_MEM | MEM_RDONLY: 8051 case PTR_TO_MEM | MEM_RINGBUF: 8052 case PTR_TO_BUF: 8053 case PTR_TO_BUF | MEM_RDONLY: 8054 case PTR_TO_ARENA: 8055 case SCALAR_VALUE: 8056 return 0; 8057 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8058 * fixed offset. 8059 */ 8060 case PTR_TO_BTF_ID: 8061 case PTR_TO_BTF_ID | MEM_ALLOC: 8062 case PTR_TO_BTF_ID | PTR_TRUSTED: 8063 case PTR_TO_BTF_ID | MEM_RCU: 8064 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8065 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8066 /* When referenced PTR_TO_BTF_ID is passed to release function, 8067 * its fixed offset must be 0. In the other cases, fixed offset 8068 * can be non-zero unless the caller requires otherwise. 8069 * var_off always must be 0 for PTR_TO_BTF_ID, hence we still 8070 * need to do checks instead of returning. 8071 */ 8072 return __check_ptr_off_reg(env, reg, argno, btf_id_fixed_off_ok); 8073 case PTR_TO_CTX: 8074 /* 8075 * Allow fixed and variable offsets for syscall context, but 8076 * only when the argument is passed as memory, not ctx, 8077 * otherwise we may get modified ctx in tail called programs and 8078 * global subprogs (that may act as extension prog hooks). 8079 */ 8080 if (arg_type != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog)) 8081 return 0; 8082 fallthrough; 8083 default: 8084 return __check_ptr_off_reg(env, reg, argno, false); 8085 } 8086 } 8087 8088 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8089 const struct bpf_reg_state *reg, argno_t argno, 8090 enum bpf_arg_type arg_type) 8091 { 8092 return __check_func_arg_reg_off(env, reg, argno, arg_type, true); 8093 } 8094 8095 static int check_arg_const_str(struct bpf_verifier_env *env, 8096 struct bpf_reg_state *reg, argno_t argno) 8097 { 8098 struct bpf_map *map = reg->map_ptr; 8099 int err; 8100 int map_off; 8101 u64 map_addr; 8102 char *str_ptr; 8103 8104 if (reg->type != PTR_TO_MAP_VALUE) 8105 return -EINVAL; 8106 8107 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 8108 verbose(env, "%s points to insn_array map which cannot be used as const string\n", 8109 reg_arg_name(env, argno)); 8110 return -EACCES; 8111 } 8112 8113 if (!bpf_map_is_rdonly(map)) { 8114 verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno)); 8115 return -EACCES; 8116 } 8117 8118 if (!tnum_is_const(reg->var_off)) { 8119 verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno)); 8120 return -EACCES; 8121 } 8122 8123 if (!map->ops->map_direct_value_addr) { 8124 verbose(env, "no direct value access support for this map type\n"); 8125 return -EACCES; 8126 } 8127 8128 err = check_map_access(env, reg, argno, 0, 8129 map->value_size - reg->var_off.value, false, 8130 ACCESS_HELPER); 8131 if (err) 8132 return err; 8133 8134 map_off = reg->var_off.value; 8135 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8136 if (err) { 8137 verbose(env, "direct value access on string failed\n"); 8138 return err; 8139 } 8140 8141 str_ptr = (char *)(long)(map_addr); 8142 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8143 verbose(env, "string is not zero-terminated\n"); 8144 return -EINVAL; 8145 } 8146 return 0; 8147 } 8148 8149 /* Returns constant key value in `value` if possible, else negative error */ 8150 static int get_constant_map_key(struct bpf_verifier_env *env, 8151 struct bpf_reg_state *key, 8152 u32 key_size, 8153 s64 *value) 8154 { 8155 struct bpf_func_state *state = bpf_func(env, key); 8156 struct bpf_reg_state *reg; 8157 int slot, spi, off; 8158 int spill_size = 0; 8159 int zero_size = 0; 8160 int stack_off; 8161 int i, err; 8162 u8 *stype; 8163 8164 if (!env->bpf_capable) 8165 return -EOPNOTSUPP; 8166 if (key->type != PTR_TO_STACK) 8167 return -EOPNOTSUPP; 8168 if (!tnum_is_const(key->var_off)) 8169 return -EOPNOTSUPP; 8170 8171 stack_off = key->var_off.value; 8172 slot = -stack_off - 1; 8173 spi = slot / BPF_REG_SIZE; 8174 off = slot % BPF_REG_SIZE; 8175 stype = state->stack[spi].slot_type; 8176 8177 /* First handle precisely tracked STACK_ZERO */ 8178 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) 8179 zero_size++; 8180 if (zero_size >= key_size) { 8181 *value = 0; 8182 return 0; 8183 } 8184 8185 /* Check that stack contains a scalar spill of expected size */ 8186 if (!bpf_is_spilled_scalar_reg(&state->stack[spi])) 8187 return -EOPNOTSUPP; 8188 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) 8189 spill_size++; 8190 if (spill_size != key_size) 8191 return -EOPNOTSUPP; 8192 8193 reg = &state->stack[spi].spilled_ptr; 8194 if (!tnum_is_const(reg->var_off)) 8195 /* Stack value not statically known */ 8196 return -EOPNOTSUPP; 8197 8198 /* We are relying on a constant value. So mark as precise 8199 * to prevent pruning on it. 8200 */ 8201 bpf_bt_set_frame_slot(&env->bt, key->frameno, spi); 8202 err = mark_chain_precision_batch(env, env->cur_state); 8203 if (err < 0) 8204 return err; 8205 8206 *value = reg->var_off.value; 8207 return 0; 8208 } 8209 8210 static bool can_elide_value_nullness(const struct bpf_map *map); 8211 8212 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8213 struct bpf_call_arg_meta *meta, 8214 const struct bpf_func_proto *fn, 8215 int insn_idx) 8216 { 8217 u32 regno = BPF_REG_1 + arg; 8218 struct bpf_reg_state *reg = reg_state(env, regno); 8219 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8220 argno_t argno = argno_from_arg(arg + 1); 8221 enum bpf_reg_type type = reg->type; 8222 u32 *arg_btf_id = NULL; 8223 u32 key_size; 8224 int err = 0; 8225 8226 if (arg_type == ARG_DONTCARE) 8227 return 0; 8228 8229 err = check_reg_arg(env, regno, SRC_OP); 8230 if (err) 8231 return err; 8232 8233 if (arg_type == ARG_ANYTHING) { 8234 if (is_pointer_value(env, regno)) { 8235 verbose(env, "R%d leaks addr into helper function\n", 8236 regno); 8237 return -EACCES; 8238 } 8239 return 0; 8240 } 8241 8242 if (type_is_pkt_pointer(type) && 8243 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8244 verbose(env, "helper access to the packet is not allowed\n"); 8245 return -EACCES; 8246 } 8247 8248 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8249 err = resolve_map_arg_type(env, meta, &arg_type); 8250 if (err) 8251 return err; 8252 } 8253 8254 if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) 8255 /* A NULL register has a SCALAR_VALUE type, so skip 8256 * type checking. 8257 */ 8258 goto skip_type_check; 8259 8260 /* arg_btf_id and arg_size are in a union. */ 8261 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8262 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8263 arg_btf_id = fn->arg_btf_id[arg]; 8264 8265 err = check_reg_type(env, reg, argno_from_reg(regno), arg_type, arg_btf_id, meta); 8266 if (err) 8267 return err; 8268 8269 err = check_func_arg_reg_off(env, reg, argno_from_reg(regno), arg_type); 8270 if (err) 8271 return err; 8272 8273 skip_type_check: 8274 if (arg_type_is_release(arg_type) && !arg_type_is_dynptr(arg_type) && 8275 !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) { 8276 verbose(env, "release helper %s expects referenced PTR_TO_BTF_ID passed to %s\n", 8277 func_id_name(meta->func_id), reg_arg_name(env, argno)); 8278 return -EINVAL; 8279 } 8280 8281 if (reg_is_referenced(env, reg)) 8282 update_ref_obj(&meta->ref_obj, reg); 8283 8284 switch (base_type(arg_type)) { 8285 case ARG_CONST_MAP_PTR: 8286 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8287 if (meta->map.ptr) { 8288 /* Use map_uid (which is unique id of inner map) to reject: 8289 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8290 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8291 * if (inner_map1 && inner_map2) { 8292 * timer = bpf_map_lookup_elem(inner_map1); 8293 * if (timer) 8294 * // mismatch would have been allowed 8295 * bpf_timer_init(timer, inner_map2); 8296 * } 8297 * 8298 * Comparing map_ptr is enough to distinguish normal and outer maps. 8299 */ 8300 if (meta->map.ptr != reg->map_ptr || 8301 meta->map.uid != reg->map_uid) { 8302 verbose(env, 8303 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8304 meta->map.uid, reg->map_uid); 8305 return -EINVAL; 8306 } 8307 } 8308 meta->map.ptr = reg->map_ptr; 8309 meta->map.uid = reg->map_uid; 8310 break; 8311 case ARG_PTR_TO_MAP_KEY: 8312 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8313 * check that [key, key + map->key_size) are within 8314 * stack limits and initialized 8315 */ 8316 if (!meta->map.ptr) { 8317 /* in function declaration map_ptr must come before 8318 * map_key, so that it's verified and known before 8319 * we have to check map_key here. Otherwise it means 8320 * that kernel subsystem misconfigured verifier 8321 */ 8322 verifier_bug(env, "invalid map_ptr to access map->key"); 8323 return -EFAULT; 8324 } 8325 key_size = meta->map.ptr->key_size; 8326 err = check_helper_mem_access(env, reg, argno_from_reg(regno), key_size, BPF_READ, false, NULL); 8327 if (err) 8328 return err; 8329 if (can_elide_value_nullness(meta->map.ptr)) { 8330 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key); 8331 if (err < 0) { 8332 meta->const_map_key = -1; 8333 if (err == -EOPNOTSUPP) 8334 err = 0; 8335 else 8336 return err; 8337 } 8338 } 8339 break; 8340 case ARG_PTR_TO_MAP_VALUE: 8341 if (type_may_be_null(arg_type) && bpf_register_is_null(reg)) 8342 return 0; 8343 8344 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8345 * check [value, value + map->value_size) validity 8346 */ 8347 if (!meta->map.ptr) { 8348 /* kernel subsystem misconfigured verifier */ 8349 verifier_bug(env, "invalid map_ptr to access map->value"); 8350 return -EFAULT; 8351 } 8352 meta->raw_mode = arg_type & MEM_UNINIT; 8353 err = check_helper_mem_access(env, reg, argno_from_reg(regno), meta->map.ptr->value_size, 8354 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8355 false, meta); 8356 break; 8357 case ARG_PTR_TO_PERCPU_BTF_ID: 8358 if (!reg->btf_id) { 8359 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8360 return -EACCES; 8361 } 8362 meta->ret_btf = reg->btf; 8363 meta->ret_btf_id = reg->btf_id; 8364 break; 8365 case ARG_PTR_TO_SPIN_LOCK: 8366 if (in_rbtree_lock_required_cb(env)) { 8367 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8368 return -EACCES; 8369 } 8370 if (meta->func_id == BPF_FUNC_spin_lock) { 8371 err = process_spin_lock(env, reg, argno_from_reg(regno), PROCESS_SPIN_LOCK); 8372 if (err) 8373 return err; 8374 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8375 err = process_spin_lock(env, reg, argno_from_reg(regno), 0); 8376 if (err) 8377 return err; 8378 } else { 8379 verifier_bug(env, "spin lock arg on unexpected helper"); 8380 return -EFAULT; 8381 } 8382 break; 8383 case ARG_PTR_TO_TIMER: 8384 err = process_timer_helper(env, reg, argno_from_reg(regno), meta); 8385 if (err) 8386 return err; 8387 break; 8388 case ARG_PTR_TO_FUNC: 8389 meta->subprogno = reg->subprogno; 8390 break; 8391 case ARG_PTR_TO_MEM: 8392 /* The access to this pointer is only checked when we hit the 8393 * next is_mem_size argument below. 8394 */ 8395 meta->raw_mode = arg_type & MEM_UNINIT; 8396 if (arg_type & MEM_FIXED_SIZE) { 8397 err = check_helper_mem_access(env, reg, argno_from_reg(regno), fn->arg_size[arg], 8398 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8399 false, meta); 8400 if (err) 8401 return err; 8402 if (arg_type & MEM_ALIGNED) 8403 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 8404 } 8405 break; 8406 case ARG_CONST_SIZE: 8407 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1), 8408 argno_from_reg(regno), 8409 fn->arg_type[arg - 1] & MEM_WRITE ? 8410 BPF_WRITE : BPF_READ, 8411 false, meta); 8412 break; 8413 case ARG_CONST_SIZE_OR_ZERO: 8414 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1), 8415 argno_from_reg(regno), 8416 fn->arg_type[arg - 1] & MEM_WRITE ? 8417 BPF_WRITE : BPF_READ, 8418 true, meta); 8419 break; 8420 case ARG_PTR_TO_DYNPTR: 8421 err = process_dynptr_func(env, reg, argno_from_reg(regno), insn_idx, arg_type, &meta->ref_obj, 8422 &meta->dynptr); 8423 if (err) 8424 return err; 8425 break; 8426 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8427 if (!tnum_is_const(reg->var_off)) { 8428 verbose(env, "R%d is not a known constant'\n", 8429 regno); 8430 return -EACCES; 8431 } 8432 meta->mem_size = reg->var_off.value; 8433 err = mark_chain_precision(env, regno); 8434 if (err) 8435 return err; 8436 break; 8437 case ARG_PTR_TO_CONST_STR: 8438 { 8439 err = check_arg_const_str(env, reg, argno_from_reg(regno)); 8440 if (err) 8441 return err; 8442 break; 8443 } 8444 case ARG_KPTR_XCHG_DEST: 8445 err = process_kptr_func(env, regno, meta); 8446 if (err) 8447 return err; 8448 break; 8449 } 8450 8451 return err; 8452 } 8453 8454 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8455 { 8456 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8457 enum bpf_prog_type type = resolve_prog_type(env->prog); 8458 8459 if (func_id != BPF_FUNC_map_update_elem && 8460 func_id != BPF_FUNC_map_delete_elem) 8461 return false; 8462 8463 /* It's not possible to get access to a locked struct sock in these 8464 * contexts, so updating is safe. 8465 */ 8466 switch (type) { 8467 case BPF_PROG_TYPE_TRACING: 8468 if (eatype == BPF_TRACE_ITER) 8469 return true; 8470 break; 8471 case BPF_PROG_TYPE_SOCK_OPS: 8472 /* map_update allowed only via dedicated helpers with event type checks */ 8473 if (func_id == BPF_FUNC_map_delete_elem) 8474 return true; 8475 break; 8476 case BPF_PROG_TYPE_SK_REUSEPORT: 8477 case BPF_PROG_TYPE_SK_LOOKUP: 8478 return true; 8479 default: 8480 break; 8481 } 8482 8483 verbose(env, "cannot update sockmap in this context\n"); 8484 return false; 8485 } 8486 8487 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8488 { 8489 return env->prog->jit_requested && 8490 bpf_jit_supports_subprog_tailcalls(); 8491 } 8492 8493 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8494 struct bpf_map *map, int func_id) 8495 { 8496 if (!map) 8497 return 0; 8498 8499 /* We need a two way check, first is from map perspective ... */ 8500 switch (map->map_type) { 8501 case BPF_MAP_TYPE_PROG_ARRAY: 8502 if (func_id != BPF_FUNC_tail_call) 8503 goto error; 8504 break; 8505 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8506 if (func_id != BPF_FUNC_perf_event_read && 8507 func_id != BPF_FUNC_perf_event_output && 8508 func_id != BPF_FUNC_skb_output && 8509 func_id != BPF_FUNC_perf_event_read_value && 8510 func_id != BPF_FUNC_xdp_output) 8511 goto error; 8512 break; 8513 case BPF_MAP_TYPE_RINGBUF: 8514 if (func_id != BPF_FUNC_ringbuf_output && 8515 func_id != BPF_FUNC_ringbuf_reserve && 8516 func_id != BPF_FUNC_ringbuf_query && 8517 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8518 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8519 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8520 goto error; 8521 break; 8522 case BPF_MAP_TYPE_USER_RINGBUF: 8523 if (func_id != BPF_FUNC_user_ringbuf_drain) 8524 goto error; 8525 break; 8526 case BPF_MAP_TYPE_STACK_TRACE: 8527 if (func_id != BPF_FUNC_get_stackid) 8528 goto error; 8529 break; 8530 case BPF_MAP_TYPE_CGROUP_ARRAY: 8531 if (func_id != BPF_FUNC_skb_under_cgroup && 8532 func_id != BPF_FUNC_current_task_under_cgroup) 8533 goto error; 8534 break; 8535 case BPF_MAP_TYPE_CGROUP_STORAGE: 8536 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8537 if (func_id != BPF_FUNC_get_local_storage) 8538 goto error; 8539 break; 8540 case BPF_MAP_TYPE_DEVMAP: 8541 case BPF_MAP_TYPE_DEVMAP_HASH: 8542 if (func_id != BPF_FUNC_redirect_map && 8543 func_id != BPF_FUNC_map_lookup_elem) 8544 goto error; 8545 break; 8546 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8547 * appear. 8548 */ 8549 case BPF_MAP_TYPE_CPUMAP: 8550 if (func_id != BPF_FUNC_redirect_map) 8551 goto error; 8552 break; 8553 case BPF_MAP_TYPE_XSKMAP: 8554 if (func_id != BPF_FUNC_redirect_map && 8555 func_id != BPF_FUNC_map_lookup_elem) 8556 goto error; 8557 break; 8558 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8559 case BPF_MAP_TYPE_HASH_OF_MAPS: 8560 if (func_id != BPF_FUNC_map_lookup_elem) 8561 goto error; 8562 break; 8563 case BPF_MAP_TYPE_SOCKMAP: 8564 if (func_id != BPF_FUNC_sk_redirect_map && 8565 func_id != BPF_FUNC_sock_map_update && 8566 func_id != BPF_FUNC_msg_redirect_map && 8567 func_id != BPF_FUNC_sk_select_reuseport && 8568 func_id != BPF_FUNC_map_lookup_elem && 8569 !may_update_sockmap(env, func_id)) 8570 goto error; 8571 break; 8572 case BPF_MAP_TYPE_SOCKHASH: 8573 if (func_id != BPF_FUNC_sk_redirect_hash && 8574 func_id != BPF_FUNC_sock_hash_update && 8575 func_id != BPF_FUNC_msg_redirect_hash && 8576 func_id != BPF_FUNC_sk_select_reuseport && 8577 func_id != BPF_FUNC_map_lookup_elem && 8578 !may_update_sockmap(env, func_id)) 8579 goto error; 8580 break; 8581 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8582 if (func_id != BPF_FUNC_sk_select_reuseport) 8583 goto error; 8584 break; 8585 case BPF_MAP_TYPE_QUEUE: 8586 case BPF_MAP_TYPE_STACK: 8587 if (func_id != BPF_FUNC_map_peek_elem && 8588 func_id != BPF_FUNC_map_pop_elem && 8589 func_id != BPF_FUNC_map_push_elem) 8590 goto error; 8591 break; 8592 case BPF_MAP_TYPE_SK_STORAGE: 8593 if (func_id != BPF_FUNC_sk_storage_get && 8594 func_id != BPF_FUNC_sk_storage_delete && 8595 func_id != BPF_FUNC_kptr_xchg) 8596 goto error; 8597 break; 8598 case BPF_MAP_TYPE_INODE_STORAGE: 8599 if (func_id != BPF_FUNC_inode_storage_get && 8600 func_id != BPF_FUNC_inode_storage_delete && 8601 func_id != BPF_FUNC_kptr_xchg) 8602 goto error; 8603 break; 8604 case BPF_MAP_TYPE_TASK_STORAGE: 8605 if (func_id != BPF_FUNC_task_storage_get && 8606 func_id != BPF_FUNC_task_storage_delete && 8607 func_id != BPF_FUNC_kptr_xchg) 8608 goto error; 8609 break; 8610 case BPF_MAP_TYPE_CGRP_STORAGE: 8611 if (func_id != BPF_FUNC_cgrp_storage_get && 8612 func_id != BPF_FUNC_cgrp_storage_delete && 8613 func_id != BPF_FUNC_kptr_xchg) 8614 goto error; 8615 break; 8616 case BPF_MAP_TYPE_BLOOM_FILTER: 8617 if (func_id != BPF_FUNC_map_peek_elem && 8618 func_id != BPF_FUNC_map_push_elem) 8619 goto error; 8620 break; 8621 case BPF_MAP_TYPE_INSN_ARRAY: 8622 goto error; 8623 default: 8624 break; 8625 } 8626 8627 /* ... and second from the function itself. */ 8628 switch (func_id) { 8629 case BPF_FUNC_tail_call: 8630 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8631 goto error; 8632 if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) { 8633 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n"); 8634 return -EINVAL; 8635 } 8636 break; 8637 case BPF_FUNC_perf_event_read: 8638 case BPF_FUNC_perf_event_output: 8639 case BPF_FUNC_perf_event_read_value: 8640 case BPF_FUNC_skb_output: 8641 case BPF_FUNC_xdp_output: 8642 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8643 goto error; 8644 break; 8645 case BPF_FUNC_ringbuf_output: 8646 case BPF_FUNC_ringbuf_reserve: 8647 case BPF_FUNC_ringbuf_query: 8648 case BPF_FUNC_ringbuf_reserve_dynptr: 8649 case BPF_FUNC_ringbuf_submit_dynptr: 8650 case BPF_FUNC_ringbuf_discard_dynptr: 8651 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8652 goto error; 8653 break; 8654 case BPF_FUNC_user_ringbuf_drain: 8655 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8656 goto error; 8657 break; 8658 case BPF_FUNC_get_stackid: 8659 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8660 goto error; 8661 break; 8662 case BPF_FUNC_current_task_under_cgroup: 8663 case BPF_FUNC_skb_under_cgroup: 8664 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8665 goto error; 8666 break; 8667 case BPF_FUNC_redirect_map: 8668 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8669 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8670 map->map_type != BPF_MAP_TYPE_CPUMAP && 8671 map->map_type != BPF_MAP_TYPE_XSKMAP) 8672 goto error; 8673 break; 8674 case BPF_FUNC_sk_redirect_map: 8675 case BPF_FUNC_msg_redirect_map: 8676 case BPF_FUNC_sock_map_update: 8677 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8678 goto error; 8679 break; 8680 case BPF_FUNC_sk_redirect_hash: 8681 case BPF_FUNC_msg_redirect_hash: 8682 case BPF_FUNC_sock_hash_update: 8683 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8684 goto error; 8685 break; 8686 case BPF_FUNC_get_local_storage: 8687 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8688 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8689 goto error; 8690 break; 8691 case BPF_FUNC_sk_select_reuseport: 8692 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8693 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8694 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8695 goto error; 8696 break; 8697 case BPF_FUNC_map_pop_elem: 8698 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8699 map->map_type != BPF_MAP_TYPE_STACK) 8700 goto error; 8701 break; 8702 case BPF_FUNC_map_peek_elem: 8703 case BPF_FUNC_map_push_elem: 8704 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8705 map->map_type != BPF_MAP_TYPE_STACK && 8706 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8707 goto error; 8708 break; 8709 case BPF_FUNC_map_lookup_percpu_elem: 8710 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8711 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8712 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8713 goto error; 8714 break; 8715 case BPF_FUNC_sk_storage_get: 8716 case BPF_FUNC_sk_storage_delete: 8717 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8718 goto error; 8719 break; 8720 case BPF_FUNC_inode_storage_get: 8721 case BPF_FUNC_inode_storage_delete: 8722 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8723 goto error; 8724 break; 8725 case BPF_FUNC_task_storage_get: 8726 case BPF_FUNC_task_storage_delete: 8727 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8728 goto error; 8729 break; 8730 case BPF_FUNC_cgrp_storage_get: 8731 case BPF_FUNC_cgrp_storage_delete: 8732 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8733 goto error; 8734 break; 8735 default: 8736 break; 8737 } 8738 8739 return 0; 8740 error: 8741 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8742 map->map_type, func_id_name(func_id), func_id); 8743 return -EINVAL; 8744 } 8745 8746 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 8747 { 8748 int count = 0; 8749 8750 if (arg_type_is_raw_mem(fn->arg1_type)) 8751 count++; 8752 if (arg_type_is_raw_mem(fn->arg2_type)) 8753 count++; 8754 if (arg_type_is_raw_mem(fn->arg3_type)) 8755 count++; 8756 if (arg_type_is_raw_mem(fn->arg4_type)) 8757 count++; 8758 if (arg_type_is_raw_mem(fn->arg5_type)) 8759 count++; 8760 8761 /* We only support one arg being in raw mode at the moment, 8762 * which is sufficient for the helper functions we have 8763 * right now. 8764 */ 8765 return count <= 1; 8766 } 8767 8768 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8769 { 8770 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8771 bool has_size = fn->arg_size[arg] != 0; 8772 bool is_next_size = false; 8773 8774 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8775 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8776 8777 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8778 return is_next_size; 8779 8780 return has_size == is_next_size || is_next_size == is_fixed; 8781 } 8782 8783 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8784 { 8785 /* bpf_xxx(..., buf, len) call will access 'len' 8786 * bytes from memory 'buf'. Both arg types need 8787 * to be paired, so make sure there's no buggy 8788 * helper function specification. 8789 */ 8790 if (arg_type_is_mem_size(fn->arg1_type) || 8791 check_args_pair_invalid(fn, 0) || 8792 check_args_pair_invalid(fn, 1) || 8793 check_args_pair_invalid(fn, 2) || 8794 check_args_pair_invalid(fn, 3) || 8795 check_args_pair_invalid(fn, 4)) 8796 return false; 8797 8798 return true; 8799 } 8800 8801 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8802 { 8803 int i; 8804 8805 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8806 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8807 return !!fn->arg_btf_id[i]; 8808 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8809 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8810 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8811 /* arg_btf_id and arg_size are in a union. */ 8812 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8813 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8814 return false; 8815 } 8816 8817 return true; 8818 } 8819 8820 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn) 8821 { 8822 int i; 8823 8824 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8825 enum bpf_arg_type arg_type = fn->arg_type[i]; 8826 8827 if (base_type(arg_type) != ARG_PTR_TO_MEM) 8828 continue; 8829 if (!(arg_type & (MEM_WRITE | MEM_RDONLY))) 8830 return false; 8831 } 8832 8833 return true; 8834 } 8835 8836 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8837 { 8838 int i; 8839 8840 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8841 enum bpf_arg_type arg_type = fn->arg_type[i]; 8842 8843 if (arg_type_is_release(arg_type)) { 8844 if (meta->release_regno) 8845 return false; 8846 meta->release_regno = i + 1; 8847 } 8848 } 8849 8850 return true; 8851 } 8852 8853 static int check_func_proto(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8854 { 8855 return check_raw_mode_ok(fn) && 8856 check_arg_pair_ok(fn) && 8857 check_mem_arg_rw_flag_ok(fn) && 8858 check_proto_release_reg(fn, meta) && 8859 check_btf_id_ok(fn) ? 0 : -EINVAL; 8860 } 8861 8862 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8863 * are now invalid, so turn them into unknown SCALAR_VALUE. 8864 * 8865 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8866 * since these slices point to packet data. 8867 */ 8868 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8869 { 8870 struct bpf_func_state *state; 8871 struct bpf_reg_state *reg; 8872 8873 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8874 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8875 mark_reg_invalid(env, reg); 8876 })); 8877 } 8878 8879 enum { 8880 AT_PKT_END = -1, 8881 BEYOND_PKT_END = -2, 8882 }; 8883 8884 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8885 { 8886 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8887 struct bpf_reg_state *reg = &state->regs[regn]; 8888 8889 if (reg->type != PTR_TO_PACKET) 8890 /* PTR_TO_PACKET_META is not supported yet */ 8891 return; 8892 8893 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8894 * How far beyond pkt_end it goes is unknown. 8895 * if (!range_open) it's the case of pkt >= pkt_end 8896 * if (range_open) it's the case of pkt > pkt_end 8897 * hence this pointer is at least 1 byte bigger than pkt_end 8898 */ 8899 if (range_open) 8900 reg->range = BEYOND_PKT_END; 8901 else 8902 reg->range = AT_PKT_END; 8903 } 8904 8905 static int release_reference_nomark(struct bpf_verifier_state *state, int id) 8906 { 8907 int i; 8908 8909 for (i = 0; i < state->acquired_refs; i++) { 8910 if (state->refs[i].type != REF_TYPE_PTR) 8911 continue; 8912 if (state->refs[i].id == id) { 8913 release_reference_state(state, i); 8914 return 0; 8915 } 8916 } 8917 return -EINVAL; 8918 } 8919 8920 static int idstack_push(struct bpf_idmap *idmap, u32 id) 8921 { 8922 int i; 8923 8924 if (!id) 8925 return 0; 8926 8927 for (i = 0; i < idmap->cnt; i++) 8928 if (idmap->map[i].old == id) 8929 return 0; 8930 8931 if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE)) 8932 return -EFAULT; 8933 8934 idmap->map[idmap->cnt++].old = id; 8935 return 0; 8936 } 8937 8938 static int idstack_pop(struct bpf_idmap *idmap) 8939 { 8940 if (!idmap->cnt) 8941 return 0; 8942 8943 return idmap->map[--idmap->cnt].old; 8944 } 8945 8946 /* Release id and objects derived from it iteratively in a DFS manner */ 8947 static int release_reference(struct bpf_verifier_env *env, int id) 8948 { 8949 u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR); 8950 struct bpf_verifier_state *vstate = env->cur_state; 8951 struct bpf_idmap *idstack = &env->idmap_scratch; 8952 struct bpf_stack_state *stack; 8953 struct bpf_func_state *state; 8954 struct bpf_reg_state *reg; 8955 int i, err; 8956 8957 idstack->cnt = 0; 8958 err = idstack_push(idstack, id); 8959 if (err) 8960 return err; 8961 8962 if (find_reference_state(vstate, id)) 8963 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 8964 8965 while ((id = idstack_pop(idstack))) { 8966 /* 8967 * Child references are inaccessible after parent is released, 8968 * any child references that exist at this point are a leak. 8969 */ 8970 for (i = 0; i < vstate->acquired_refs; i++) { 8971 if (vstate->refs[i].type != REF_TYPE_PTR) 8972 continue; 8973 if (vstate->refs[i].parent_id != id) 8974 continue; 8975 verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n", 8976 vstate->refs[i].id, vstate->refs[i].insn_idx); 8977 return -EINVAL; 8978 } 8979 8980 bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({ 8981 if (reg->id != id && reg->parent_id != id) 8982 continue; 8983 8984 /* Free objects derived from the current object */ 8985 if (reg->parent_id == id) { 8986 err = idstack_push(idstack, reg->id); 8987 if (err) 8988 return err; 8989 } 8990 8991 if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL) 8992 mark_reg_invalid(env, reg); 8993 else if (stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR) 8994 invalidate_dynptr(env, stack); 8995 })); 8996 } 8997 8998 return 0; 8999 } 9000 9001 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9002 { 9003 struct bpf_func_state *unused; 9004 struct bpf_reg_state *reg; 9005 9006 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9007 if (type_is_non_owning_ref(reg->type)) 9008 mark_reg_invalid(env, reg); 9009 })); 9010 } 9011 9012 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env) 9013 { 9014 struct bpf_stack_state *stack; 9015 struct bpf_func_state *state; 9016 struct bpf_reg_state *reg; 9017 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 9018 9019 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({ 9020 if (reg->type & MEM_RCU) { 9021 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 9022 reg->type |= PTR_UNTRUSTED; 9023 } 9024 })); 9025 } 9026 9027 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id) 9028 { 9029 struct bpf_func_state *state; 9030 struct bpf_reg_state *reg; 9031 int err; 9032 9033 err = release_reference_nomark(env->cur_state, id); 9034 9035 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9036 if (reg->id != id) 9037 continue; 9038 if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 9039 reg->id = 0; 9040 reg->type &= ~MEM_ALLOC; 9041 reg->type |= MEM_RCU; 9042 } 9043 })); 9044 9045 return err; 9046 } 9047 9048 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9049 struct bpf_reg_state *regs) 9050 { 9051 int i; 9052 9053 /* after the call registers r0 - r5 were scratched */ 9054 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9055 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 9056 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9057 } 9058 } 9059 9060 static void invalidate_outgoing_stack_args(const struct bpf_verifier_env *env, 9061 struct bpf_func_state *state) 9062 { 9063 int i, nslots = state->out_stack_arg_cnt; 9064 9065 for (i = 0; i < nslots; i++) 9066 bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]); 9067 } 9068 9069 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9070 struct bpf_func_state *caller, 9071 struct bpf_func_state *callee, 9072 int insn_idx); 9073 9074 static int set_callee_state(struct bpf_verifier_env *env, 9075 struct bpf_func_state *caller, 9076 struct bpf_func_state *callee, int insn_idx); 9077 9078 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9079 set_callee_state_fn set_callee_state_cb, 9080 struct bpf_verifier_state *state) 9081 { 9082 struct bpf_func_state *caller, *callee; 9083 int err; 9084 9085 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9086 verbose(env, "the call stack of %d frames is too deep\n", 9087 state->curframe + 2); 9088 return -E2BIG; 9089 } 9090 9091 if (state->frame[state->curframe + 1]) { 9092 verifier_bug(env, "Frame %d already allocated", state->curframe + 1); 9093 return -EFAULT; 9094 } 9095 9096 caller = state->frame[state->curframe]; 9097 callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT); 9098 if (!callee) 9099 return -ENOMEM; 9100 state->frame[state->curframe + 1] = callee; 9101 9102 /* callee cannot access r0, r6 - r9 for reading and has to write 9103 * into its own stack before reading from it. 9104 * callee can read/write into caller's stack 9105 */ 9106 init_func_state(env, callee, 9107 /* remember the callsite, it will be used by bpf_exit */ 9108 callsite, 9109 state->curframe + 1 /* frameno within this callchain */, 9110 subprog /* subprog number within this prog */); 9111 err = set_callee_state_cb(env, caller, callee, callsite); 9112 if (err) 9113 goto err_out; 9114 9115 /* only increment it after check_reg_arg() finished */ 9116 state->curframe++; 9117 9118 return 0; 9119 9120 err_out: 9121 free_func_state(callee); 9122 state->frame[state->curframe + 1] = NULL; 9123 return err; 9124 } 9125 9126 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9127 const struct btf *btf, 9128 struct bpf_reg_state *regs) 9129 { 9130 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9131 struct bpf_func_state *caller = cur_func(env); 9132 struct bpf_verifier_log *log = &env->log; 9133 struct ref_obj_desc ref_obj = {}; 9134 u32 i; 9135 int ret, err; 9136 9137 ret = btf_prepare_func_args(env, subprog); 9138 if (ret) { 9139 if (bpf_in_stack_arg_cnt(sub) > 0) { 9140 err = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9141 if (err) 9142 return err; 9143 } 9144 return ret; 9145 } 9146 9147 ret = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9148 if (ret) 9149 return ret; 9150 9151 /* check that BTF function arguments match actual types that the 9152 * verifier sees. 9153 */ 9154 for (i = 0; i < sub->arg_cnt; i++) { 9155 argno_t argno = argno_from_arg(i + 1); 9156 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 9157 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9158 9159 if (arg->arg_type == ARG_ANYTHING) { 9160 if (reg->type != SCALAR_VALUE) { 9161 bpf_log(log, "%s is not a scalar\n", reg_arg_name(env, argno)); 9162 return -EINVAL; 9163 } 9164 } else if (arg->arg_type & PTR_UNTRUSTED) { 9165 /* 9166 * Anything is allowed for untrusted arguments, as these are 9167 * read-only and probe read instructions would protect against 9168 * invalid memory access. 9169 */ 9170 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9171 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_CTX); 9172 if (ret < 0) 9173 return ret; 9174 /* If function expects ctx type in BTF check that caller 9175 * is passing PTR_TO_CTX. 9176 */ 9177 if (reg->type != PTR_TO_CTX) { 9178 bpf_log(log, "%s expects pointer to ctx\n", 9179 reg_arg_name(env, argno)); 9180 return -EINVAL; 9181 } 9182 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9183 ret = check_func_arg_reg_off(env, reg, argno, ARG_DONTCARE); 9184 if (ret < 0) 9185 return ret; 9186 if (check_mem_reg(env, reg, argno, arg->mem_size)) 9187 return -EINVAL; 9188 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9189 bpf_log(log, "%s is expected to be non-NULL\n", 9190 reg_arg_name(env, argno)); 9191 return -EINVAL; 9192 } 9193 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9194 /* 9195 * Can pass any value and the kernel won't crash, but 9196 * only PTR_TO_ARENA or SCALAR make sense. Everything 9197 * else is a bug in the bpf program. Point it out to 9198 * the user at the verification time instead of 9199 * run-time debug nightmare. 9200 */ 9201 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9202 bpf_log(log, "%s is not a pointer to arena or scalar.\n", 9203 reg_arg_name(env, argno)); 9204 return -EINVAL; 9205 } 9206 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 9207 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_DYNPTR); 9208 if (ret) 9209 return ret; 9210 9211 ret = process_dynptr_func(env, reg, argno, -1, arg->arg_type, &ref_obj, NULL); 9212 if (ret) 9213 return ret; 9214 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9215 struct bpf_call_arg_meta meta; 9216 int err; 9217 9218 if (bpf_register_is_null(reg) && type_may_be_null(arg->arg_type)) 9219 continue; 9220 9221 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9222 err = check_reg_type(env, reg, argno, arg->arg_type, &arg->btf_id, &meta); 9223 err = err ?: check_func_arg_reg_off(env, reg, argno, arg->arg_type); 9224 if (err) 9225 return err; 9226 } else { 9227 verifier_bug(env, "unrecognized %s type %d", 9228 reg_arg_name(env, argno), arg->arg_type); 9229 return -EFAULT; 9230 } 9231 } 9232 9233 return 0; 9234 } 9235 9236 /* Compare BTF of a function call with given bpf_reg_state. 9237 * Returns: 9238 * EFAULT - there is a verifier bug. Abort verification. 9239 * EINVAL - there is a type mismatch or BTF is not available. 9240 * 0 - BTF matches with what bpf_reg_state expects. 9241 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9242 */ 9243 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9244 struct bpf_reg_state *regs) 9245 { 9246 struct bpf_prog *prog = env->prog; 9247 struct btf *btf = prog->aux->btf; 9248 u32 btf_id; 9249 int err; 9250 9251 if (!prog->aux->func_info) 9252 return -EINVAL; 9253 9254 btf_id = prog->aux->func_info[subprog].type_id; 9255 if (!btf_id) 9256 return -EFAULT; 9257 9258 if (prog->aux->func_info_aux[subprog].unreliable) 9259 return -EINVAL; 9260 9261 err = btf_check_func_arg_match(env, subprog, btf, regs); 9262 /* Compiler optimizations can remove arguments from static functions 9263 * or mismatched type can be passed into a global function. 9264 * In such cases mark the function as unreliable from BTF point of view. 9265 */ 9266 if (err) 9267 prog->aux->func_info_aux[subprog].unreliable = true; 9268 return err; 9269 } 9270 9271 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9272 int insn_idx, int subprog, 9273 set_callee_state_fn set_callee_state_cb) 9274 { 9275 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9276 struct bpf_func_state *caller, *callee; 9277 int err; 9278 9279 caller = state->frame[state->curframe]; 9280 err = btf_check_subprog_call(env, subprog, caller->regs); 9281 if (err == -EFAULT) 9282 return err; 9283 9284 /* set_callee_state is used for direct subprog calls, but we are 9285 * interested in validating only BPF helpers that can call subprogs as 9286 * callbacks 9287 */ 9288 env->subprog_info[subprog].is_cb = true; 9289 if (bpf_pseudo_kfunc_call(insn) && 9290 !is_callback_calling_kfunc(insn->imm)) { 9291 verifier_bug(env, "kfunc %s#%d not marked as callback-calling", 9292 func_id_name(insn->imm), insn->imm); 9293 return -EFAULT; 9294 } else if (!bpf_pseudo_kfunc_call(insn) && 9295 !is_callback_calling_function(insn->imm)) { /* helper */ 9296 verifier_bug(env, "helper %s#%d not marked as callback-calling", 9297 func_id_name(insn->imm), insn->imm); 9298 return -EFAULT; 9299 } 9300 9301 if (bpf_is_async_callback_calling_insn(insn)) { 9302 struct bpf_verifier_state *async_cb; 9303 9304 /* there is no real recursion here. timer and workqueue callbacks are async */ 9305 env->subprog_info[subprog].is_async_cb = true; 9306 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9307 insn_idx, subprog, 9308 is_async_cb_sleepable(env, insn)); 9309 if (IS_ERR(async_cb)) 9310 return PTR_ERR(async_cb); 9311 callee = async_cb->frame[0]; 9312 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9313 9314 /* Convert bpf_timer_set_callback() args into timer callback args */ 9315 err = set_callee_state_cb(env, caller, callee, insn_idx); 9316 if (err) 9317 return err; 9318 9319 return 0; 9320 } 9321 9322 /* for callback functions enqueue entry to callback and 9323 * proceed with next instruction within current frame. 9324 */ 9325 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9326 if (IS_ERR(callback_state)) 9327 return PTR_ERR(callback_state); 9328 9329 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9330 callback_state); 9331 if (err) 9332 return err; 9333 9334 callback_state->callback_unroll_depth++; 9335 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9336 caller->callback_depth = 0; 9337 return 0; 9338 } 9339 9340 static int process_bpf_exit_full(struct bpf_verifier_env *env, 9341 bool *do_print_state, bool exception_exit); 9342 9343 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9344 int *insn_idx) 9345 { 9346 struct bpf_verifier_state *state = env->cur_state; 9347 struct bpf_subprog_info *caller_info; 9348 u16 callee_incoming, stack_arg_cnt; 9349 struct bpf_func_state *caller; 9350 int err, subprog, target_insn; 9351 9352 target_insn = *insn_idx + insn->imm + 1; 9353 subprog = bpf_find_subprog(env, target_insn); 9354 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program", 9355 target_insn)) 9356 return -EFAULT; 9357 9358 caller = state->frame[state->curframe]; 9359 err = btf_check_subprog_call(env, subprog, caller->regs); 9360 if (err == -EFAULT) 9361 return err; 9362 if (bpf_subprog_is_global(env, subprog)) { 9363 const char *sub_name = subprog_name(env, subprog); 9364 9365 if (env->cur_state->active_locks) { 9366 verbose(env, "global function calls are not allowed while holding a lock,\n" 9367 "use static function instead\n"); 9368 return -EINVAL; 9369 } 9370 9371 if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) { 9372 verbose(env, "sleepable global function %s() called in %s\n", 9373 sub_name, non_sleepable_context_description(env)); 9374 return -EINVAL; 9375 } 9376 9377 if (err) { 9378 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9379 subprog, sub_name); 9380 return err; 9381 } 9382 9383 if (env->log.level & BPF_LOG_LEVEL) 9384 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9385 subprog, sub_name); 9386 if (env->subprog_info[subprog].changes_pkt_data) 9387 clear_all_pkt_pointers(env); 9388 /* mark global subprog for verifying after main prog */ 9389 subprog_aux(env, subprog)->called = true; 9390 clear_caller_saved_regs(env, caller->regs); 9391 invalidate_outgoing_stack_args(env, cur_func(env)); 9392 9393 /* All non-void global functions return a 64-bit SCALAR_VALUE. */ 9394 if (!subprog_returns_void(env, subprog)) { 9395 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9396 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9397 } 9398 9399 if (env->subprog_info[subprog].might_throw) { 9400 struct bpf_verifier_state *branch; 9401 9402 branch = push_stack(env, *insn_idx + 1, *insn_idx, false); 9403 if (IS_ERR(branch)) { 9404 verbose(env, "failed to push state for global subprog exception path\n"); 9405 return PTR_ERR(branch); 9406 } 9407 return process_bpf_exit_full(env, NULL, true); 9408 } 9409 9410 /* continue with next insn after call */ 9411 return 0; 9412 } 9413 9414 /* 9415 * Track caller's total stack arg count (incoming + max outgoing). 9416 * This is needed so the JIT knows how much stack arg space to allocate. 9417 */ 9418 caller_info = &env->subprog_info[caller->subprogno]; 9419 callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]); 9420 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming; 9421 if (stack_arg_cnt > caller_info->stack_arg_cnt) 9422 caller_info->stack_arg_cnt = stack_arg_cnt; 9423 9424 /* for regular function entry setup new frame and continue 9425 * from that frame. 9426 */ 9427 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9428 if (err) 9429 return err; 9430 9431 clear_caller_saved_regs(env, caller->regs); 9432 9433 /* and go analyze first insn of the callee */ 9434 *insn_idx = env->subprog_info[subprog].start - 1; 9435 9436 if (env->log.level & BPF_LOG_LEVEL) { 9437 verbose(env, "caller:\n"); 9438 print_verifier_state(env, state, caller->frameno, true); 9439 verbose(env, "callee:\n"); 9440 print_verifier_state(env, state, state->curframe, true); 9441 } 9442 9443 return 0; 9444 } 9445 9446 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9447 struct bpf_func_state *caller, 9448 struct bpf_func_state *callee) 9449 { 9450 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9451 * void *callback_ctx, u64 flags); 9452 * callback_fn(struct bpf_map *map, void *key, void *value, 9453 * void *callback_ctx); 9454 */ 9455 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9456 9457 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9458 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9459 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9460 9461 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9462 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9463 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9464 9465 /* pointer to stack or null */ 9466 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9467 9468 /* unused */ 9469 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9470 return 0; 9471 } 9472 9473 static int set_callee_state(struct bpf_verifier_env *env, 9474 struct bpf_func_state *caller, 9475 struct bpf_func_state *callee, int insn_idx) 9476 { 9477 int i; 9478 9479 /* copy r1 - r5 args that callee can access. The copy includes parent 9480 * pointers, which connects us up to the liveness chain 9481 */ 9482 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9483 callee->regs[i] = caller->regs[i]; 9484 return 0; 9485 } 9486 9487 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9488 struct bpf_func_state *caller, 9489 struct bpf_func_state *callee, 9490 int insn_idx) 9491 { 9492 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9493 struct bpf_map *map; 9494 int err; 9495 9496 /* valid map_ptr and poison value does not matter */ 9497 map = insn_aux->map_ptr_state.map_ptr; 9498 if (!map->ops->map_set_for_each_callback_args || 9499 !map->ops->map_for_each_callback) { 9500 verbose(env, "callback function not allowed for map\n"); 9501 return -ENOTSUPP; 9502 } 9503 9504 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9505 if (err) 9506 return err; 9507 9508 callee->in_callback_fn = true; 9509 callee->callback_ret_range = retval_range(0, 1); 9510 return 0; 9511 } 9512 9513 static int set_loop_callback_state(struct bpf_verifier_env *env, 9514 struct bpf_func_state *caller, 9515 struct bpf_func_state *callee, 9516 int insn_idx) 9517 { 9518 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9519 * u64 flags); 9520 * callback_fn(u64 index, void *callback_ctx); 9521 */ 9522 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9523 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9524 9525 /* unused */ 9526 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9527 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9528 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9529 9530 callee->in_callback_fn = true; 9531 callee->callback_ret_range = retval_range(0, 1); 9532 return 0; 9533 } 9534 9535 static int set_timer_callback_state(struct bpf_verifier_env *env, 9536 struct bpf_func_state *caller, 9537 struct bpf_func_state *callee, 9538 int insn_idx) 9539 { 9540 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9541 9542 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9543 * callback_fn(struct bpf_map *map, void *key, void *value); 9544 */ 9545 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9546 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9547 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9548 9549 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9550 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9551 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9552 9553 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9554 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9555 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9556 9557 /* unused */ 9558 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9559 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9560 callee->in_async_callback_fn = true; 9561 callee->callback_ret_range = retval_range(0, 0); 9562 return 0; 9563 } 9564 9565 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9566 struct bpf_func_state *caller, 9567 struct bpf_func_state *callee, 9568 int insn_idx) 9569 { 9570 /* bpf_find_vma(struct task_struct *task, u64 addr, 9571 * void *callback_fn, void *callback_ctx, u64 flags) 9572 * (callback_fn)(struct task_struct *task, 9573 * struct vm_area_struct *vma, void *callback_ctx); 9574 */ 9575 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9576 9577 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9578 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9579 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9580 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9581 9582 /* pointer to stack or null */ 9583 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9584 9585 /* unused */ 9586 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9587 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9588 callee->in_callback_fn = true; 9589 callee->callback_ret_range = retval_range(0, 1); 9590 return 0; 9591 } 9592 9593 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9594 struct bpf_func_state *caller, 9595 struct bpf_func_state *callee, 9596 int insn_idx) 9597 { 9598 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9599 * callback_ctx, u64 flags); 9600 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9601 */ 9602 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9603 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9604 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9605 9606 /* unused */ 9607 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9608 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9609 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9610 9611 callee->in_callback_fn = true; 9612 callee->callback_ret_range = retval_range(0, 1); 9613 return 0; 9614 } 9615 9616 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9617 struct bpf_func_state *caller, 9618 struct bpf_func_state *callee, 9619 int insn_idx) 9620 { 9621 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9622 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9623 * 9624 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9625 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9626 * by this point, so look at 'root' 9627 */ 9628 struct btf_field *field; 9629 9630 field = reg_find_field_offset(&caller->regs[BPF_REG_1], 9631 caller->regs[BPF_REG_1].var_off.value, 9632 BPF_RB_ROOT); 9633 if (!field || !field->graph_root.value_btf_id) 9634 return -EFAULT; 9635 9636 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9637 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9638 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9639 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9640 9641 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9642 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9643 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9644 callee->in_callback_fn = true; 9645 callee->callback_ret_range = retval_range(0, 1); 9646 return 0; 9647 } 9648 9649 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env, 9650 struct bpf_func_state *caller, 9651 struct bpf_func_state *callee, 9652 int insn_idx) 9653 { 9654 struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr; 9655 9656 /* 9657 * callback_fn(struct bpf_map *map, void *key, void *value); 9658 */ 9659 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9660 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9661 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9662 9663 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9664 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9665 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9666 9667 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9668 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9669 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9670 9671 /* unused */ 9672 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9673 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9674 callee->in_async_callback_fn = true; 9675 callee->callback_ret_range = retval_range(S32_MIN, S32_MAX); 9676 return 0; 9677 } 9678 9679 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9680 9681 /* Are we currently verifying the callback for a rbtree helper that must 9682 * be called with lock held? If so, no need to complain about unreleased 9683 * lock 9684 */ 9685 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9686 { 9687 struct bpf_verifier_state *state = env->cur_state; 9688 struct bpf_insn *insn = env->prog->insnsi; 9689 struct bpf_func_state *callee; 9690 int kfunc_btf_id; 9691 9692 if (!state->curframe) 9693 return false; 9694 9695 callee = state->frame[state->curframe]; 9696 9697 if (!callee->in_callback_fn) 9698 return false; 9699 9700 kfunc_btf_id = insn[callee->callsite].imm; 9701 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9702 } 9703 9704 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9705 { 9706 if (range.return_32bit) 9707 return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval; 9708 else 9709 return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval; 9710 } 9711 9712 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9713 { 9714 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9715 struct bpf_func_state *caller, *callee; 9716 struct bpf_reg_state *r0; 9717 bool in_callback_fn; 9718 int err; 9719 9720 callee = state->frame[state->curframe]; 9721 r0 = &callee->regs[BPF_REG_0]; 9722 if (r0->type == PTR_TO_STACK) { 9723 /* technically it's ok to return caller's stack pointer 9724 * (or caller's caller's pointer) back to the caller, 9725 * since these pointers are valid. Only current stack 9726 * pointer will be invalid as soon as function exits, 9727 * but let's be conservative 9728 */ 9729 verbose(env, "cannot return stack pointer to the caller\n"); 9730 return -EINVAL; 9731 } 9732 9733 caller = state->frame[state->curframe - 1]; 9734 if (callee->in_callback_fn) { 9735 if (r0->type != SCALAR_VALUE) { 9736 verbose(env, "R0 not a scalar value\n"); 9737 return -EACCES; 9738 } 9739 9740 /* we are going to rely on register's precise value */ 9741 err = mark_chain_precision(env, BPF_REG_0); 9742 if (err) 9743 return err; 9744 9745 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 9746 if (!retval_range_within(callee->callback_ret_range, r0)) { 9747 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9748 "At callback return", "R0"); 9749 return -EINVAL; 9750 } 9751 if (!bpf_calls_callback(env, callee->callsite)) { 9752 verifier_bug(env, "in callback at %d, callsite %d !calls_callback", 9753 *insn_idx, callee->callsite); 9754 return -EFAULT; 9755 } 9756 } else { 9757 /* return to the caller whatever r0 had in the callee */ 9758 caller->regs[BPF_REG_0] = *r0; 9759 } 9760 9761 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9762 * there function call logic would reschedule callback visit. If iteration 9763 * converges is_state_visited() would prune that visit eventually. 9764 */ 9765 in_callback_fn = callee->in_callback_fn; 9766 if (in_callback_fn) 9767 *insn_idx = callee->callsite; 9768 else 9769 *insn_idx = callee->callsite + 1; 9770 9771 if (env->log.level & BPF_LOG_LEVEL) { 9772 verbose(env, "returning from callee:\n"); 9773 print_verifier_state(env, state, callee->frameno, true); 9774 verbose(env, "to caller at %d:\n", *insn_idx); 9775 print_verifier_state(env, state, caller->frameno, true); 9776 } 9777 /* clear everything in the callee. In case of exceptional exits using 9778 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9779 free_func_state(callee); 9780 state->frame[state->curframe--] = NULL; 9781 invalidate_outgoing_stack_args(env, caller); 9782 9783 /* for callbacks widen imprecise scalars to make programs like below verify: 9784 * 9785 * struct ctx { int i; } 9786 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9787 * ... 9788 * struct ctx = { .i = 0; } 9789 * bpf_loop(100, cb, &ctx, 0); 9790 * 9791 * This is similar to what is done in process_iter_next_call() for open 9792 * coded iterators. 9793 */ 9794 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9795 if (prev_st) { 9796 err = widen_imprecise_scalars(env, prev_st, state); 9797 if (err) 9798 return err; 9799 } 9800 return 0; 9801 } 9802 9803 static int do_refine_retval_range(struct bpf_verifier_env *env, 9804 struct bpf_reg_state *regs, int ret_type, 9805 int func_id, 9806 struct bpf_call_arg_meta *meta) 9807 { 9808 struct bpf_retval_range range; 9809 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9810 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9811 9812 if (ret_type != RET_INTEGER) 9813 return 0; 9814 9815 switch (func_id) { 9816 case BPF_FUNC_get_stack: 9817 case BPF_FUNC_get_task_stack: 9818 case BPF_FUNC_probe_read_str: 9819 case BPF_FUNC_probe_read_kernel_str: 9820 case BPF_FUNC_probe_read_user_str: 9821 reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9822 reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9823 reg_bounds_sync(ret_reg); 9824 break; 9825 case BPF_FUNC_get_smp_processor_id: 9826 reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1); 9827 reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1); 9828 reg_bounds_sync(ret_reg); 9829 break; 9830 case BPF_FUNC_get_retval: 9831 /* 9832 * bpf_get_retval may see arbitrary value passed by bpf_prog_run_array_cg for 9833 * CGROUP_GETSOCKOPT type. 9834 */ 9835 if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT && 9836 env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) 9837 break; 9838 9839 if (prog_type == BPF_PROG_TYPE_LSM && 9840 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 9841 if (!env->prog->aux->attach_func_proto->type) 9842 break; 9843 bpf_lsm_get_retval_range(env->prog, &range); 9844 } else { 9845 range.minval = -MAX_ERRNO; 9846 range.maxval = 0; 9847 } 9848 9849 reg_set_srange64(ret_reg, range.minval, range.maxval); 9850 reg_set_srange32(ret_reg, range.minval, range.maxval); 9851 reg_bounds_sync(ret_reg); 9852 break; 9853 } 9854 9855 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9856 } 9857 9858 static int 9859 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9860 int func_id, int insn_idx) 9861 { 9862 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9863 struct bpf_map *map = meta->map.ptr; 9864 9865 if (func_id != BPF_FUNC_tail_call && 9866 func_id != BPF_FUNC_map_lookup_elem && 9867 func_id != BPF_FUNC_map_update_elem && 9868 func_id != BPF_FUNC_map_delete_elem && 9869 func_id != BPF_FUNC_map_push_elem && 9870 func_id != BPF_FUNC_map_pop_elem && 9871 func_id != BPF_FUNC_map_peek_elem && 9872 func_id != BPF_FUNC_for_each_map_elem && 9873 func_id != BPF_FUNC_redirect_map && 9874 func_id != BPF_FUNC_map_lookup_percpu_elem) 9875 return 0; 9876 9877 if (map == NULL) { 9878 verifier_bug(env, "expected map for helper call"); 9879 return -EFAULT; 9880 } 9881 9882 /* In case of read-only, some additional restrictions 9883 * need to be applied in order to prevent altering the 9884 * state of the map from program side. 9885 */ 9886 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9887 (func_id == BPF_FUNC_map_delete_elem || 9888 func_id == BPF_FUNC_map_update_elem || 9889 func_id == BPF_FUNC_map_push_elem || 9890 func_id == BPF_FUNC_map_pop_elem)) { 9891 verbose(env, "write into map forbidden\n"); 9892 return -EACCES; 9893 } 9894 9895 if (!aux->map_ptr_state.map_ptr) 9896 bpf_map_ptr_store(aux, meta->map.ptr, 9897 !meta->map.ptr->bypass_spec_v1, false); 9898 else if (aux->map_ptr_state.map_ptr != meta->map.ptr) 9899 bpf_map_ptr_store(aux, meta->map.ptr, 9900 !meta->map.ptr->bypass_spec_v1, true); 9901 return 0; 9902 } 9903 9904 static int 9905 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9906 int func_id, int insn_idx) 9907 { 9908 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9909 struct bpf_reg_state *reg; 9910 struct bpf_map *map = meta->map.ptr; 9911 u64 val, max; 9912 int err; 9913 9914 if (func_id != BPF_FUNC_tail_call) 9915 return 0; 9916 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9917 verbose(env, "expected prog array map for tail call"); 9918 return -EINVAL; 9919 } 9920 9921 reg = reg_state(env, BPF_REG_3); 9922 val = reg->var_off.value; 9923 max = map->max_entries; 9924 9925 if (!(is_reg_const(reg, false) && val < max)) { 9926 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9927 return 0; 9928 } 9929 9930 err = mark_chain_precision(env, BPF_REG_3); 9931 if (err) 9932 return err; 9933 if (bpf_map_key_unseen(aux)) 9934 bpf_map_key_store(aux, val); 9935 else if (!bpf_map_key_poisoned(aux) && 9936 bpf_map_key_immediate(aux) != val) 9937 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9938 return 0; 9939 } 9940 9941 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9942 { 9943 struct bpf_verifier_state *state = env->cur_state; 9944 enum bpf_prog_type type = resolve_prog_type(env->prog); 9945 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 9946 bool refs_lingering = false; 9947 int i; 9948 9949 if (!exception_exit && cur_func(env)->frameno) 9950 return 0; 9951 9952 for (i = 0; i < state->acquired_refs; i++) { 9953 if (state->refs[i].type != REF_TYPE_PTR) 9954 continue; 9955 /* Allow struct_ops programs to return a referenced kptr back to 9956 * kernel. Type checks are performed later in check_return_code. 9957 */ 9958 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && 9959 reg->id == state->refs[i].id) 9960 continue; 9961 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9962 state->refs[i].id, state->refs[i].insn_idx); 9963 refs_lingering = true; 9964 } 9965 return refs_lingering ? -EINVAL : 0; 9966 } 9967 9968 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 9969 { 9970 int err; 9971 9972 if (check_lock && env->cur_state->active_locks) { 9973 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 9974 return -EINVAL; 9975 } 9976 9977 err = check_reference_leak(env, exception_exit); 9978 if (err) { 9979 verbose(env, "%s would lead to reference leak\n", prefix); 9980 return err; 9981 } 9982 9983 if (check_lock && env->cur_state->active_irq_id) { 9984 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix); 9985 return -EINVAL; 9986 } 9987 9988 if (check_lock && env->cur_state->active_rcu_locks) { 9989 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 9990 return -EINVAL; 9991 } 9992 9993 if (check_lock && env->cur_state->active_preempt_locks) { 9994 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 9995 return -EINVAL; 9996 } 9997 9998 return 0; 9999 } 10000 10001 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10002 struct bpf_reg_state *regs) 10003 { 10004 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10005 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10006 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10007 struct bpf_bprintf_data data = {}; 10008 int err, fmt_map_off, num_args; 10009 u64 fmt_addr; 10010 char *fmt; 10011 10012 /* data must be an array of u64 */ 10013 if (data_len_reg->var_off.value % 8) 10014 return -EINVAL; 10015 num_args = data_len_reg->var_off.value / 8; 10016 10017 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10018 * and map_direct_value_addr is set. 10019 */ 10020 fmt_map_off = fmt_reg->var_off.value; 10021 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10022 fmt_map_off); 10023 if (err) { 10024 verbose(env, "failed to retrieve map value address\n"); 10025 return -EFAULT; 10026 } 10027 fmt = (char *)(long)fmt_addr + fmt_map_off; 10028 10029 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10030 * can focus on validating the format specifiers. 10031 */ 10032 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10033 if (err < 0) 10034 verbose(env, "Invalid format string\n"); 10035 10036 return err; 10037 } 10038 10039 static int check_get_func_ip(struct bpf_verifier_env *env) 10040 { 10041 enum bpf_prog_type type = resolve_prog_type(env->prog); 10042 int func_id = BPF_FUNC_get_func_ip; 10043 10044 if (type == BPF_PROG_TYPE_TRACING) { 10045 if (!bpf_prog_has_trampoline(env->prog)) { 10046 verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n", 10047 func_id_name(func_id), func_id); 10048 return -ENOTSUPP; 10049 } 10050 return 0; 10051 } else if (type == BPF_PROG_TYPE_KPROBE) { 10052 return 0; 10053 } 10054 10055 verbose(env, "func %s#%d not supported for program type %d\n", 10056 func_id_name(func_id), func_id, type); 10057 return -ENOTSUPP; 10058 } 10059 10060 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env) 10061 { 10062 return &env->insn_aux_data[env->insn_idx]; 10063 } 10064 10065 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10066 { 10067 struct bpf_reg_state *reg = reg_state(env, BPF_REG_4); 10068 bool reg_is_null = bpf_register_is_null(reg); 10069 10070 if (reg_is_null) 10071 mark_chain_precision(env, BPF_REG_4); 10072 10073 return reg_is_null; 10074 } 10075 10076 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10077 { 10078 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10079 10080 if (!state->initialized) { 10081 state->initialized = 1; 10082 state->fit_for_inline = loop_flag_is_zero(env); 10083 state->callback_subprogno = subprogno; 10084 return; 10085 } 10086 10087 if (!state->fit_for_inline) 10088 return; 10089 10090 state->fit_for_inline = (loop_flag_is_zero(env) && 10091 state->callback_subprogno == subprogno); 10092 } 10093 10094 /* Returns whether or not the given map can potentially elide 10095 * lookup return value nullness check. This is possible if the key 10096 * is statically known. 10097 */ 10098 static bool can_elide_value_nullness(const struct bpf_map *map) 10099 { 10100 if (map->map_flags & BPF_F_INNER_MAP) 10101 return false; 10102 10103 switch (map->map_type) { 10104 case BPF_MAP_TYPE_ARRAY: 10105 case BPF_MAP_TYPE_PERCPU_ARRAY: 10106 return true; 10107 default: 10108 return false; 10109 } 10110 } 10111 10112 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id, 10113 const struct bpf_func_proto **ptr) 10114 { 10115 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 10116 return -ERANGE; 10117 10118 if (!env->ops->get_func_proto) 10119 return -EINVAL; 10120 10121 *ptr = env->ops->get_func_proto(func_id, env->prog); 10122 return *ptr && (*ptr)->func ? 0 : -EINVAL; 10123 } 10124 10125 /* Check if we're in a sleepable context. */ 10126 static inline bool in_sleepable_context(struct bpf_verifier_env *env) 10127 { 10128 return !env->cur_state->active_rcu_locks && 10129 !env->cur_state->active_preempt_locks && 10130 !env->cur_state->active_locks && 10131 !env->cur_state->active_irq_id && 10132 in_sleepable(env); 10133 } 10134 10135 static const char *non_sleepable_context_description(struct bpf_verifier_env *env) 10136 { 10137 if (env->cur_state->active_rcu_locks) 10138 return "rcu_read_lock region"; 10139 if (env->cur_state->active_preempt_locks) 10140 return "non-preemptible region"; 10141 if (env->cur_state->active_irq_id) 10142 return "IRQ-disabled region"; 10143 if (env->cur_state->active_locks) 10144 return "lock region"; 10145 return "non-sleepable prog"; 10146 } 10147 10148 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 10149 bool convert_rcu, bool release_dynptr) 10150 { 10151 int err = -EINVAL; 10152 10153 if (bpf_register_is_null(reg)) 10154 return 0; 10155 10156 if (release_dynptr) 10157 err = unmark_stack_slots_dynptr(env, reg); 10158 else if (convert_rcu) 10159 err = ref_convert_alloc_rcu_protected(env, reg->id); 10160 else if (reg_is_referenced(env, reg)) 10161 err = release_reference(env, reg->id); 10162 10163 return err; 10164 } 10165 10166 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10167 int *insn_idx_p) 10168 { 10169 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10170 bool returns_cpu_specific_alloc_ptr = false; 10171 const struct bpf_func_proto *fn = NULL; 10172 enum bpf_return_type ret_type; 10173 enum bpf_type_flag ret_flag; 10174 struct bpf_reg_state *regs; 10175 struct bpf_call_arg_meta meta; 10176 int insn_idx = *insn_idx_p; 10177 bool changes_data; 10178 int i, err, func_id; 10179 10180 /* find function prototype */ 10181 func_id = insn->imm; 10182 err = bpf_get_helper_proto(env, insn->imm, &fn); 10183 if (err == -ERANGE) { 10184 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 10185 return -EINVAL; 10186 } 10187 10188 if (err) { 10189 verbose(env, "program of this type cannot use helper %s#%d\n", 10190 func_id_name(func_id), func_id); 10191 return err; 10192 } 10193 10194 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10195 if (!env->prog->gpl_compatible && fn->gpl_only) { 10196 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10197 return -EINVAL; 10198 } 10199 10200 if (fn->allowed && !fn->allowed(env->prog)) { 10201 verbose(env, "helper call is not allowed in probe\n"); 10202 return -EINVAL; 10203 } 10204 10205 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10206 changes_data = bpf_helper_changes_pkt_data(func_id); 10207 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10208 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id); 10209 return -EFAULT; 10210 } 10211 10212 memset(&meta, 0, sizeof(meta)); 10213 meta.pkt_access = fn->pkt_access; 10214 10215 err = check_func_proto(fn, &meta); 10216 if (err) { 10217 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id); 10218 return err; 10219 } 10220 10221 if (fn->might_sleep && !in_sleepable_context(env)) { 10222 verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id, 10223 non_sleepable_context_description(env)); 10224 return -EINVAL; 10225 } 10226 10227 /* Track non-sleepable context for helpers. */ 10228 if (!in_sleepable_context(env)) 10229 env->insn_aux_data[insn_idx].non_sleepable = true; 10230 10231 meta.func_id = func_id; 10232 /* check args */ 10233 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10234 err = check_func_arg(env, i, &meta, fn, insn_idx); 10235 if (err) 10236 return err; 10237 } 10238 10239 err = record_func_map(env, &meta, func_id, insn_idx); 10240 if (err) 10241 return err; 10242 10243 err = record_func_key(env, &meta, func_id, insn_idx); 10244 if (err) 10245 return err; 10246 10247 regs = cur_regs(env); 10248 10249 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10250 * is inferred from register state. 10251 */ 10252 for (i = 0; i < meta.access_size; i++) { 10253 err = check_mem_access(env, insn_idx, regs + meta.regno, argno_from_reg(meta.regno), i, BPF_B, 10254 BPF_WRITE, -1, false, false); 10255 if (err) 10256 return err; 10257 } 10258 10259 if (meta.release_regno) { 10260 struct bpf_reg_state *reg = ®s[meta.release_regno]; 10261 bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) && 10262 (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU); 10263 10264 err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id); 10265 if (err) 10266 return err; 10267 } 10268 10269 switch (func_id) { 10270 case BPF_FUNC_tail_call: 10271 err = check_resource_leak(env, false, true, "tail_call"); 10272 if (err) 10273 return err; 10274 break; 10275 case BPF_FUNC_get_local_storage: 10276 /* check that flags argument in get_local_storage(map, flags) is 0, 10277 * this is required because get_local_storage() can't return an error. 10278 */ 10279 if (!bpf_register_is_null(®s[BPF_REG_2])) { 10280 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10281 return -EINVAL; 10282 } 10283 break; 10284 case BPF_FUNC_for_each_map_elem: 10285 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10286 set_map_elem_callback_state); 10287 break; 10288 case BPF_FUNC_timer_set_callback: 10289 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10290 set_timer_callback_state); 10291 break; 10292 case BPF_FUNC_find_vma: 10293 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10294 set_find_vma_callback_state); 10295 break; 10296 case BPF_FUNC_snprintf: 10297 err = check_bpf_snprintf_call(env, regs); 10298 break; 10299 case BPF_FUNC_loop: 10300 update_loop_inline_state(env, meta.subprogno); 10301 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10302 * is finished, thus mark it precise. 10303 */ 10304 err = mark_chain_precision(env, BPF_REG_1); 10305 if (err) 10306 return err; 10307 if (cur_func(env)->callback_depth < reg_umax(®s[BPF_REG_1])) { 10308 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10309 set_loop_callback_state); 10310 } else { 10311 cur_func(env)->callback_depth = 0; 10312 if (env->log.level & BPF_LOG_LEVEL2) 10313 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10314 env->cur_state->curframe); 10315 } 10316 break; 10317 case BPF_FUNC_dynptr_from_mem: 10318 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10319 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10320 reg_type_str(env, regs[BPF_REG_1].type)); 10321 return -EACCES; 10322 } 10323 break; 10324 case BPF_FUNC_set_retval: 10325 { 10326 struct bpf_retval_range range = { 10327 .minval = -MAX_ERRNO, 10328 .maxval = 0, 10329 .return_32bit = true 10330 }; 10331 struct bpf_reg_state *r1 = ®s[BPF_REG_1]; 10332 10333 if (r1->type != SCALAR_VALUE) { 10334 verbose(env, "R1 is not a scalar\n"); 10335 return -EINVAL; 10336 } 10337 10338 /* CGROUP_GETSOCKOPT is allowed to return arbitrary value */ 10339 if (prog_type == BPF_PROG_TYPE_CGROUP_SOCKOPT && 10340 env->prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT) 10341 break; 10342 10343 if (prog_type == BPF_PROG_TYPE_LSM && 10344 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10345 if (!env->prog->aux->attach_func_proto->type) { 10346 /* Make sure programs that attach to void 10347 * hooks don't try to modify return value. 10348 */ 10349 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10350 return -EINVAL; 10351 } 10352 bpf_lsm_get_retval_range(env->prog, &range); 10353 } 10354 10355 err = mark_chain_precision(env, BPF_REG_1); 10356 if (err) 10357 return err; 10358 10359 if (!retval_range_within(range, r1)) { 10360 verbose_invalid_scalar(env, r1, range, "At bpf_set_retval", "R1"); 10361 return -EINVAL; 10362 } 10363 10364 break; 10365 } 10366 case BPF_FUNC_dynptr_write: 10367 { 10368 enum bpf_dynptr_type dynptr_type = meta.dynptr.type; 10369 10370 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10371 return -EFAULT; 10372 10373 if (dynptr_type == BPF_DYNPTR_TYPE_SKB || 10374 dynptr_type == BPF_DYNPTR_TYPE_SKB_META) 10375 /* this will trigger clear_all_pkt_pointers(), which will 10376 * invalidate all dynptr slices associated with the skb 10377 */ 10378 changes_data = true; 10379 10380 break; 10381 } 10382 case BPF_FUNC_per_cpu_ptr: 10383 case BPF_FUNC_this_cpu_ptr: 10384 { 10385 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10386 const struct btf_type *type; 10387 10388 if (reg->type & MEM_RCU) { 10389 type = btf_type_by_id(reg->btf, reg->btf_id); 10390 if (!type || !btf_type_is_struct(type)) { 10391 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10392 return -EFAULT; 10393 } 10394 returns_cpu_specific_alloc_ptr = true; 10395 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10396 } 10397 break; 10398 } 10399 case BPF_FUNC_user_ringbuf_drain: 10400 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10401 set_user_ringbuf_callback_state); 10402 break; 10403 } 10404 10405 if (err) 10406 return err; 10407 10408 /* reset caller saved regs */ 10409 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10410 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 10411 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10412 } 10413 invalidate_outgoing_stack_args(env, cur_func(env)); 10414 10415 /* helper call returns 64-bit value. */ 10416 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10417 10418 /* update return register (already marked as written above) */ 10419 ret_type = fn->ret_type; 10420 ret_flag = type_flag(ret_type); 10421 10422 switch (base_type(ret_type)) { 10423 case RET_INTEGER: 10424 /* sets type to SCALAR_VALUE */ 10425 mark_reg_unknown(env, regs, BPF_REG_0); 10426 break; 10427 case RET_VOID: 10428 regs[BPF_REG_0].type = NOT_INIT; 10429 break; 10430 case RET_PTR_TO_MAP_VALUE: 10431 /* There is no offset yet applied, variable or fixed */ 10432 mark_reg_known_zero(env, regs, BPF_REG_0); 10433 /* remember map_ptr, so that check_map_access() 10434 * can check 'value_size' boundary of memory access 10435 * to map element returned from bpf_map_lookup_elem() 10436 */ 10437 if (meta.map.ptr == NULL) { 10438 verifier_bug(env, "unexpected null map_ptr"); 10439 return -EFAULT; 10440 } 10441 10442 if (func_id == BPF_FUNC_map_lookup_elem && 10443 can_elide_value_nullness(meta.map.ptr) && 10444 meta.const_map_key >= 0 && 10445 meta.const_map_key < meta.map.ptr->max_entries) 10446 ret_flag &= ~PTR_MAYBE_NULL; 10447 10448 regs[BPF_REG_0].map_ptr = meta.map.ptr; 10449 regs[BPF_REG_0].map_uid = meta.map.uid; 10450 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10451 if (!type_may_be_null(ret_flag) && 10452 btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 10453 regs[BPF_REG_0].id = ++env->id_gen; 10454 } 10455 break; 10456 case RET_PTR_TO_SOCKET: 10457 mark_reg_known_zero(env, regs, BPF_REG_0); 10458 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10459 break; 10460 case RET_PTR_TO_SOCK_COMMON: 10461 mark_reg_known_zero(env, regs, BPF_REG_0); 10462 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10463 break; 10464 case RET_PTR_TO_TCP_SOCK: 10465 mark_reg_known_zero(env, regs, BPF_REG_0); 10466 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10467 break; 10468 case RET_PTR_TO_MEM: 10469 mark_reg_known_zero(env, regs, BPF_REG_0); 10470 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10471 regs[BPF_REG_0].mem_size = meta.mem_size; 10472 break; 10473 case RET_PTR_TO_MEM_OR_BTF_ID: 10474 { 10475 const struct btf_type *t; 10476 10477 mark_reg_known_zero(env, regs, BPF_REG_0); 10478 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10479 if (!btf_type_is_struct(t)) { 10480 u32 tsize; 10481 const struct btf_type *ret; 10482 const char *tname; 10483 10484 /* resolve the type size of ksym. */ 10485 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10486 if (IS_ERR(ret)) { 10487 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10488 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10489 tname, PTR_ERR(ret)); 10490 return -EINVAL; 10491 } 10492 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10493 regs[BPF_REG_0].mem_size = tsize; 10494 } else { 10495 if (returns_cpu_specific_alloc_ptr) { 10496 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10497 } else { 10498 /* MEM_RDONLY may be carried from ret_flag, but it 10499 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10500 * it will confuse the check of PTR_TO_BTF_ID in 10501 * check_mem_access(). 10502 */ 10503 ret_flag &= ~MEM_RDONLY; 10504 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10505 } 10506 10507 regs[BPF_REG_0].btf = meta.ret_btf; 10508 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10509 } 10510 break; 10511 } 10512 case RET_PTR_TO_BTF_ID: 10513 { 10514 struct btf *ret_btf; 10515 int ret_btf_id; 10516 10517 mark_reg_known_zero(env, regs, BPF_REG_0); 10518 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10519 if (func_id == BPF_FUNC_kptr_xchg) { 10520 ret_btf = meta.kptr_field->kptr.btf; 10521 ret_btf_id = meta.kptr_field->kptr.btf_id; 10522 if (!btf_is_kernel(ret_btf)) { 10523 regs[BPF_REG_0].type |= MEM_ALLOC; 10524 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10525 regs[BPF_REG_0].type |= MEM_PERCPU; 10526 } 10527 } else { 10528 if (fn->ret_btf_id == BPF_PTR_POISON) { 10529 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type", 10530 func_id_name(func_id)); 10531 return -EFAULT; 10532 } 10533 ret_btf = btf_vmlinux; 10534 ret_btf_id = *fn->ret_btf_id; 10535 } 10536 if (ret_btf_id == 0) { 10537 verbose(env, "invalid return type %u of func %s#%d\n", 10538 base_type(ret_type), func_id_name(func_id), 10539 func_id); 10540 return -EINVAL; 10541 } 10542 regs[BPF_REG_0].btf = ret_btf; 10543 regs[BPF_REG_0].btf_id = ret_btf_id; 10544 break; 10545 } 10546 default: 10547 verbose(env, "unknown return type %u of func %s#%d\n", 10548 base_type(ret_type), func_id_name(func_id), func_id); 10549 return -EINVAL; 10550 } 10551 10552 if (type_may_be_null(regs[BPF_REG_0].type)) 10553 regs[BPF_REG_0].id = ++env->id_gen; 10554 10555 if (is_ptr_cast_function(func_id) && 10556 find_reference_state(env->cur_state, meta.ref_obj.id)) { 10557 struct bpf_verifier_state *branch; 10558 struct bpf_reg_state *r0; 10559 10560 err = validate_ref_obj(env, &meta.ref_obj); 10561 if (err) 10562 return err; 10563 10564 /* 10565 * In order for a release of any of the original or cast pointers 10566 * to invalidate all other pointers, reuse the same reference id for 10567 * the cast result. 10568 * This reference id can't be used for nullness propagation, 10569 * as cast might return NULL for a non-NULL input. 10570 * Hence, explore the NULL case as a separate branch. 10571 */ 10572 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10573 if (IS_ERR(branch)) 10574 return PTR_ERR(branch); 10575 10576 r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0]; 10577 __mark_reg_known_zero(r0); 10578 r0->type = SCALAR_VALUE; 10579 10580 regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL; 10581 regs[BPF_REG_0].id = meta.ref_obj.id; 10582 } else if (is_acquire_function(func_id, meta.map.ptr)) { 10583 int id = acquire_reference(env, insn_idx, 0); 10584 10585 if (id < 0) 10586 return id; 10587 10588 regs[BPF_REG_0].id = id; 10589 } 10590 10591 if (func_id == BPF_FUNC_dynptr_data) 10592 regs[BPF_REG_0].parent_id = meta.dynptr.id; 10593 10594 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10595 if (err) 10596 return err; 10597 10598 err = check_map_func_compatibility(env, meta.map.ptr, func_id); 10599 if (err) 10600 return err; 10601 10602 if ((func_id == BPF_FUNC_get_stack || 10603 func_id == BPF_FUNC_get_task_stack) && 10604 !env->prog->has_callchain_buf) { 10605 const char *err_str; 10606 10607 #ifdef CONFIG_PERF_EVENTS 10608 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10609 err_str = "cannot get callchain buffer for func %s#%d\n"; 10610 #else 10611 err = -ENOTSUPP; 10612 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10613 #endif 10614 if (err) { 10615 verbose(env, err_str, func_id_name(func_id), func_id); 10616 return err; 10617 } 10618 10619 env->prog->has_callchain_buf = true; 10620 } 10621 10622 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10623 env->prog->call_get_stack = true; 10624 10625 if (func_id == BPF_FUNC_get_func_ip) { 10626 if (check_get_func_ip(env)) 10627 return -ENOTSUPP; 10628 env->prog->call_get_func_ip = true; 10629 } 10630 10631 if (func_id == BPF_FUNC_tail_call) { 10632 if (env->cur_state->curframe) { 10633 struct bpf_verifier_state *branch; 10634 10635 mark_reg_scratched(env, BPF_REG_0); 10636 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10637 if (IS_ERR(branch)) 10638 return PTR_ERR(branch); 10639 clear_all_pkt_pointers(env); 10640 mark_reg_unknown(env, regs, BPF_REG_0); 10641 err = prepare_func_exit(env, &env->insn_idx); 10642 if (err) 10643 return err; 10644 env->insn_idx--; 10645 } else { 10646 changes_data = false; 10647 } 10648 } 10649 10650 if (changes_data) 10651 clear_all_pkt_pointers(env); 10652 return 0; 10653 } 10654 10655 /* mark_btf_func_reg_size() is used when the reg size is determined by 10656 * the BTF func_proto's return value size and argument. 10657 */ 10658 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs, 10659 u32 regno, size_t reg_size) 10660 { 10661 struct bpf_reg_state *reg = ®s[regno]; 10662 10663 if (regno == BPF_REG_0) { 10664 /* Function return value */ 10665 reg->subreg_def = reg_size == sizeof(u64) ? 10666 DEF_NOT_SUBREG : env->insn_idx + 1; 10667 } else if (reg_size == sizeof(u64)) { 10668 /* Function argument */ 10669 mark_insn_zext(env, reg); 10670 } 10671 } 10672 10673 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10674 size_t reg_size) 10675 { 10676 return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size); 10677 } 10678 10679 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10680 { 10681 return meta->kfunc_flags & KF_ACQUIRE; 10682 } 10683 10684 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10685 { 10686 return meta->kfunc_flags & KF_RELEASE; 10687 } 10688 10689 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10690 { 10691 return meta->kfunc_flags & KF_DESTRUCTIVE; 10692 } 10693 10694 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10695 { 10696 return meta->kfunc_flags & KF_RCU; 10697 } 10698 10699 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10700 { 10701 return meta->kfunc_flags & KF_RCU_PROTECTED; 10702 } 10703 10704 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10705 const struct btf_param *arg, 10706 const struct bpf_reg_state *reg) 10707 { 10708 const struct btf_type *t; 10709 10710 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10711 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10712 return false; 10713 10714 return btf_param_match_suffix(btf, arg, "__sz"); 10715 } 10716 10717 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10718 const struct btf_param *arg, 10719 const struct bpf_reg_state *reg) 10720 { 10721 const struct btf_type *t; 10722 10723 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10724 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10725 return false; 10726 10727 return btf_param_match_suffix(btf, arg, "__szk"); 10728 } 10729 10730 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10731 { 10732 return btf_param_match_suffix(btf, arg, "__k"); 10733 } 10734 10735 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10736 { 10737 return btf_param_match_suffix(btf, arg, "__ign"); 10738 } 10739 10740 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 10741 { 10742 return btf_param_match_suffix(btf, arg, "__map"); 10743 } 10744 10745 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10746 { 10747 return btf_param_match_suffix(btf, arg, "__alloc"); 10748 } 10749 10750 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10751 { 10752 return btf_param_match_suffix(btf, arg, "__uninit"); 10753 } 10754 10755 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10756 { 10757 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 10758 } 10759 10760 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10761 { 10762 return btf_param_match_suffix(btf, arg, "__nullable"); 10763 } 10764 10765 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg) 10766 { 10767 return btf_param_match_suffix(btf, arg, "__nonown_allowed"); 10768 } 10769 10770 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10771 { 10772 return btf_param_match_suffix(btf, arg, "__str"); 10773 } 10774 10775 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg) 10776 { 10777 return btf_param_match_suffix(btf, arg, "__irq_flag"); 10778 } 10779 10780 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10781 const struct btf_param *arg, 10782 const char *name) 10783 { 10784 int len, target_len = strlen(name); 10785 const char *param_name; 10786 10787 param_name = btf_name_by_offset(btf, arg->name_off); 10788 if (str_is_empty(param_name)) 10789 return false; 10790 len = strlen(param_name); 10791 if (len != target_len) 10792 return false; 10793 if (strcmp(param_name, name)) 10794 return false; 10795 10796 return true; 10797 } 10798 10799 enum { 10800 KF_ARG_DYNPTR_ID, 10801 KF_ARG_LIST_HEAD_ID, 10802 KF_ARG_LIST_NODE_ID, 10803 KF_ARG_RB_ROOT_ID, 10804 KF_ARG_RB_NODE_ID, 10805 KF_ARG_WORKQUEUE_ID, 10806 KF_ARG_RES_SPIN_LOCK_ID, 10807 KF_ARG_TASK_WORK_ID, 10808 KF_ARG_PROG_AUX_ID, 10809 KF_ARG_TIMER_ID 10810 }; 10811 10812 BTF_ID_LIST(kf_arg_btf_ids) 10813 BTF_ID(struct, bpf_dynptr) 10814 BTF_ID(struct, bpf_list_head) 10815 BTF_ID(struct, bpf_list_node) 10816 BTF_ID(struct, bpf_rb_root) 10817 BTF_ID(struct, bpf_rb_node) 10818 BTF_ID(struct, bpf_wq) 10819 BTF_ID(struct, bpf_res_spin_lock) 10820 BTF_ID(struct, bpf_task_work) 10821 BTF_ID(struct, bpf_prog_aux) 10822 BTF_ID(struct, bpf_timer) 10823 10824 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10825 const struct btf_param *arg, int type) 10826 { 10827 const struct btf_type *t; 10828 u32 res_id; 10829 10830 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10831 if (!t) 10832 return false; 10833 if (!btf_type_is_ptr(t)) 10834 return false; 10835 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10836 if (!t) 10837 return false; 10838 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10839 } 10840 10841 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10842 { 10843 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10844 } 10845 10846 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10847 { 10848 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10849 } 10850 10851 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10852 { 10853 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10854 } 10855 10856 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10857 { 10858 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10859 } 10860 10861 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10862 { 10863 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10864 } 10865 10866 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg) 10867 { 10868 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID); 10869 } 10870 10871 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 10872 { 10873 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 10874 } 10875 10876 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg) 10877 { 10878 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID); 10879 } 10880 10881 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg) 10882 { 10883 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID); 10884 } 10885 10886 static bool is_rbtree_node_type(const struct btf_type *t) 10887 { 10888 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]); 10889 } 10890 10891 static bool is_list_node_type(const struct btf_type *t) 10892 { 10893 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]); 10894 } 10895 10896 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10897 const struct btf_param *arg) 10898 { 10899 const struct btf_type *t; 10900 10901 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10902 if (!t) 10903 return false; 10904 10905 return true; 10906 } 10907 10908 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg) 10909 { 10910 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID); 10911 } 10912 10913 /* 10914 * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF: 10915 * - the _impl prototype with full arg list (meta->func_proto) 10916 * - the BPF API prototype w/o implicit args (func->type in BTF) 10917 * To determine whether an argument is implicit, we compare its position 10918 * against the number of arguments in the prototype w/o implicit args. 10919 */ 10920 static bool is_kfunc_arg_implicit(const struct bpf_kfunc_call_arg_meta *meta, u32 arg_idx) 10921 { 10922 const struct btf_type *func, *func_proto; 10923 u32 argn; 10924 10925 if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS)) 10926 return false; 10927 10928 func = btf_type_by_id(meta->btf, meta->func_id); 10929 func_proto = btf_type_by_id(meta->btf, func->type); 10930 argn = btf_type_vlen(func_proto); 10931 10932 return argn <= arg_idx; 10933 } 10934 10935 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10936 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10937 const struct btf *btf, 10938 const struct btf_type *t, int rec) 10939 { 10940 const struct btf_type *member_type; 10941 const struct btf_member *member; 10942 u32 i; 10943 10944 if (!btf_type_is_struct(t)) 10945 return false; 10946 10947 for_each_member(i, t, member) { 10948 const struct btf_array *array; 10949 10950 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10951 if (btf_type_is_struct(member_type)) { 10952 if (rec >= 3) { 10953 verbose(env, "max struct nesting depth exceeded\n"); 10954 return false; 10955 } 10956 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10957 return false; 10958 continue; 10959 } 10960 if (btf_type_is_array(member_type)) { 10961 array = btf_array(member_type); 10962 if (!array->nelems) 10963 return false; 10964 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10965 if (!btf_type_is_scalar(member_type)) 10966 return false; 10967 continue; 10968 } 10969 if (!btf_type_is_scalar(member_type)) 10970 return false; 10971 } 10972 return true; 10973 } 10974 10975 enum kfunc_ptr_arg_type { 10976 KF_ARG_PTR_TO_CTX, 10977 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10978 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10979 KF_ARG_PTR_TO_DYNPTR, 10980 KF_ARG_PTR_TO_ITER, 10981 KF_ARG_PTR_TO_LIST_HEAD, 10982 KF_ARG_PTR_TO_LIST_NODE, 10983 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10984 KF_ARG_PTR_TO_MEM, 10985 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10986 KF_ARG_PTR_TO_CALLBACK, 10987 KF_ARG_PTR_TO_RB_ROOT, 10988 KF_ARG_PTR_TO_RB_NODE, 10989 KF_ARG_PTR_TO_NULL, 10990 KF_ARG_PTR_TO_CONST_STR, 10991 KF_ARG_PTR_TO_MAP, 10992 KF_ARG_PTR_TO_TIMER, 10993 KF_ARG_PTR_TO_WORKQUEUE, 10994 KF_ARG_PTR_TO_IRQ_FLAG, 10995 KF_ARG_PTR_TO_RES_SPIN_LOCK, 10996 KF_ARG_PTR_TO_TASK_WORK, 10997 }; 10998 10999 enum special_kfunc_type { 11000 KF_bpf_obj_new_impl, 11001 KF_bpf_obj_new, 11002 KF_bpf_obj_drop_impl, 11003 KF_bpf_obj_drop, 11004 KF_bpf_refcount_acquire_impl, 11005 KF_bpf_refcount_acquire, 11006 KF_bpf_list_push_front_impl, 11007 KF_bpf_list_push_front, 11008 KF_bpf_list_push_back_impl, 11009 KF_bpf_list_push_back, 11010 KF_bpf_list_add, 11011 KF_bpf_list_pop_front, 11012 KF_bpf_list_pop_back, 11013 KF_bpf_list_del, 11014 KF_bpf_list_front, 11015 KF_bpf_list_back, 11016 KF_bpf_list_is_first, 11017 KF_bpf_list_is_last, 11018 KF_bpf_list_empty, 11019 KF_bpf_cast_to_kern_ctx, 11020 KF_bpf_rdonly_cast, 11021 KF_bpf_rcu_read_lock, 11022 KF_bpf_rcu_read_unlock, 11023 KF_bpf_rbtree_remove, 11024 KF_bpf_rbtree_add_impl, 11025 KF_bpf_rbtree_add, 11026 KF_bpf_rbtree_first, 11027 KF_bpf_rbtree_root, 11028 KF_bpf_rbtree_left, 11029 KF_bpf_rbtree_right, 11030 KF_bpf_dynptr_from_skb, 11031 KF_bpf_dynptr_from_xdp, 11032 KF_bpf_dynptr_from_skb_meta, 11033 KF_bpf_xdp_pull_data, 11034 KF_bpf_dynptr_slice, 11035 KF_bpf_dynptr_slice_rdwr, 11036 KF_bpf_dynptr_clone, 11037 KF_bpf_percpu_obj_new_impl, 11038 KF_bpf_percpu_obj_new, 11039 KF_bpf_percpu_obj_drop_impl, 11040 KF_bpf_percpu_obj_drop, 11041 KF_bpf_throw, 11042 KF_bpf_wq_set_callback, 11043 KF_bpf_preempt_disable, 11044 KF_bpf_preempt_enable, 11045 KF_bpf_iter_css_task_new, 11046 KF_bpf_session_cookie, 11047 KF_bpf_get_kmem_cache, 11048 KF_bpf_local_irq_save, 11049 KF_bpf_local_irq_restore, 11050 KF_bpf_iter_num_new, 11051 KF_bpf_iter_num_next, 11052 KF_bpf_iter_num_destroy, 11053 KF_bpf_set_dentry_xattr, 11054 KF_bpf_remove_dentry_xattr, 11055 KF_bpf_res_spin_lock, 11056 KF_bpf_res_spin_unlock, 11057 KF_bpf_res_spin_lock_irqsave, 11058 KF_bpf_res_spin_unlock_irqrestore, 11059 KF_bpf_dynptr_from_file, 11060 KF_bpf_dynptr_file_discard, 11061 KF___bpf_trap, 11062 KF_bpf_task_work_schedule_signal, 11063 KF_bpf_task_work_schedule_resume, 11064 KF_bpf_arena_alloc_pages, 11065 KF_bpf_arena_free_pages, 11066 KF_bpf_arena_reserve_pages, 11067 KF_bpf_session_is_return, 11068 KF_bpf_stream_vprintk, 11069 KF_bpf_stream_print_stack, 11070 }; 11071 11072 BTF_ID_LIST(special_kfunc_list) 11073 BTF_ID(func, bpf_obj_new_impl) 11074 BTF_ID(func, bpf_obj_new) 11075 BTF_ID(func, bpf_obj_drop_impl) 11076 BTF_ID(func, bpf_obj_drop) 11077 BTF_ID(func, bpf_refcount_acquire_impl) 11078 BTF_ID(func, bpf_refcount_acquire) 11079 BTF_ID(func, bpf_list_push_front_impl) 11080 BTF_ID(func, bpf_list_push_front) 11081 BTF_ID(func, bpf_list_push_back_impl) 11082 BTF_ID(func, bpf_list_push_back) 11083 BTF_ID(func, bpf_list_add) 11084 BTF_ID(func, bpf_list_pop_front) 11085 BTF_ID(func, bpf_list_pop_back) 11086 BTF_ID(func, bpf_list_del) 11087 BTF_ID(func, bpf_list_front) 11088 BTF_ID(func, bpf_list_back) 11089 BTF_ID(func, bpf_list_is_first) 11090 BTF_ID(func, bpf_list_is_last) 11091 BTF_ID(func, bpf_list_empty) 11092 BTF_ID(func, bpf_cast_to_kern_ctx) 11093 BTF_ID(func, bpf_rdonly_cast) 11094 BTF_ID(func, bpf_rcu_read_lock) 11095 BTF_ID(func, bpf_rcu_read_unlock) 11096 BTF_ID(func, bpf_rbtree_remove) 11097 BTF_ID(func, bpf_rbtree_add_impl) 11098 BTF_ID(func, bpf_rbtree_add) 11099 BTF_ID(func, bpf_rbtree_first) 11100 BTF_ID(func, bpf_rbtree_root) 11101 BTF_ID(func, bpf_rbtree_left) 11102 BTF_ID(func, bpf_rbtree_right) 11103 #ifdef CONFIG_NET 11104 BTF_ID(func, bpf_dynptr_from_skb) 11105 BTF_ID(func, bpf_dynptr_from_xdp) 11106 BTF_ID(func, bpf_dynptr_from_skb_meta) 11107 BTF_ID(func, bpf_xdp_pull_data) 11108 #else 11109 BTF_ID_UNUSED 11110 BTF_ID_UNUSED 11111 BTF_ID_UNUSED 11112 BTF_ID_UNUSED 11113 #endif 11114 BTF_ID(func, bpf_dynptr_slice) 11115 BTF_ID(func, bpf_dynptr_slice_rdwr) 11116 BTF_ID(func, bpf_dynptr_clone) 11117 BTF_ID(func, bpf_percpu_obj_new_impl) 11118 BTF_ID(func, bpf_percpu_obj_new) 11119 BTF_ID(func, bpf_percpu_obj_drop_impl) 11120 BTF_ID(func, bpf_percpu_obj_drop) 11121 BTF_ID(func, bpf_throw) 11122 BTF_ID(func, bpf_wq_set_callback) 11123 BTF_ID(func, bpf_preempt_disable) 11124 BTF_ID(func, bpf_preempt_enable) 11125 #ifdef CONFIG_CGROUPS 11126 BTF_ID(func, bpf_iter_css_task_new) 11127 #else 11128 BTF_ID_UNUSED 11129 #endif 11130 #ifdef CONFIG_BPF_EVENTS 11131 BTF_ID(func, bpf_session_cookie) 11132 #else 11133 BTF_ID_UNUSED 11134 #endif 11135 BTF_ID(func, bpf_get_kmem_cache) 11136 BTF_ID(func, bpf_local_irq_save) 11137 BTF_ID(func, bpf_local_irq_restore) 11138 BTF_ID(func, bpf_iter_num_new) 11139 BTF_ID(func, bpf_iter_num_next) 11140 BTF_ID(func, bpf_iter_num_destroy) 11141 #ifdef CONFIG_BPF_LSM 11142 BTF_ID(func, bpf_set_dentry_xattr) 11143 BTF_ID(func, bpf_remove_dentry_xattr) 11144 #else 11145 BTF_ID_UNUSED 11146 BTF_ID_UNUSED 11147 #endif 11148 BTF_ID(func, bpf_res_spin_lock) 11149 BTF_ID(func, bpf_res_spin_unlock) 11150 BTF_ID(func, bpf_res_spin_lock_irqsave) 11151 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 11152 BTF_ID(func, bpf_dynptr_from_file) 11153 BTF_ID(func, bpf_dynptr_file_discard) 11154 BTF_ID(func, __bpf_trap) 11155 BTF_ID(func, bpf_task_work_schedule_signal) 11156 BTF_ID(func, bpf_task_work_schedule_resume) 11157 BTF_ID(func, bpf_arena_alloc_pages) 11158 BTF_ID(func, bpf_arena_free_pages) 11159 BTF_ID(func, bpf_arena_reserve_pages) 11160 #ifdef CONFIG_BPF_EVENTS 11161 BTF_ID(func, bpf_session_is_return) 11162 #else 11163 BTF_ID_UNUSED 11164 #endif 11165 BTF_ID(func, bpf_stream_vprintk) 11166 BTF_ID(func, bpf_stream_print_stack) 11167 11168 static bool is_bpf_obj_new_kfunc(u32 func_id) 11169 { 11170 return func_id == special_kfunc_list[KF_bpf_obj_new] || 11171 func_id == special_kfunc_list[KF_bpf_obj_new_impl]; 11172 } 11173 11174 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id) 11175 { 11176 return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] || 11177 func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]; 11178 } 11179 11180 static bool is_bpf_obj_drop_kfunc(u32 func_id) 11181 { 11182 return func_id == special_kfunc_list[KF_bpf_obj_drop] || 11183 func_id == special_kfunc_list[KF_bpf_obj_drop_impl]; 11184 } 11185 11186 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id) 11187 { 11188 return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] || 11189 func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]; 11190 } 11191 11192 static bool is_bpf_refcount_acquire_kfunc(u32 func_id) 11193 { 11194 return func_id == special_kfunc_list[KF_bpf_refcount_acquire] || 11195 func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11196 } 11197 11198 static bool is_bpf_list_push_kfunc(u32 func_id) 11199 { 11200 return func_id == special_kfunc_list[KF_bpf_list_push_front] || 11201 func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11202 func_id == special_kfunc_list[KF_bpf_list_push_back] || 11203 func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11204 func_id == special_kfunc_list[KF_bpf_list_add]; 11205 } 11206 11207 static bool is_bpf_rbtree_add_kfunc(u32 func_id) 11208 { 11209 return func_id == special_kfunc_list[KF_bpf_rbtree_add] || 11210 func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11211 } 11212 11213 static bool is_task_work_add_kfunc(u32 func_id) 11214 { 11215 return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] || 11216 func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume]; 11217 } 11218 11219 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11220 { 11221 if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref) 11222 return false; 11223 11224 return meta->kfunc_flags & KF_RET_NULL; 11225 } 11226 11227 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11228 { 11229 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11230 } 11231 11232 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11233 { 11234 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11235 } 11236 11237 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11238 { 11239 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11240 } 11241 11242 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11243 { 11244 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11245 } 11246 11247 bool bpf_is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta) 11248 { 11249 return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data]; 11250 } 11251 11252 static enum kfunc_ptr_arg_type 11253 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, struct bpf_func_state *caller, 11254 struct bpf_reg_state *regs, struct bpf_kfunc_call_arg_meta *meta, 11255 const struct btf_type *t, const struct btf_type *ref_t, 11256 const char *ref_tname, const struct btf_param *args, 11257 int arg, int nargs, argno_t argno, struct bpf_reg_state *reg) 11258 { 11259 bool arg_mem_size = false; 11260 11261 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 11262 meta->func_id == special_kfunc_list[KF_bpf_session_is_return] || 11263 meta->func_id == special_kfunc_list[KF_bpf_session_cookie]) 11264 return KF_ARG_PTR_TO_CTX; 11265 11266 if (arg + 1 < nargs && 11267 (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)) || 11268 is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)))) 11269 arg_mem_size = true; 11270 11271 /* In this function, we verify the kfunc's BTF as per the argument type, 11272 * leaving the rest of the verification with respect to the register 11273 * type to our caller. When a set of conditions hold in the BTF type of 11274 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11275 */ 11276 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg)) 11277 return KF_ARG_PTR_TO_CTX; 11278 11279 if (is_kfunc_arg_nullable(meta->btf, &args[arg]) && bpf_register_is_null(reg) && 11280 !arg_mem_size) 11281 return KF_ARG_PTR_TO_NULL; 11282 11283 if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg])) 11284 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11285 11286 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg])) 11287 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11288 11289 if (is_kfunc_arg_dynptr(meta->btf, &args[arg])) 11290 return KF_ARG_PTR_TO_DYNPTR; 11291 11292 if (is_kfunc_arg_iter(meta, arg, &args[arg])) 11293 return KF_ARG_PTR_TO_ITER; 11294 11295 if (is_kfunc_arg_list_head(meta->btf, &args[arg])) 11296 return KF_ARG_PTR_TO_LIST_HEAD; 11297 11298 if (is_kfunc_arg_list_node(meta->btf, &args[arg])) 11299 return KF_ARG_PTR_TO_LIST_NODE; 11300 11301 if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg])) 11302 return KF_ARG_PTR_TO_RB_ROOT; 11303 11304 if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg])) 11305 return KF_ARG_PTR_TO_RB_NODE; 11306 11307 if (is_kfunc_arg_const_str(meta->btf, &args[arg])) 11308 return KF_ARG_PTR_TO_CONST_STR; 11309 11310 if (is_kfunc_arg_map(meta->btf, &args[arg])) 11311 return KF_ARG_PTR_TO_MAP; 11312 11313 if (is_kfunc_arg_wq(meta->btf, &args[arg])) 11314 return KF_ARG_PTR_TO_WORKQUEUE; 11315 11316 if (is_kfunc_arg_timer(meta->btf, &args[arg])) 11317 return KF_ARG_PTR_TO_TIMER; 11318 11319 if (is_kfunc_arg_task_work(meta->btf, &args[arg])) 11320 return KF_ARG_PTR_TO_TASK_WORK; 11321 11322 if (is_kfunc_arg_irq_flag(meta->btf, &args[arg])) 11323 return KF_ARG_PTR_TO_IRQ_FLAG; 11324 11325 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg])) 11326 return KF_ARG_PTR_TO_RES_SPIN_LOCK; 11327 11328 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11329 if (!btf_type_is_struct(ref_t)) { 11330 verbose(env, "kernel function %s %s pointer type %s %s is not supported\n", 11331 meta->func_name, reg_arg_name(env, argno), 11332 btf_type_str(ref_t), ref_tname); 11333 return -EINVAL; 11334 } 11335 return KF_ARG_PTR_TO_BTF_ID; 11336 } 11337 11338 if (is_kfunc_arg_callback(env, meta->btf, &args[arg])) 11339 return KF_ARG_PTR_TO_CALLBACK; 11340 11341 /* This is the catch all argument type of register types supported by 11342 * check_helper_mem_access. However, we only allow when argument type is 11343 * pointer to scalar, or struct composed (recursively) of scalars. When 11344 * arg_mem_size is true, the pointer can be void *. 11345 */ 11346 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11347 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11348 verbose(env, "%s pointer type %s %s must point to %sscalar, or struct with scalar\n", 11349 reg_arg_name(env, argno), 11350 btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11351 return -EINVAL; 11352 } 11353 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11354 } 11355 11356 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11357 struct bpf_reg_state *reg, 11358 const struct btf_type *ref_t, 11359 const char *ref_tname, u32 ref_id, 11360 struct bpf_kfunc_call_arg_meta *meta, 11361 int arg, argno_t argno) 11362 { 11363 const struct btf_type *reg_ref_t; 11364 bool strict_type_match = false; 11365 const struct btf *reg_btf; 11366 const char *reg_ref_tname; 11367 bool taking_projection; 11368 bool struct_same; 11369 u32 reg_ref_id; 11370 11371 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11372 reg_btf = reg->btf; 11373 reg_ref_id = reg->btf_id; 11374 } else { 11375 reg_btf = btf_vmlinux; 11376 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11377 } 11378 11379 /* Enforce strict type matching for calls to kfuncs that are acquiring 11380 * or releasing a reference, or are no-cast aliases. We do _not_ 11381 * enforce strict matching for kfuncs by default, 11382 * as we want to enable BPF programs to pass types that are bitwise 11383 * equivalent without forcing them to explicitly cast with something 11384 * like bpf_cast_to_kern_ctx(). 11385 * 11386 * For example, say we had a type like the following: 11387 * 11388 * struct bpf_cpumask { 11389 * cpumask_t cpumask; 11390 * refcount_t usage; 11391 * }; 11392 * 11393 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11394 * to a struct cpumask, so it would be safe to pass a struct 11395 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11396 * 11397 * The philosophy here is similar to how we allow scalars of different 11398 * types to be passed to kfuncs as long as the size is the same. The 11399 * only difference here is that we're simply allowing 11400 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11401 * resolve types. 11402 */ 11403 if ((is_kfunc_release(meta) && reg_is_referenced(env, reg)) || 11404 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11405 strict_type_match = true; 11406 11407 WARN_ON_ONCE(is_kfunc_release(meta) && !tnum_is_const(reg->var_off)); 11408 11409 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11410 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11411 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->var_off.value, 11412 meta->btf, ref_id, strict_type_match, 11413 !type_is_alloc(reg->type)); 11414 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11415 * actually use it -- it must cast to the underlying type. So we allow 11416 * caller to pass in the underlying type. 11417 */ 11418 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11419 if (!taking_projection && !struct_same) { 11420 verbose(env, "kernel function %s %s expected pointer to %s %s but %s has a pointer to %s %s\n", 11421 meta->func_name, reg_arg_name(env, argno), 11422 btf_type_str(ref_t), ref_tname, reg_arg_name(env, argno), 11423 btf_type_str(reg_ref_t), reg_ref_tname); 11424 return -EINVAL; 11425 } 11426 return 0; 11427 } 11428 11429 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 11430 struct bpf_kfunc_call_arg_meta *meta) 11431 { 11432 int err, spi, kfunc_class = IRQ_NATIVE_KFUNC; 11433 bool irq_save; 11434 11435 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] || 11436 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) { 11437 irq_save = true; 11438 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 11439 kfunc_class = IRQ_LOCK_KFUNC; 11440 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] || 11441 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) { 11442 irq_save = false; 11443 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 11444 kfunc_class = IRQ_LOCK_KFUNC; 11445 } else { 11446 verifier_bug(env, "unknown irq flags kfunc"); 11447 return -EFAULT; 11448 } 11449 11450 if (irq_save) { 11451 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 11452 verbose(env, "expected uninitialized irq flag as %s\n", 11453 reg_arg_name(env, argno)); 11454 return -EINVAL; 11455 } 11456 11457 err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW, 11458 BPF_WRITE, -1, false, false); 11459 if (err) 11460 return err; 11461 11462 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 11463 if (err) 11464 return err; 11465 } else { 11466 err = is_irq_flag_reg_valid_init(env, reg); 11467 if (err) { 11468 verbose(env, "expected an initialized irq flag as %s\n", 11469 reg_arg_name(env, argno)); 11470 return err; 11471 } 11472 11473 spi = irq_flag_get_spi(env, reg); 11474 if (spi < 0) 11475 return spi; 11476 11477 mark_stack_slots_scratched(env, spi, 1); 11478 11479 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 11480 if (err) 11481 return err; 11482 } 11483 return 0; 11484 } 11485 11486 11487 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11488 { 11489 struct btf_record *rec = reg_btf_record(reg); 11490 11491 if (!env->cur_state->active_locks) { 11492 verifier_bug(env, "%s w/o active lock", __func__); 11493 return -EFAULT; 11494 } 11495 11496 if (type_flag(reg->type) & NON_OWN_REF) { 11497 verifier_bug(env, "NON_OWN_REF already set"); 11498 return -EFAULT; 11499 } 11500 11501 reg->type |= NON_OWN_REF; 11502 if (rec->refcount_off >= 0) 11503 reg->type |= MEM_RCU; 11504 11505 return 0; 11506 } 11507 11508 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id) 11509 { 11510 struct bpf_func_state *unused; 11511 struct bpf_reg_state *reg; 11512 11513 WARN_ON_ONCE(release_reference_nomark(env->cur_state, id)); 11514 11515 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11516 if (reg->id == id) { 11517 reg->id = 0; 11518 ref_set_non_owning(env, reg); 11519 } 11520 })); 11521 11522 return; 11523 } 11524 11525 /* Implementation details: 11526 * 11527 * Each register points to some region of memory, which we define as an 11528 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11529 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11530 * allocation. The lock and the data it protects are colocated in the same 11531 * memory region. 11532 * 11533 * Hence, everytime a register holds a pointer value pointing to such 11534 * allocation, the verifier preserves a unique reg->id for it. 11535 * 11536 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11537 * bpf_spin_lock is called. 11538 * 11539 * To enable this, lock state in the verifier captures two values: 11540 * active_lock.ptr = Register's type specific pointer 11541 * active_lock.id = A unique ID for each register pointer value 11542 * 11543 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11544 * supported register types. 11545 * 11546 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11547 * allocated objects is the reg->btf pointer. 11548 * 11549 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11550 * can establish the provenance of the map value statically for each distinct 11551 * lookup into such maps. They always contain a single map value hence unique 11552 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11553 * 11554 * So, in case of global variables, they use array maps with max_entries = 1, 11555 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11556 * into the same map value as max_entries is 1, as described above). 11557 * 11558 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11559 * outer map pointer (in verifier context), but each lookup into an inner map 11560 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11561 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11562 * will get different reg->id assigned to each lookup, hence different 11563 * active_lock.id. 11564 * 11565 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11566 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11567 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11568 */ 11569 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11570 { 11571 struct bpf_reference_state *s; 11572 void *ptr; 11573 u32 id; 11574 11575 switch ((int)reg->type) { 11576 case PTR_TO_MAP_VALUE: 11577 ptr = reg->map_ptr; 11578 break; 11579 case PTR_TO_BTF_ID | MEM_ALLOC: 11580 ptr = reg->btf; 11581 break; 11582 default: 11583 verifier_bug(env, "unknown reg type for lock check"); 11584 return -EFAULT; 11585 } 11586 id = reg->id; 11587 11588 if (!env->cur_state->active_locks) 11589 return -EINVAL; 11590 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 11591 if (!s) { 11592 verbose(env, "held lock and object are not in the same allocation\n"); 11593 return -EINVAL; 11594 } 11595 return 0; 11596 } 11597 11598 static bool is_bpf_list_api_kfunc(u32 btf_id) 11599 { 11600 return is_bpf_list_push_kfunc(btf_id) || 11601 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11602 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 11603 btf_id == special_kfunc_list[KF_bpf_list_del] || 11604 btf_id == special_kfunc_list[KF_bpf_list_front] || 11605 btf_id == special_kfunc_list[KF_bpf_list_back] || 11606 btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11607 btf_id == special_kfunc_list[KF_bpf_list_is_last] || 11608 btf_id == special_kfunc_list[KF_bpf_list_empty]; 11609 } 11610 11611 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11612 { 11613 return is_bpf_rbtree_add_kfunc(btf_id) || 11614 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11615 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 11616 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 11617 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11618 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 11619 } 11620 11621 static bool is_bpf_iter_num_api_kfunc(u32 btf_id) 11622 { 11623 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] || 11624 btf_id == special_kfunc_list[KF_bpf_iter_num_next] || 11625 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy]; 11626 } 11627 11628 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11629 { 11630 return is_bpf_list_api_kfunc(btf_id) || 11631 is_bpf_rbtree_api_kfunc(btf_id) || 11632 is_bpf_refcount_acquire_kfunc(btf_id); 11633 } 11634 11635 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id) 11636 { 11637 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 11638 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 11639 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 11640 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]; 11641 } 11642 11643 static bool is_bpf_arena_kfunc(u32 btf_id) 11644 { 11645 return btf_id == special_kfunc_list[KF_bpf_arena_alloc_pages] || 11646 btf_id == special_kfunc_list[KF_bpf_arena_free_pages] || 11647 btf_id == special_kfunc_list[KF_bpf_arena_reserve_pages]; 11648 } 11649 11650 static bool is_bpf_stream_kfunc(u32 btf_id) 11651 { 11652 return btf_id == special_kfunc_list[KF_bpf_stream_vprintk] || 11653 btf_id == special_kfunc_list[KF_bpf_stream_print_stack]; 11654 } 11655 11656 static bool kfunc_spin_allowed(u32 btf_id) 11657 { 11658 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) || 11659 is_bpf_res_spin_lock_kfunc(btf_id) || is_bpf_arena_kfunc(btf_id) || 11660 is_bpf_stream_kfunc(btf_id); 11661 } 11662 11663 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11664 { 11665 return is_bpf_rbtree_add_kfunc(btf_id); 11666 } 11667 11668 static bool is_async_callback_calling_kfunc(u32 btf_id) 11669 { 11670 return is_bpf_wq_set_callback_kfunc(btf_id) || 11671 is_task_work_add_kfunc(btf_id); 11672 } 11673 11674 bool bpf_is_throw_kfunc(struct bpf_insn *insn) 11675 { 11676 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11677 insn->imm == special_kfunc_list[KF_bpf_throw]; 11678 } 11679 11680 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id) 11681 { 11682 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback]; 11683 } 11684 11685 static bool is_callback_calling_kfunc(u32 btf_id) 11686 { 11687 return is_sync_callback_calling_kfunc(btf_id) || 11688 is_async_callback_calling_kfunc(btf_id); 11689 } 11690 11691 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11692 { 11693 return is_bpf_rbtree_api_kfunc(btf_id); 11694 } 11695 11696 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11697 enum btf_field_type head_field_type, 11698 u32 kfunc_btf_id) 11699 { 11700 bool ret; 11701 11702 switch (head_field_type) { 11703 case BPF_LIST_HEAD: 11704 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11705 break; 11706 case BPF_RB_ROOT: 11707 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11708 break; 11709 default: 11710 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11711 btf_field_type_name(head_field_type)); 11712 return false; 11713 } 11714 11715 if (!ret) 11716 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11717 btf_field_type_name(head_field_type)); 11718 return ret; 11719 } 11720 11721 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11722 enum btf_field_type node_field_type, 11723 u32 kfunc_btf_id) 11724 { 11725 bool ret; 11726 11727 switch (node_field_type) { 11728 case BPF_LIST_NODE: 11729 ret = is_bpf_list_push_kfunc(kfunc_btf_id) || 11730 kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] || 11731 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11732 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last]; 11733 break; 11734 case BPF_RB_NODE: 11735 ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) || 11736 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11737 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11738 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 11739 break; 11740 default: 11741 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11742 btf_field_type_name(node_field_type)); 11743 return false; 11744 } 11745 11746 if (!ret) 11747 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11748 btf_field_type_name(node_field_type)); 11749 return ret; 11750 } 11751 11752 static int 11753 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11754 struct bpf_reg_state *reg, argno_t argno, 11755 struct bpf_kfunc_call_arg_meta *meta, 11756 enum btf_field_type head_field_type, 11757 struct btf_field **head_field) 11758 { 11759 const char *head_type_name; 11760 struct btf_field *field; 11761 struct btf_record *rec; 11762 u32 head_off; 11763 11764 if (meta->btf != btf_vmlinux) { 11765 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11766 return -EFAULT; 11767 } 11768 11769 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11770 return -EFAULT; 11771 11772 head_type_name = btf_field_type_name(head_field_type); 11773 if (!tnum_is_const(reg->var_off)) { 11774 verbose(env, 11775 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11776 reg_arg_name(env, argno), head_type_name); 11777 return -EINVAL; 11778 } 11779 11780 rec = reg_btf_record(reg); 11781 head_off = reg->var_off.value; 11782 field = btf_record_find(rec, head_off, head_field_type); 11783 if (!field) { 11784 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11785 return -EINVAL; 11786 } 11787 11788 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11789 if (check_reg_allocation_locked(env, reg)) { 11790 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11791 rec->spin_lock_off, head_type_name); 11792 return -EINVAL; 11793 } 11794 11795 if (*head_field) { 11796 verifier_bug(env, "repeating %s arg", head_type_name); 11797 return -EFAULT; 11798 } 11799 *head_field = field; 11800 return 0; 11801 } 11802 11803 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11804 struct bpf_reg_state *reg, argno_t argno, 11805 struct bpf_kfunc_call_arg_meta *meta) 11806 { 11807 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD, 11808 &meta->arg_list_head.field); 11809 } 11810 11811 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11812 struct bpf_reg_state *reg, argno_t argno, 11813 struct bpf_kfunc_call_arg_meta *meta) 11814 { 11815 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT, 11816 &meta->arg_rbtree_root.field); 11817 } 11818 11819 static int 11820 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11821 struct bpf_reg_state *reg, argno_t argno, 11822 struct bpf_kfunc_call_arg_meta *meta, 11823 enum btf_field_type head_field_type, 11824 enum btf_field_type node_field_type, 11825 struct btf_field **node_field) 11826 { 11827 const char *node_type_name; 11828 const struct btf_type *et, *t; 11829 struct btf_field *field; 11830 u32 node_off; 11831 11832 if (meta->btf != btf_vmlinux) { 11833 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11834 return -EFAULT; 11835 } 11836 11837 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11838 return -EFAULT; 11839 11840 node_type_name = btf_field_type_name(node_field_type); 11841 if (!tnum_is_const(reg->var_off)) { 11842 verbose(env, 11843 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11844 reg_arg_name(env, argno), node_type_name); 11845 return -EINVAL; 11846 } 11847 11848 node_off = reg->var_off.value; 11849 field = reg_find_field_offset(reg, node_off, node_field_type); 11850 if (!field) { 11851 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11852 return -EINVAL; 11853 } 11854 11855 field = *node_field; 11856 11857 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11858 t = btf_type_by_id(reg->btf, reg->btf_id); 11859 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11860 field->graph_root.value_btf_id, true, 11861 !type_is_alloc(reg->type))) { 11862 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11863 "in struct %s, but arg is at offset=%d in struct %s\n", 11864 btf_field_type_name(head_field_type), 11865 btf_field_type_name(node_field_type), 11866 field->graph_root.node_offset, 11867 btf_name_by_offset(field->graph_root.btf, et->name_off), 11868 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11869 return -EINVAL; 11870 } 11871 meta->arg_btf = reg->btf; 11872 meta->arg_btf_id = reg->btf_id; 11873 11874 if (node_off != field->graph_root.node_offset) { 11875 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11876 node_off, btf_field_type_name(node_field_type), 11877 field->graph_root.node_offset, 11878 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11879 return -EINVAL; 11880 } 11881 11882 return 0; 11883 } 11884 11885 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11886 struct bpf_reg_state *reg, argno_t argno, 11887 struct bpf_kfunc_call_arg_meta *meta) 11888 { 11889 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 11890 BPF_LIST_HEAD, BPF_LIST_NODE, 11891 &meta->arg_list_head.field); 11892 } 11893 11894 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11895 struct bpf_reg_state *reg, argno_t argno, 11896 struct bpf_kfunc_call_arg_meta *meta) 11897 { 11898 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 11899 BPF_RB_ROOT, BPF_RB_NODE, 11900 &meta->arg_rbtree_root.field); 11901 } 11902 11903 /* 11904 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11905 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11906 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11907 * them can only be attached to some specific hook points. 11908 */ 11909 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11910 { 11911 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11912 11913 switch (prog_type) { 11914 case BPF_PROG_TYPE_LSM: 11915 return true; 11916 case BPF_PROG_TYPE_TRACING: 11917 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11918 return true; 11919 fallthrough; 11920 default: 11921 return in_sleepable(env); 11922 } 11923 } 11924 11925 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11926 int insn_idx) 11927 { 11928 const char *func_name = meta->func_name, *ref_tname; 11929 struct bpf_func_state *caller = cur_func(env); 11930 struct bpf_reg_state *regs = cur_regs(env); 11931 const struct btf *btf = meta->btf; 11932 const struct btf_param *args; 11933 struct btf_record *rec; 11934 u32 i, nargs; 11935 int ret; 11936 11937 args = (const struct btf_param *)(meta->func_proto + 1); 11938 nargs = btf_type_vlen(meta->func_proto); 11939 if (nargs > MAX_BPF_FUNC_ARGS) { 11940 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11941 MAX_BPF_FUNC_ARGS); 11942 return -EINVAL; 11943 } 11944 if (nargs > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) { 11945 verbose(env, "JIT does not support kfunc %s() with %d args\n", 11946 func_name, nargs); 11947 return -ENOTSUPP; 11948 } 11949 11950 ret = check_outgoing_stack_args(env, caller, nargs); 11951 if (ret) 11952 return ret; 11953 11954 /* Check that BTF function arguments match actual types that the 11955 * verifier sees. 11956 */ 11957 for (i = 0; i < nargs; i++) { 11958 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 11959 const struct btf_type *t, *ref_t, *resolve_ret; 11960 enum bpf_arg_type arg_type = ARG_DONTCARE; 11961 argno_t argno = argno_from_arg(i + 1); 11962 int regno = reg_from_argno(argno); 11963 bool btf_id_fixed_off_ok = true; 11964 u32 ref_id, type_size; 11965 bool is_ret_buf_sz = false; 11966 int kf_arg_type; 11967 11968 if (is_kfunc_arg_prog_aux(btf, &args[i])) { 11969 /* Reject repeated use bpf_prog_aux */ 11970 if (meta->arg_prog) { 11971 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc"); 11972 return -EFAULT; 11973 } 11974 if (regno < 0) { 11975 verbose(env, "%s prog->aux cannot be a stack argument\n", 11976 reg_arg_name(env, argno)); 11977 return -EINVAL; 11978 } 11979 meta->arg_prog = true; 11980 cur_aux(env)->arg_prog = regno; 11981 continue; 11982 } 11983 11984 if (is_kfunc_arg_ignore(btf, &args[i]) || is_kfunc_arg_implicit(meta, i)) 11985 continue; 11986 11987 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11988 11989 if (btf_type_is_scalar(t)) { 11990 if (reg->type != SCALAR_VALUE) { 11991 verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno)); 11992 return -EINVAL; 11993 } 11994 11995 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11996 if (meta->arg_constant.found) { 11997 verifier_bug(env, "only one constant argument permitted"); 11998 return -EFAULT; 11999 } 12000 if (!tnum_is_const(reg->var_off)) { 12001 verbose(env, "%s must be a known constant\n", 12002 reg_arg_name(env, argno)); 12003 return -EINVAL; 12004 } 12005 if (regno >= 0) 12006 ret = mark_chain_precision(env, regno); 12007 else 12008 ret = mark_stack_arg_precision(env, i); 12009 if (ret < 0) 12010 return ret; 12011 meta->arg_constant.found = true; 12012 meta->arg_constant.value = reg->var_off.value; 12013 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 12014 meta->r0_rdonly = true; 12015 is_ret_buf_sz = true; 12016 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 12017 is_ret_buf_sz = true; 12018 } 12019 12020 if (is_ret_buf_sz) { 12021 if (meta->r0_size) { 12022 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 12023 return -EINVAL; 12024 } 12025 12026 if (!tnum_is_const(reg->var_off)) { 12027 verbose(env, "%s is not a const\n", 12028 reg_arg_name(env, argno)); 12029 return -EINVAL; 12030 } 12031 12032 meta->r0_size = reg->var_off.value; 12033 if (regno >= 0) 12034 ret = mark_chain_precision(env, regno); 12035 else 12036 ret = mark_stack_arg_precision(env, i); 12037 if (ret) 12038 return ret; 12039 } 12040 continue; 12041 } 12042 12043 if (!btf_type_is_ptr(t)) { 12044 verbose(env, "Unrecognized %s type %s\n", 12045 reg_arg_name(env, argno), btf_type_str(t)); 12046 return -EINVAL; 12047 } 12048 12049 if ((bpf_register_is_null(reg) || type_may_be_null(reg->type)) && 12050 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 12051 verbose(env, "Possibly NULL pointer passed to trusted %s\n", 12052 reg_arg_name(env, argno)); 12053 return -EACCES; 12054 } 12055 12056 if (regno == meta->release_regno && !is_kfunc_arg_dynptr(meta->btf, &args[i]) && 12057 !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) { 12058 verbose(env, "release kfunc %s expects referenced PTR_TO_BTF_ID passed to %s\n", 12059 func_name, reg_arg_name(env, argno)); 12060 return -EINVAL; 12061 } 12062 12063 if (reg_is_referenced(env, reg)) 12064 update_ref_obj(&meta->ref_obj, reg); 12065 12066 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 12067 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12068 12069 kf_arg_type = get_kfunc_ptr_arg_type(env, caller, regs, meta, t, ref_t, ref_tname, 12070 args, i, nargs, argno, reg); 12071 if (kf_arg_type < 0) 12072 return kf_arg_type; 12073 12074 switch (kf_arg_type) { 12075 case KF_ARG_PTR_TO_NULL: 12076 continue; 12077 case KF_ARG_PTR_TO_MAP: 12078 if (!reg->map_ptr) { 12079 verbose(env, "pointer in %s isn't map pointer\n", 12080 reg_arg_name(env, argno)); 12081 return -EINVAL; 12082 } 12083 if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 || 12084 reg->map_ptr->record->task_work_off >= 0)) { 12085 /* Use map_uid (which is unique id of inner map) to reject: 12086 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 12087 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 12088 * if (inner_map1 && inner_map2) { 12089 * wq = bpf_map_lookup_elem(inner_map1); 12090 * if (wq) 12091 * // mismatch would have been allowed 12092 * bpf_wq_init(wq, inner_map2); 12093 * } 12094 * 12095 * Comparing map_ptr is enough to distinguish normal and outer maps. 12096 */ 12097 if (meta->map.ptr != reg->map_ptr || 12098 meta->map.uid != reg->map_uid) { 12099 if (reg->map_ptr->record->task_work_off >= 0) { 12100 verbose(env, 12101 "bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n", 12102 meta->map.uid, reg->map_uid); 12103 return -EINVAL; 12104 } 12105 verbose(env, 12106 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 12107 meta->map.uid, reg->map_uid); 12108 return -EINVAL; 12109 } 12110 } 12111 meta->map.ptr = reg->map_ptr; 12112 meta->map.uid = reg->map_uid; 12113 fallthrough; 12114 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12115 case KF_ARG_PTR_TO_BTF_ID: 12116 if (!is_trusted_reg(env, reg)) { 12117 if (!is_kfunc_rcu(meta)) { 12118 verbose(env, "%s must be referenced or trusted\n", 12119 reg_arg_name(env, argno)); 12120 return -EINVAL; 12121 } 12122 if (!is_rcu_reg(reg)) { 12123 verbose(env, "%s must be a rcu pointer\n", 12124 reg_arg_name(env, argno)); 12125 return -EINVAL; 12126 } 12127 } 12128 fallthrough; 12129 case KF_ARG_PTR_TO_ITER: 12130 case KF_ARG_PTR_TO_LIST_HEAD: 12131 case KF_ARG_PTR_TO_LIST_NODE: 12132 case KF_ARG_PTR_TO_RB_ROOT: 12133 case KF_ARG_PTR_TO_RB_NODE: 12134 case KF_ARG_PTR_TO_MEM: 12135 case KF_ARG_PTR_TO_MEM_SIZE: 12136 case KF_ARG_PTR_TO_CALLBACK: 12137 case KF_ARG_PTR_TO_CONST_STR: 12138 case KF_ARG_PTR_TO_WORKQUEUE: 12139 case KF_ARG_PTR_TO_TIMER: 12140 case KF_ARG_PTR_TO_TASK_WORK: 12141 case KF_ARG_PTR_TO_IRQ_FLAG: 12142 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12143 break; 12144 case KF_ARG_PTR_TO_DYNPTR: 12145 arg_type = ARG_PTR_TO_DYNPTR; 12146 break; 12147 case KF_ARG_PTR_TO_CTX: 12148 arg_type = ARG_PTR_TO_CTX; 12149 break; 12150 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12151 arg_type = ARG_PTR_TO_BTF_ID; 12152 btf_id_fixed_off_ok = false; 12153 break; 12154 default: 12155 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type); 12156 return -EFAULT; 12157 } 12158 12159 if (regno == meta->release_regno) 12160 arg_type |= OBJ_RELEASE; 12161 ret = __check_func_arg_reg_off(env, reg, argno, arg_type, 12162 btf_id_fixed_off_ok); 12163 if (ret < 0) 12164 return ret; 12165 12166 switch (kf_arg_type) { 12167 case KF_ARG_PTR_TO_CTX: 12168 if (reg->type != PTR_TO_CTX) { 12169 verbose(env, "%s expected pointer to ctx, but got %s\n", 12170 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 12171 return -EINVAL; 12172 } 12173 12174 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12175 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 12176 if (ret < 0) 12177 return -EINVAL; 12178 meta->ret_btf_id = ret; 12179 } 12180 break; 12181 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12182 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 12183 if (!is_bpf_obj_drop_kfunc(meta->func_id)) { 12184 verbose(env, "%s expected for bpf_obj_drop()\n", 12185 reg_arg_name(env, argno)); 12186 return -EINVAL; 12187 } 12188 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 12189 if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) { 12190 verbose(env, "%s expected for bpf_percpu_obj_drop()\n", 12191 reg_arg_name(env, argno)); 12192 return -EINVAL; 12193 } 12194 } else { 12195 verbose(env, "%s expected pointer to allocated object\n", 12196 reg_arg_name(env, argno)); 12197 return -EINVAL; 12198 } 12199 if (!reg_is_referenced(env, reg)) { 12200 verbose(env, "allocated object must be referenced\n"); 12201 return -EINVAL; 12202 } 12203 if (meta->btf == btf_vmlinux) { 12204 meta->arg_btf = reg->btf; 12205 meta->arg_btf_id = reg->btf_id; 12206 } 12207 break; 12208 case KF_ARG_PTR_TO_DYNPTR: 12209 { 12210 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 12211 12212 if (is_kfunc_arg_uninit(btf, &args[i])) 12213 dynptr_arg_type |= MEM_UNINIT; 12214 12215 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 12216 dynptr_arg_type |= DYNPTR_TYPE_SKB; 12217 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 12218 dynptr_arg_type |= DYNPTR_TYPE_XDP; 12219 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) { 12220 dynptr_arg_type |= DYNPTR_TYPE_SKB_META; 12221 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 12222 dynptr_arg_type |= DYNPTR_TYPE_FILE; 12223 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) { 12224 dynptr_arg_type |= DYNPTR_TYPE_FILE | OBJ_RELEASE; 12225 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 12226 (dynptr_arg_type & MEM_UNINIT)) { 12227 enum bpf_dynptr_type parent_type = meta->dynptr.type; 12228 12229 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 12230 verifier_bug(env, "no dynptr type for parent of clone"); 12231 return -EFAULT; 12232 } 12233 12234 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12235 } 12236 12237 ret = process_dynptr_func(env, reg, argno, insn_idx, dynptr_arg_type, 12238 &meta->ref_obj, &meta->dynptr); 12239 if (ret < 0) 12240 return ret; 12241 break; 12242 } 12243 case KF_ARG_PTR_TO_ITER: 12244 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12245 if (!check_css_task_iter_allowlist(env)) { 12246 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12247 return -EINVAL; 12248 } 12249 } 12250 ret = process_iter_arg(env, reg, argno, insn_idx, meta); 12251 if (ret < 0) 12252 return ret; 12253 break; 12254 case KF_ARG_PTR_TO_LIST_HEAD: 12255 if (reg->type != PTR_TO_MAP_VALUE && 12256 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12257 verbose(env, "%s expected pointer to map value or allocated object\n", 12258 reg_arg_name(env, argno)); 12259 return -EINVAL; 12260 } 12261 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 12262 !reg_is_referenced(env, reg)) { 12263 verbose(env, "allocated object must be referenced\n"); 12264 return -EINVAL; 12265 } 12266 ret = process_kf_arg_ptr_to_list_head(env, reg, argno, meta); 12267 if (ret < 0) 12268 return ret; 12269 break; 12270 case KF_ARG_PTR_TO_RB_ROOT: 12271 if (reg->type != PTR_TO_MAP_VALUE && 12272 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12273 verbose(env, "%s expected pointer to map value or allocated object\n", 12274 reg_arg_name(env, argno)); 12275 return -EINVAL; 12276 } 12277 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 12278 !reg_is_referenced(env, reg)) { 12279 verbose(env, "allocated object must be referenced\n"); 12280 return -EINVAL; 12281 } 12282 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta); 12283 if (ret < 0) 12284 return ret; 12285 break; 12286 case KF_ARG_PTR_TO_LIST_NODE: 12287 if (is_kfunc_arg_nonown_allowed(btf, &args[i]) && 12288 type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg)) { 12289 /* Allow bpf_list_front/back return value for 12290 * __nonown_allowed list-node arguments. 12291 */ 12292 goto check_ok; 12293 } 12294 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12295 verbose(env, "%s expected pointer to allocated object\n", 12296 reg_arg_name(env, argno)); 12297 return -EINVAL; 12298 } 12299 if (!reg_is_referenced(env, reg)) { 12300 verbose(env, "allocated object must be referenced\n"); 12301 return -EINVAL; 12302 } 12303 check_ok: 12304 ret = process_kf_arg_ptr_to_list_node(env, reg, argno, meta); 12305 if (ret < 0) 12306 return ret; 12307 break; 12308 case KF_ARG_PTR_TO_RB_NODE: 12309 if (is_bpf_rbtree_add_kfunc(meta->func_id)) { 12310 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12311 verbose(env, "%s expected pointer to allocated object\n", 12312 reg_arg_name(env, argno)); 12313 return -EINVAL; 12314 } 12315 if (!reg_is_referenced(env, reg)) { 12316 verbose(env, "allocated object must be referenced\n"); 12317 return -EINVAL; 12318 } 12319 } else { 12320 if (!type_is_non_owning_ref(reg->type) && 12321 !reg_is_referenced(env, reg)) { 12322 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name); 12323 return -EINVAL; 12324 } 12325 if (in_rbtree_lock_required_cb(env)) { 12326 verbose(env, "%s not allowed in rbtree cb\n", func_name); 12327 return -EINVAL; 12328 } 12329 } 12330 12331 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta); 12332 if (ret < 0) 12333 return ret; 12334 break; 12335 case KF_ARG_PTR_TO_MAP: 12336 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12337 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12338 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12339 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12340 fallthrough; 12341 case KF_ARG_PTR_TO_BTF_ID: 12342 /* Only base_type is checked, further checks are done here */ 12343 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12344 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12345 !reg2btf_ids[base_type(reg->type)]) { 12346 verbose(env, "%s is %s ", reg_arg_name(env, argno), 12347 reg_type_str(env, reg->type)); 12348 verbose(env, "expected %s or socket\n", 12349 reg_type_str(env, base_type(reg->type) | 12350 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12351 return -EINVAL; 12352 } 12353 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i, argno); 12354 if (ret < 0) 12355 return ret; 12356 break; 12357 case KF_ARG_PTR_TO_MEM: 12358 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12359 if (IS_ERR(resolve_ret)) { 12360 verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n", 12361 reg_arg_name(env, argno), btf_type_str(ref_t), 12362 ref_tname, PTR_ERR(resolve_ret)); 12363 return -EINVAL; 12364 } 12365 ret = check_mem_reg(env, reg, argno, type_size); 12366 if (ret < 0) 12367 return ret; 12368 break; 12369 case KF_ARG_PTR_TO_MEM_SIZE: 12370 { 12371 struct bpf_reg_state *buff_reg = reg; 12372 const struct btf_param *buff_arg = &args[i]; 12373 struct bpf_reg_state *size_reg = get_func_arg_reg(caller, regs, i + 1); 12374 const struct btf_param *size_arg = &args[i + 1]; 12375 argno_t next_argno = argno_from_arg(i + 2); 12376 12377 if (!bpf_register_is_null(buff_reg) || !is_kfunc_arg_nullable(meta->btf, buff_arg)) { 12378 ret = check_kfunc_mem_size_reg(env, buff_reg, size_reg, 12379 argno, next_argno); 12380 if (ret < 0) { 12381 verbose(env, "%s and ", reg_arg_name(env, argno)); 12382 verbose(env, "%s memory, len pair leads to invalid memory access\n", 12383 reg_arg_name(env, next_argno)); 12384 return ret; 12385 } 12386 } 12387 12388 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12389 if (meta->arg_constant.found) { 12390 verifier_bug(env, "only one constant argument permitted"); 12391 return -EFAULT; 12392 } 12393 if (!tnum_is_const(size_reg->var_off)) { 12394 verbose(env, "%s must be a known constant\n", 12395 reg_arg_name(env, next_argno)); 12396 return -EINVAL; 12397 } 12398 meta->arg_constant.found = true; 12399 meta->arg_constant.value = size_reg->var_off.value; 12400 } 12401 12402 /* Skip next '__sz' or '__szk' argument */ 12403 i++; 12404 break; 12405 } 12406 case KF_ARG_PTR_TO_CALLBACK: 12407 if (reg->type != PTR_TO_FUNC) { 12408 verbose(env, "%s expected pointer to func\n", reg_arg_name(env, argno)); 12409 return -EINVAL; 12410 } 12411 meta->subprogno = reg->subprogno; 12412 break; 12413 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12414 if (!type_is_ptr_alloc_obj(reg->type)) { 12415 verbose(env, "%s is neither owning or non-owning ref\n", 12416 reg_arg_name(env, argno)); 12417 return -EINVAL; 12418 } 12419 if (!type_is_non_owning_ref(reg->type)) 12420 meta->arg_owning_ref = true; 12421 12422 rec = reg_btf_record(reg); 12423 if (!rec) { 12424 verifier_bug(env, "Couldn't find btf_record"); 12425 return -EFAULT; 12426 } 12427 12428 if (rec->refcount_off < 0) { 12429 verbose(env, "%s doesn't point to a type with bpf_refcount field\n", 12430 reg_arg_name(env, argno)); 12431 return -EINVAL; 12432 } 12433 12434 meta->arg_btf = reg->btf; 12435 meta->arg_btf_id = reg->btf_id; 12436 break; 12437 case KF_ARG_PTR_TO_CONST_STR: 12438 if (reg->type != PTR_TO_MAP_VALUE) { 12439 verbose(env, "%s doesn't point to a const string\n", 12440 reg_arg_name(env, argno)); 12441 return -EINVAL; 12442 } 12443 ret = check_arg_const_str(env, reg, argno); 12444 if (ret) 12445 return ret; 12446 break; 12447 case KF_ARG_PTR_TO_WORKQUEUE: 12448 if (reg->type != PTR_TO_MAP_VALUE) { 12449 verbose(env, "%s doesn't point to a map value\n", 12450 reg_arg_name(env, argno)); 12451 return -EINVAL; 12452 } 12453 ret = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map); 12454 if (ret < 0) 12455 return ret; 12456 break; 12457 case KF_ARG_PTR_TO_TIMER: 12458 if (reg->type != PTR_TO_MAP_VALUE) { 12459 verbose(env, "%s doesn't point to a map value\n", 12460 reg_arg_name(env, argno)); 12461 return -EINVAL; 12462 } 12463 ret = process_timer_kfunc(env, reg, argno, meta); 12464 if (ret < 0) 12465 return ret; 12466 break; 12467 case KF_ARG_PTR_TO_TASK_WORK: 12468 if (reg->type != PTR_TO_MAP_VALUE) { 12469 verbose(env, "%s doesn't point to a map value\n", 12470 reg_arg_name(env, argno)); 12471 return -EINVAL; 12472 } 12473 ret = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map); 12474 if (ret < 0) 12475 return ret; 12476 break; 12477 case KF_ARG_PTR_TO_IRQ_FLAG: 12478 if (reg->type != PTR_TO_STACK) { 12479 verbose(env, "%s doesn't point to an irq flag on stack\n", 12480 reg_arg_name(env, argno)); 12481 return -EINVAL; 12482 } 12483 ret = process_irq_flag(env, reg, argno, meta); 12484 if (ret < 0) 12485 return ret; 12486 break; 12487 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12488 { 12489 int flags = PROCESS_RES_LOCK; 12490 12491 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12492 verbose(env, "%s doesn't point to map value or allocated object\n", 12493 reg_arg_name(env, argno)); 12494 return -EINVAL; 12495 } 12496 12497 if (!is_bpf_res_spin_lock_kfunc(meta->func_id)) 12498 return -EFAULT; 12499 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 12500 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 12501 flags |= PROCESS_SPIN_LOCK; 12502 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 12503 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 12504 flags |= PROCESS_LOCK_IRQ; 12505 ret = process_spin_lock(env, reg, argno, flags); 12506 if (ret < 0) 12507 return ret; 12508 break; 12509 } 12510 } 12511 } 12512 12513 return 0; 12514 } 12515 12516 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, 12517 s32 func_id, 12518 s16 offset, 12519 struct bpf_kfunc_call_arg_meta *meta) 12520 { 12521 struct bpf_kfunc_meta kfunc; 12522 int err; 12523 12524 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 12525 if (err) 12526 return err; 12527 12528 memset(meta, 0, sizeof(*meta)); 12529 meta->btf = kfunc.btf; 12530 meta->func_id = kfunc.id; 12531 meta->func_proto = kfunc.proto; 12532 meta->func_name = kfunc.name; 12533 12534 if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog)) 12535 return -EACCES; 12536 12537 meta->kfunc_flags = *kfunc.flags; 12538 12539 /* Only support release referenced argument passed by register */ 12540 if (is_kfunc_release(meta)) 12541 meta->release_regno = BPF_REG_1; 12542 12543 return 0; 12544 } 12545 12546 /* 12547 * Determine how many bytes a helper accesses through a stack pointer at 12548 * argument position @arg (0-based, corresponding to R1-R5). 12549 * 12550 * Returns: 12551 * > 0 known read access size in bytes 12552 * 0 doesn't read anything directly 12553 * S64_MIN unknown 12554 * < 0 known write access of (-return) bytes 12555 */ 12556 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12557 int arg, int insn_idx) 12558 { 12559 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12560 const struct bpf_func_proto *fn; 12561 enum bpf_arg_type at; 12562 s64 size; 12563 12564 if (bpf_get_helper_proto(env, insn->imm, &fn) < 0) 12565 return S64_MIN; 12566 12567 at = fn->arg_type[arg]; 12568 12569 switch (base_type(at)) { 12570 case ARG_PTR_TO_MAP_KEY: 12571 case ARG_PTR_TO_MAP_VALUE: { 12572 bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY; 12573 u64 val; 12574 int i, map_reg; 12575 12576 for (i = 0; i < arg; i++) { 12577 if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR) 12578 break; 12579 } 12580 if (i >= arg) 12581 goto scan_all_maps; 12582 12583 map_reg = BPF_REG_1 + i; 12584 12585 if (!(aux->const_reg_map_mask & BIT(map_reg))) 12586 goto scan_all_maps; 12587 12588 i = aux->const_reg_vals[map_reg]; 12589 if (i < env->used_map_cnt) { 12590 size = is_key ? env->used_maps[i]->key_size 12591 : env->used_maps[i]->value_size; 12592 goto out; 12593 } 12594 scan_all_maps: 12595 /* 12596 * Map pointer is not known at this call site (e.g. different 12597 * maps on merged paths). Conservatively return the largest 12598 * key_size or value_size across all maps used by the program. 12599 */ 12600 val = 0; 12601 for (i = 0; i < env->used_map_cnt; i++) { 12602 struct bpf_map *map = env->used_maps[i]; 12603 u32 sz = is_key ? map->key_size : map->value_size; 12604 12605 if (sz > val) 12606 val = sz; 12607 if (map->inner_map_meta) { 12608 sz = is_key ? map->inner_map_meta->key_size 12609 : map->inner_map_meta->value_size; 12610 if (sz > val) 12611 val = sz; 12612 } 12613 } 12614 if (!val) 12615 return S64_MIN; 12616 size = val; 12617 goto out; 12618 } 12619 case ARG_PTR_TO_MEM: 12620 if (at & MEM_FIXED_SIZE) { 12621 size = fn->arg_size[arg]; 12622 goto out; 12623 } 12624 if (arg + 1 < ARRAY_SIZE(fn->arg_type) && 12625 arg_type_is_mem_size(fn->arg_type[arg + 1])) { 12626 int size_reg = BPF_REG_1 + arg + 1; 12627 12628 if (aux->const_reg_mask & BIT(size_reg)) { 12629 size = (s64)aux->const_reg_vals[size_reg]; 12630 goto out; 12631 } 12632 /* 12633 * Size arg is const on each path but differs across merged 12634 * paths. MAX_BPF_STACK is a safe upper bound for reads. 12635 */ 12636 if (at & MEM_UNINIT) 12637 return 0; 12638 return MAX_BPF_STACK; 12639 } 12640 return S64_MIN; 12641 case ARG_PTR_TO_DYNPTR: 12642 size = BPF_DYNPTR_SIZE; 12643 break; 12644 case ARG_PTR_TO_STACK: 12645 /* 12646 * Only used by bpf_calls_callback() helpers. The helper itself 12647 * doesn't access stack. The callback subprog does and it's 12648 * analyzed separately. 12649 */ 12650 return 0; 12651 default: 12652 return S64_MIN; 12653 } 12654 out: 12655 /* 12656 * MEM_UNINIT args are write-only: the helper initializes the 12657 * buffer without reading it. 12658 */ 12659 if (at & MEM_UNINIT) 12660 return -size; 12661 return size; 12662 } 12663 12664 /* 12665 * Determine how many bytes a kfunc accesses through a stack pointer at 12666 * argument position @arg (0-based, corresponding to R1-R5). 12667 * 12668 * Returns: 12669 * > 0 known read access size in bytes 12670 * 0 doesn't access memory through that argument (ex: not a pointer) 12671 * S64_MIN unknown 12672 * < 0 known write access of (-return) bytes 12673 */ 12674 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12675 int arg, int insn_idx) 12676 { 12677 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12678 struct bpf_kfunc_call_arg_meta meta; 12679 const struct btf_param *args; 12680 const struct btf_type *t, *ref_t; 12681 const struct btf *btf; 12682 u32 nargs, type_size; 12683 s64 size; 12684 12685 if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0) 12686 return S64_MIN; 12687 12688 btf = meta.btf; 12689 args = btf_params(meta.func_proto); 12690 nargs = btf_type_vlen(meta.func_proto); 12691 if (arg >= nargs) 12692 return 0; 12693 12694 t = btf_type_skip_modifiers(btf, args[arg].type, NULL); 12695 if (!btf_type_is_ptr(t)) 12696 return 0; 12697 12698 /* dynptr: fixed 16-byte on-stack representation */ 12699 if (is_kfunc_arg_dynptr(btf, &args[arg])) { 12700 size = BPF_DYNPTR_SIZE; 12701 goto out; 12702 } 12703 12704 /* ptr + __sz/__szk pair: size is in the next register */ 12705 if (arg + 1 < nargs && 12706 (btf_param_match_suffix(btf, &args[arg + 1], "__sz") || 12707 btf_param_match_suffix(btf, &args[arg + 1], "__szk"))) { 12708 int size_reg = BPF_REG_1 + arg + 1; 12709 12710 if (aux->const_reg_mask & BIT(size_reg)) { 12711 size = (s64)aux->const_reg_vals[size_reg]; 12712 goto out; 12713 } 12714 return MAX_BPF_STACK; 12715 } 12716 12717 /* fixed-size pointed-to type: resolve via BTF */ 12718 ref_t = btf_type_skip_modifiers(btf, t->type, NULL); 12719 if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) { 12720 size = type_size; 12721 goto out; 12722 } 12723 12724 return S64_MIN; 12725 out: 12726 /* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */ 12727 if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW) 12728 return -size; 12729 if (is_kfunc_arg_uninit(btf, &args[arg])) 12730 return -size; 12731 return size; 12732 } 12733 12734 /* check special kfuncs and return: 12735 * 1 - not fall-through to 'else' branch, continue verification 12736 * 0 - fall-through to 'else' branch 12737 * < 0 - not fall-through to 'else' branch, return error 12738 */ 12739 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 12740 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 12741 const struct btf_type *ptr_type, struct btf *desc_btf) 12742 { 12743 const struct btf_type *ret_t; 12744 int err = 0; 12745 12746 if (meta->btf != btf_vmlinux) 12747 return 0; 12748 12749 if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12750 struct btf_struct_meta *struct_meta; 12751 struct btf *ret_btf; 12752 u32 ret_btf_id; 12753 12754 if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set) 12755 return -ENOMEM; 12756 12757 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 12758 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12759 return -EINVAL; 12760 } 12761 12762 ret_btf = env->prog->aux->btf; 12763 ret_btf_id = meta->arg_constant.value; 12764 12765 /* This may be NULL due to user not supplying a BTF */ 12766 if (!ret_btf) { 12767 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12768 return -EINVAL; 12769 } 12770 12771 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12772 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12773 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12774 return -EINVAL; 12775 } 12776 12777 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12778 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12779 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12780 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12781 return -EINVAL; 12782 } 12783 12784 if (!bpf_global_percpu_ma_set) { 12785 mutex_lock(&bpf_percpu_ma_lock); 12786 if (!bpf_global_percpu_ma_set) { 12787 /* Charge memory allocated with bpf_global_percpu_ma to 12788 * root memcg. The obj_cgroup for root memcg is NULL. 12789 */ 12790 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12791 if (!err) 12792 bpf_global_percpu_ma_set = true; 12793 } 12794 mutex_unlock(&bpf_percpu_ma_lock); 12795 if (err) 12796 return err; 12797 } 12798 12799 mutex_lock(&bpf_percpu_ma_lock); 12800 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12801 mutex_unlock(&bpf_percpu_ma_lock); 12802 if (err) 12803 return err; 12804 } 12805 12806 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12807 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12808 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12809 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12810 return -EINVAL; 12811 } 12812 12813 if (struct_meta) { 12814 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12815 return -EINVAL; 12816 } 12817 } 12818 12819 mark_reg_known_zero(env, regs, BPF_REG_0); 12820 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12821 regs[BPF_REG_0].btf = ret_btf; 12822 regs[BPF_REG_0].btf_id = ret_btf_id; 12823 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) 12824 regs[BPF_REG_0].type |= MEM_PERCPU; 12825 12826 insn_aux->obj_new_size = ret_t->size; 12827 insn_aux->kptr_struct_meta = struct_meta; 12828 } else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) { 12829 mark_reg_known_zero(env, regs, BPF_REG_0); 12830 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12831 regs[BPF_REG_0].btf = meta->arg_btf; 12832 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 12833 12834 insn_aux->kptr_struct_meta = 12835 btf_find_struct_meta(meta->arg_btf, 12836 meta->arg_btf_id); 12837 } else if (is_list_node_type(ptr_type)) { 12838 struct btf_field *field = meta->arg_list_head.field; 12839 12840 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12841 } else if (is_rbtree_node_type(ptr_type)) { 12842 struct btf_field *field = meta->arg_rbtree_root.field; 12843 12844 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12845 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12846 mark_reg_known_zero(env, regs, BPF_REG_0); 12847 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12848 regs[BPF_REG_0].btf = desc_btf; 12849 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 12850 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12851 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 12852 if (!ret_t) { 12853 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n", 12854 meta->arg_constant.value); 12855 return -EINVAL; 12856 } else if (btf_type_is_struct(ret_t)) { 12857 mark_reg_known_zero(env, regs, BPF_REG_0); 12858 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12859 regs[BPF_REG_0].btf = desc_btf; 12860 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 12861 } else if (btf_type_is_void(ret_t)) { 12862 mark_reg_known_zero(env, regs, BPF_REG_0); 12863 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED; 12864 regs[BPF_REG_0].mem_size = 0; 12865 } else { 12866 verbose(env, 12867 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n"); 12868 return -EINVAL; 12869 } 12870 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12871 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12872 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type); 12873 12874 mark_reg_known_zero(env, regs, BPF_REG_0); 12875 12876 if (!meta->arg_constant.found) { 12877 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size"); 12878 return -EFAULT; 12879 } 12880 12881 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 12882 12883 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12884 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12885 12886 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12887 regs[BPF_REG_0].type |= MEM_RDONLY; 12888 } else { 12889 /* this will set env->seen_direct_write to true */ 12890 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12891 verbose(env, "the prog does not allow writes to packet data\n"); 12892 return -EINVAL; 12893 } 12894 } 12895 12896 if (!meta->dynptr.id) { 12897 verifier_bug(env, "no dynptr id"); 12898 return -EFAULT; 12899 } 12900 regs[BPF_REG_0].parent_id = meta->dynptr.id; 12901 } else { 12902 return 0; 12903 } 12904 12905 return 1; 12906 } 12907 12908 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12909 12910 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12911 int *insn_idx_p) 12912 { 12913 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12914 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12915 struct bpf_reg_state *regs = cur_regs(env); 12916 const char *func_name, *ptr_type_name; 12917 const struct btf_type *t, *ptr_type; 12918 struct bpf_kfunc_call_arg_meta meta; 12919 struct bpf_insn_aux_data *insn_aux; 12920 int err, insn_idx = *insn_idx_p; 12921 const struct btf_param *args; 12922 u32 i, nargs, ptr_type_id; 12923 struct btf *desc_btf; 12924 int id; 12925 12926 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12927 if (!insn->imm) 12928 return 0; 12929 12930 err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta); 12931 if (err == -EACCES && meta.func_name) 12932 verbose(env, "calling kernel function %s is not allowed\n", meta.func_name); 12933 if (err) 12934 return err; 12935 desc_btf = meta.btf; 12936 func_name = meta.func_name; 12937 insn_aux = &env->insn_aux_data[insn_idx]; 12938 12939 insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta); 12940 12941 if (!insn->off && 12942 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 12943 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 12944 struct bpf_verifier_state *branch; 12945 struct bpf_reg_state *regs; 12946 12947 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 12948 if (IS_ERR(branch)) { 12949 verbose(env, "failed to push state for failed lock acquisition\n"); 12950 return PTR_ERR(branch); 12951 } 12952 12953 regs = branch->frame[branch->curframe]->regs; 12954 12955 /* Clear r0-r5 registers in forked state */ 12956 for (i = 0; i < CALLER_SAVED_REGS; i++) 12957 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 12958 12959 mark_reg_unknown(env, regs, BPF_REG_0); 12960 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 12961 if (err) { 12962 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 12963 return err; 12964 } 12965 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32)); 12966 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 12967 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 12968 return -EFAULT; 12969 } 12970 12971 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12972 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12973 return -EACCES; 12974 } 12975 12976 sleepable = bpf_is_kfunc_sleepable(&meta); 12977 if (sleepable && !in_sleepable(env)) { 12978 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12979 return -EACCES; 12980 } 12981 12982 /* Track non-sleepable context for kfuncs, same as for helpers. */ 12983 if (!in_sleepable_context(env)) 12984 insn_aux->non_sleepable = true; 12985 12986 /* Check the arguments */ 12987 err = check_kfunc_args(env, &meta, insn_idx); 12988 if (err < 0) 12989 return err; 12990 12991 if ((is_bpf_obj_drop_kfunc(meta.func_id) || 12992 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (is_tracing_prog_type(prog_type) || 12993 /* is_tracing_prog_type() for now doesn't cover non-iterator tracing progs. */ 12994 (prog_type == BPF_PROG_TYPE_TRACING && env->prog->expected_attach_type != BPF_TRACE_ITER 12995 && !env->prog->sleepable))) { 12996 struct btf_struct_meta *struct_meta; 12997 12998 struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12999 if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) { 13000 verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n", 13001 func_name); 13002 return -EINVAL; 13003 } 13004 } 13005 13006 if (is_bpf_rbtree_add_kfunc(meta.func_id)) { 13007 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13008 set_rbtree_add_callback_state); 13009 if (err) { 13010 verbose(env, "kfunc %s#%d failed callback verification\n", 13011 func_name, meta.func_id); 13012 return err; 13013 } 13014 } 13015 13016 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 13017 meta.r0_size = sizeof(u64); 13018 meta.r0_rdonly = false; 13019 } 13020 13021 if (is_bpf_wq_set_callback_kfunc(meta.func_id)) { 13022 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13023 set_timer_callback_state); 13024 if (err) { 13025 verbose(env, "kfunc %s#%d failed callback verification\n", 13026 func_name, meta.func_id); 13027 return err; 13028 } 13029 } 13030 13031 if (is_task_work_add_kfunc(meta.func_id)) { 13032 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13033 set_task_work_schedule_callback_state); 13034 if (err) { 13035 verbose(env, "kfunc %s#%d failed callback verification\n", 13036 func_name, meta.func_id); 13037 return err; 13038 } 13039 } 13040 13041 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 13042 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 13043 13044 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 13045 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 13046 13047 if (rcu_lock) { 13048 env->cur_state->active_rcu_locks++; 13049 } else if (rcu_unlock) { 13050 if (env->cur_state->active_rcu_locks == 0) { 13051 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 13052 return -EINVAL; 13053 } 13054 if (--env->cur_state->active_rcu_locks == 0) 13055 invalidate_rcu_protected_refs(env); 13056 } else if (preempt_disable) { 13057 env->cur_state->active_preempt_locks++; 13058 } else if (preempt_enable) { 13059 if (env->cur_state->active_preempt_locks == 0) { 13060 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 13061 return -EINVAL; 13062 } 13063 env->cur_state->active_preempt_locks--; 13064 } 13065 13066 if (sleepable && !in_sleepable_context(env)) { 13067 verbose(env, "kernel func %s is sleepable within %s\n", 13068 func_name, non_sleepable_context_description(env)); 13069 return -EACCES; 13070 } 13071 13072 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 13073 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 13074 return -EACCES; 13075 } 13076 13077 if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) { 13078 verbose(env, "kernel func %s requires RCU critical section protection\n", func_name); 13079 return -EACCES; 13080 } 13081 13082 /* In case of release function, we get register number of refcounted 13083 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 13084 */ 13085 if (meta.release_regno) { 13086 err = release_reg(env, ®s[meta.release_regno], false, !!meta.dynptr.id); 13087 if (err) 13088 return err; 13089 } 13090 13091 if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) { 13092 id = regs[BPF_REG_2].id; 13093 insn_aux->insert_off = regs[BPF_REG_2].var_off.value; 13094 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13095 ref_convert_owning_non_owning(env, id); 13096 } 13097 13098 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 13099 if (!bpf_jit_supports_exceptions()) { 13100 verbose(env, "JIT does not support calling kfunc %s#%d\n", 13101 func_name, meta.func_id); 13102 return -ENOTSUPP; 13103 } 13104 env->seen_exception = true; 13105 13106 /* In the case of the default callback, the cookie value passed 13107 * to bpf_throw becomes the return value of the program. 13108 */ 13109 if (!env->exception_callback_subprog) { 13110 err = check_return_code(env, BPF_REG_1, "R1"); 13111 if (err < 0) 13112 return err; 13113 } 13114 } 13115 13116 for (i = 0; i < CALLER_SAVED_REGS; i++) { 13117 u32 regno = caller_saved[i]; 13118 13119 bpf_mark_reg_not_init(env, ®s[regno]); 13120 regs[regno].subreg_def = DEF_NOT_SUBREG; 13121 } 13122 invalidate_outgoing_stack_args(env, cur_func(env)); 13123 13124 /* Check return type */ 13125 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13126 13127 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13128 if (meta.btf != btf_vmlinux || 13129 (!is_bpf_obj_new_kfunc(meta.func_id) && 13130 !is_bpf_percpu_obj_new_kfunc(meta.func_id) && 13131 !is_bpf_refcount_acquire_kfunc(meta.func_id))) { 13132 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13133 return -EINVAL; 13134 } 13135 } 13136 13137 if (btf_type_is_scalar(t)) { 13138 mark_reg_unknown(env, regs, BPF_REG_0); 13139 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13140 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13141 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 13142 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 13143 } else if (btf_type_is_ptr(t)) { 13144 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 13145 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 13146 if (err) { 13147 if (err < 0) 13148 return err; 13149 } else if (btf_type_is_void(ptr_type)) { 13150 /* kfunc returning 'void *' is equivalent to returning scalar */ 13151 mark_reg_unknown(env, regs, BPF_REG_0); 13152 } else if (!__btf_type_is_struct(ptr_type)) { 13153 if (!meta.r0_size) { 13154 __u32 sz; 13155 13156 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 13157 meta.r0_size = sz; 13158 meta.r0_rdonly = true; 13159 } 13160 } 13161 if (!meta.r0_size) { 13162 ptr_type_name = btf_name_by_offset(desc_btf, 13163 ptr_type->name_off); 13164 verbose(env, 13165 "kernel function %s returns pointer type %s %s is not supported\n", 13166 func_name, 13167 btf_type_str(ptr_type), 13168 ptr_type_name); 13169 return -EINVAL; 13170 } 13171 13172 mark_reg_known_zero(env, regs, BPF_REG_0); 13173 regs[BPF_REG_0].type = PTR_TO_MEM; 13174 regs[BPF_REG_0].mem_size = meta.r0_size; 13175 13176 if (meta.r0_rdonly) 13177 regs[BPF_REG_0].type |= MEM_RDONLY; 13178 13179 /* Ensures we don't access the memory after a release_reference() */ 13180 if (meta.ref_obj.id) { 13181 err = validate_ref_obj(env, &meta.ref_obj); 13182 if (err) 13183 return err; 13184 regs[BPF_REG_0].parent_id = meta.ref_obj.id; 13185 } 13186 13187 if (is_kfunc_rcu_protected(&meta)) 13188 regs[BPF_REG_0].type |= MEM_RCU; 13189 } else { 13190 enum bpf_reg_type type = PTR_TO_BTF_ID; 13191 13192 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 13193 type |= PTR_UNTRUSTED; 13194 else if (is_kfunc_rcu_protected(&meta) || 13195 (bpf_is_iter_next_kfunc(&meta) && 13196 (get_iter_from_state(env->cur_state, &meta) 13197 ->type & MEM_RCU))) { 13198 /* 13199 * If the iterator's constructor (the _new 13200 * function e.g., bpf_iter_task_new) has been 13201 * annotated with BPF kfunc flag 13202 * KF_RCU_PROTECTED and was called within a RCU 13203 * read-side critical section, also propagate 13204 * the MEM_RCU flag to the pointer returned from 13205 * the iterator's next function (e.g., 13206 * bpf_iter_task_next). 13207 */ 13208 type |= MEM_RCU; 13209 } else { 13210 /* 13211 * Any PTR_TO_BTF_ID that is returned from a BPF 13212 * kfunc should by default be treated as 13213 * implicitly trusted. 13214 */ 13215 type |= PTR_TRUSTED; 13216 } 13217 13218 mark_reg_known_zero(env, regs, BPF_REG_0); 13219 regs[BPF_REG_0].btf = desc_btf; 13220 regs[BPF_REG_0].type = type; 13221 regs[BPF_REG_0].btf_id = ptr_type_id; 13222 } 13223 13224 if (is_kfunc_ret_null(&meta)) { 13225 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 13226 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 13227 regs[BPF_REG_0].id = ++env->id_gen; 13228 } 13229 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 13230 if (is_kfunc_acquire(&meta)) { 13231 id = acquire_reference(env, insn_idx, 0); 13232 if (id < 0) 13233 return id; 13234 regs[BPF_REG_0].id = id; 13235 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 13236 ref_set_non_owning(env, ®s[BPF_REG_0]); 13237 } 13238 13239 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 13240 regs[BPF_REG_0].id = ++env->id_gen; 13241 } else if (btf_type_is_void(t)) { 13242 if (meta.btf == btf_vmlinux) { 13243 if (is_bpf_obj_drop_kfunc(meta.func_id) || 13244 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) { 13245 insn_aux->kptr_struct_meta = 13246 btf_find_struct_meta(meta.arg_btf, 13247 meta.arg_btf_id); 13248 } 13249 } 13250 } 13251 13252 if (bpf_is_kfunc_pkt_changing(&meta)) 13253 clear_all_pkt_pointers(env); 13254 13255 nargs = btf_type_vlen(meta.func_proto); 13256 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 13257 struct bpf_func_state *caller = cur_func(env); 13258 struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno]; 13259 u16 out_stack_arg_cnt = nargs - MAX_BPF_FUNC_REG_ARGS; 13260 u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt; 13261 13262 if (stack_arg_cnt > caller_info->stack_arg_cnt) 13263 caller_info->stack_arg_cnt = stack_arg_cnt; 13264 } 13265 13266 args = (const struct btf_param *)(meta.func_proto + 1); 13267 for (i = 0; i < min_t(int, nargs, MAX_BPF_FUNC_REG_ARGS); i++) { 13268 u32 regno = i + 1; 13269 13270 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 13271 if (btf_type_is_ptr(t)) 13272 mark_btf_func_reg_size(env, regno, sizeof(void *)); 13273 else 13274 /* scalar. ensured by check_kfunc_args() */ 13275 mark_btf_func_reg_size(env, regno, t->size); 13276 } 13277 13278 if (bpf_is_iter_next_kfunc(&meta)) { 13279 err = process_iter_next_call(env, insn_idx, &meta); 13280 if (err) 13281 return err; 13282 } 13283 13284 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 13285 env->prog->call_session_cookie = true; 13286 13287 if (bpf_is_throw_kfunc(insn)) 13288 return process_bpf_exit_full(env, NULL, true); 13289 13290 return 0; 13291 } 13292 13293 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env, 13294 const struct bpf_reg_state *reg, 13295 enum bpf_reg_type type) 13296 { 13297 bool known = tnum_is_const(reg->var_off); 13298 s64 val = reg->var_off.value; 13299 s64 smin = reg_smin(reg); 13300 13301 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13302 verbose(env, "math between %s pointer and %lld is not allowed\n", 13303 reg_type_str(env, type), val); 13304 return false; 13305 } 13306 13307 if (smin == S64_MIN) { 13308 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 13309 reg_type_str(env, type)); 13310 return false; 13311 } 13312 13313 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13314 verbose(env, "value %lld makes %s pointer be out of bounds\n", 13315 smin, reg_type_str(env, type)); 13316 return false; 13317 } 13318 13319 return true; 13320 } 13321 13322 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env, 13323 const struct bpf_reg_state *reg, 13324 enum bpf_reg_type type) 13325 { 13326 bool known = tnum_is_const(reg->var_off); 13327 s64 val = reg->var_off.value; 13328 s64 smin = reg_smin(reg); 13329 13330 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13331 verbose(env, "%s pointer offset %lld is not allowed\n", 13332 reg_type_str(env, type), val); 13333 return false; 13334 } 13335 13336 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13337 verbose(env, "%s pointer offset %lld is not allowed\n", 13338 reg_type_str(env, type), smin); 13339 return false; 13340 } 13341 13342 return true; 13343 } 13344 13345 enum { 13346 REASON_BOUNDS = -1, 13347 REASON_TYPE = -2, 13348 REASON_PATHS = -3, 13349 REASON_LIMIT = -4, 13350 REASON_STACK = -5, 13351 }; 13352 13353 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 13354 u32 *alu_limit, bool mask_to_left) 13355 { 13356 u32 max = 0, ptr_limit = 0; 13357 13358 switch (ptr_reg->type) { 13359 case PTR_TO_STACK: 13360 /* Offset 0 is out-of-bounds, but acceptable start for the 13361 * left direction, see BPF_REG_FP. Also, unknown scalar 13362 * offset where we would need to deal with min/max bounds is 13363 * currently prohibited for unprivileged. 13364 */ 13365 max = MAX_BPF_STACK + mask_to_left; 13366 ptr_limit = -ptr_reg->var_off.value; 13367 break; 13368 case PTR_TO_MAP_VALUE: 13369 max = ptr_reg->map_ptr->value_size; 13370 ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg); 13371 break; 13372 default: 13373 return REASON_TYPE; 13374 } 13375 13376 if (ptr_limit >= max) 13377 return REASON_LIMIT; 13378 *alu_limit = ptr_limit; 13379 return 0; 13380 } 13381 13382 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 13383 const struct bpf_insn *insn) 13384 { 13385 return env->bypass_spec_v1 || 13386 BPF_SRC(insn->code) == BPF_K || 13387 cur_aux(env)->nospec; 13388 } 13389 13390 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 13391 u32 alu_state, u32 alu_limit) 13392 { 13393 /* If we arrived here from different branches with different 13394 * state or limits to sanitize, then this won't work. 13395 */ 13396 if (aux->alu_state && 13397 (aux->alu_state != alu_state || 13398 aux->alu_limit != alu_limit)) 13399 return REASON_PATHS; 13400 13401 /* Corresponding fixup done in do_misc_fixups(). */ 13402 aux->alu_state = alu_state; 13403 aux->alu_limit = alu_limit; 13404 return 0; 13405 } 13406 13407 static int sanitize_val_alu(struct bpf_verifier_env *env, 13408 struct bpf_insn *insn) 13409 { 13410 struct bpf_insn_aux_data *aux = cur_aux(env); 13411 13412 if (can_skip_alu_sanitation(env, insn)) 13413 return 0; 13414 13415 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13416 } 13417 13418 static bool sanitize_needed(u8 opcode) 13419 { 13420 return opcode == BPF_ADD || opcode == BPF_SUB; 13421 } 13422 13423 struct bpf_sanitize_info { 13424 struct bpf_insn_aux_data aux; 13425 bool mask_to_left; 13426 }; 13427 13428 static int sanitize_speculative_path(struct bpf_verifier_env *env, 13429 const struct bpf_insn *insn, 13430 u32 next_idx, u32 curr_idx) 13431 { 13432 struct bpf_verifier_state *branch; 13433 struct bpf_reg_state *regs; 13434 13435 branch = push_stack(env, next_idx, curr_idx, true); 13436 if (!IS_ERR(branch) && insn) { 13437 regs = branch->frame[branch->curframe]->regs; 13438 if (BPF_SRC(insn->code) == BPF_K) { 13439 mark_reg_unknown(env, regs, insn->dst_reg); 13440 } else if (BPF_SRC(insn->code) == BPF_X) { 13441 mark_reg_unknown(env, regs, insn->dst_reg); 13442 mark_reg_unknown(env, regs, insn->src_reg); 13443 } 13444 } 13445 return PTR_ERR_OR_ZERO(branch); 13446 } 13447 13448 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13449 struct bpf_insn *insn, 13450 const struct bpf_reg_state *ptr_reg, 13451 const struct bpf_reg_state *off_reg, 13452 struct bpf_reg_state *dst_reg, 13453 struct bpf_sanitize_info *info, 13454 const bool commit_window) 13455 { 13456 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13457 struct bpf_verifier_state *vstate = env->cur_state; 13458 bool off_is_imm = tnum_is_const(off_reg->var_off); 13459 bool off_is_neg = reg_smin(off_reg) < 0; 13460 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13461 u8 opcode = BPF_OP(insn->code); 13462 u32 alu_state, alu_limit; 13463 struct bpf_reg_state tmp; 13464 int err; 13465 13466 if (can_skip_alu_sanitation(env, insn)) 13467 return 0; 13468 13469 /* We already marked aux for masking from non-speculative 13470 * paths, thus we got here in the first place. We only care 13471 * to explore bad access from here. 13472 */ 13473 if (vstate->speculative) 13474 goto do_sim; 13475 13476 if (!commit_window) { 13477 if (!tnum_is_const(off_reg->var_off) && 13478 (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0)) 13479 return REASON_BOUNDS; 13480 13481 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13482 (opcode == BPF_SUB && !off_is_neg); 13483 } 13484 13485 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13486 if (err < 0) 13487 return err; 13488 13489 if (commit_window) { 13490 /* In commit phase we narrow the masking window based on 13491 * the observed pointer move after the simulated operation. 13492 */ 13493 alu_state = info->aux.alu_state; 13494 alu_limit = abs(info->aux.alu_limit - alu_limit); 13495 } else { 13496 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13497 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13498 alu_state |= ptr_is_dst_reg ? 13499 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13500 13501 /* Limit pruning on unknown scalars to enable deep search for 13502 * potential masking differences from other program paths. 13503 */ 13504 if (!off_is_imm) 13505 env->explore_alu_limits = true; 13506 } 13507 13508 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13509 if (err < 0) 13510 return err; 13511 do_sim: 13512 /* If we're in commit phase, we're done here given we already 13513 * pushed the truncated dst_reg into the speculative verification 13514 * stack. 13515 * 13516 * Also, when register is a known constant, we rewrite register-based 13517 * operation to immediate-based, and thus do not need masking (and as 13518 * a consequence, do not need to simulate the zero-truncation either). 13519 */ 13520 if (commit_window || off_is_imm) 13521 return 0; 13522 13523 /* Simulate and find potential out-of-bounds access under 13524 * speculative execution from truncation as a result of 13525 * masking when off was not within expected range. If off 13526 * sits in dst, then we temporarily need to move ptr there 13527 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13528 * for cases where we use K-based arithmetic in one direction 13529 * and truncated reg-based in the other in order to explore 13530 * bad access. 13531 */ 13532 if (!ptr_is_dst_reg) { 13533 tmp = *dst_reg; 13534 *dst_reg = *ptr_reg; 13535 } 13536 err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx); 13537 if (err < 0) 13538 return REASON_STACK; 13539 if (!ptr_is_dst_reg) 13540 *dst_reg = tmp; 13541 return 0; 13542 } 13543 13544 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13545 { 13546 struct bpf_verifier_state *vstate = env->cur_state; 13547 13548 /* If we simulate paths under speculation, we don't update the 13549 * insn as 'seen' such that when we verify unreachable paths in 13550 * the non-speculative domain, sanitize_dead_code() can still 13551 * rewrite/sanitize them. 13552 */ 13553 if (!vstate->speculative) 13554 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13555 } 13556 13557 static int sanitize_err(struct bpf_verifier_env *env, 13558 const struct bpf_insn *insn, int reason, 13559 const struct bpf_reg_state *off_reg, 13560 const struct bpf_reg_state *dst_reg) 13561 { 13562 static const char *err = "pointer arithmetic with it prohibited for !root"; 13563 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13564 u32 dst = insn->dst_reg, src = insn->src_reg; 13565 13566 switch (reason) { 13567 case REASON_BOUNDS: 13568 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13569 off_reg == dst_reg ? dst : src, err); 13570 break; 13571 case REASON_TYPE: 13572 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13573 off_reg == dst_reg ? src : dst, err); 13574 break; 13575 case REASON_PATHS: 13576 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13577 dst, op, err); 13578 break; 13579 case REASON_LIMIT: 13580 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13581 dst, op, err); 13582 break; 13583 case REASON_STACK: 13584 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13585 dst, err); 13586 return -ENOMEM; 13587 default: 13588 verifier_bug(env, "unknown reason (%d)", reason); 13589 break; 13590 } 13591 13592 return -EACCES; 13593 } 13594 13595 /* check that stack access falls within stack limits and that 'reg' doesn't 13596 * have a variable offset. 13597 * 13598 * Variable offset is prohibited for unprivileged mode for simplicity since it 13599 * requires corresponding support in Spectre masking for stack ALU. See also 13600 * retrieve_ptr_limit(). 13601 */ 13602 static int check_stack_access_for_ptr_arithmetic( 13603 struct bpf_verifier_env *env, 13604 int regno, 13605 const struct bpf_reg_state *reg, 13606 int off) 13607 { 13608 if (!tnum_is_const(reg->var_off)) { 13609 char tn_buf[48]; 13610 13611 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13612 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13613 regno, tn_buf, off); 13614 return -EACCES; 13615 } 13616 13617 if (off >= 0 || off < -MAX_BPF_STACK) { 13618 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13619 "prohibited for !root; off=%d\n", regno, off); 13620 return -EACCES; 13621 } 13622 13623 return 0; 13624 } 13625 13626 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13627 const struct bpf_insn *insn, 13628 struct bpf_reg_state *dst_reg) 13629 { 13630 u32 dst = insn->dst_reg; 13631 13632 /* For unprivileged we require that resulting offset must be in bounds 13633 * in order to be able to sanitize access later on. 13634 */ 13635 if (env->bypass_spec_v1) 13636 return 0; 13637 13638 switch (dst_reg->type) { 13639 case PTR_TO_STACK: 13640 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13641 dst_reg->var_off.value)) 13642 return -EACCES; 13643 break; 13644 case PTR_TO_MAP_VALUE: 13645 if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) { 13646 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13647 "prohibited for !root\n", dst); 13648 return -EACCES; 13649 } 13650 break; 13651 default: 13652 return -EOPNOTSUPP; 13653 } 13654 13655 return 0; 13656 } 13657 13658 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13659 * Caller should also handle BPF_MOV case separately. 13660 * If we return -EACCES, caller may want to try again treating pointer as a 13661 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13662 */ 13663 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13664 struct bpf_insn *insn, 13665 const struct bpf_reg_state *ptr_reg, 13666 const struct bpf_reg_state *off_reg) 13667 { 13668 struct bpf_verifier_state *vstate = env->cur_state; 13669 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13670 struct bpf_reg_state *regs = state->regs, *dst_reg; 13671 bool known = tnum_is_const(off_reg->var_off); 13672 s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg); 13673 u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg); 13674 struct bpf_sanitize_info info = {}; 13675 u8 opcode = BPF_OP(insn->code); 13676 u32 dst = insn->dst_reg; 13677 int ret, bounds_ret; 13678 13679 dst_reg = ®s[dst]; 13680 13681 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13682 smin_val > smax_val || umin_val > umax_val) { 13683 /* Taint dst register if offset had invalid bounds derived from 13684 * e.g. dead branches. 13685 */ 13686 __mark_reg_unknown(env, dst_reg); 13687 return 0; 13688 } 13689 13690 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13691 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13692 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13693 __mark_reg_unknown(env, dst_reg); 13694 return 0; 13695 } 13696 13697 verbose(env, 13698 "R%d 32-bit pointer arithmetic prohibited\n", 13699 dst); 13700 return -EACCES; 13701 } 13702 13703 if (ptr_reg->type & PTR_MAYBE_NULL) { 13704 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13705 dst, reg_type_str(env, ptr_reg->type)); 13706 return -EACCES; 13707 } 13708 13709 /* 13710 * Accesses to untrusted PTR_TO_MEM are done through probe 13711 * instructions, hence no need to track offsets. 13712 */ 13713 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 13714 return 0; 13715 13716 switch (base_type(ptr_reg->type)) { 13717 case PTR_TO_CTX: 13718 case PTR_TO_MAP_VALUE: 13719 case PTR_TO_MAP_KEY: 13720 case PTR_TO_STACK: 13721 case PTR_TO_PACKET_META: 13722 case PTR_TO_PACKET: 13723 case PTR_TO_TP_BUFFER: 13724 case PTR_TO_BTF_ID: 13725 case PTR_TO_MEM: 13726 case PTR_TO_BUF: 13727 case PTR_TO_FUNC: 13728 case CONST_PTR_TO_DYNPTR: 13729 break; 13730 case PTR_TO_FLOW_KEYS: 13731 if (known) 13732 break; 13733 fallthrough; 13734 case CONST_PTR_TO_MAP: 13735 /* smin_val represents the known value */ 13736 if (known && smin_val == 0 && opcode == BPF_ADD) 13737 break; 13738 fallthrough; 13739 default: 13740 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13741 dst, reg_type_str(env, ptr_reg->type)); 13742 return -EACCES; 13743 } 13744 13745 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13746 * The id may be overwritten later if we create a new variable offset. 13747 */ 13748 dst_reg->type = ptr_reg->type; 13749 dst_reg->id = ptr_reg->id; 13750 13751 if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type) || 13752 !check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) 13753 return -EINVAL; 13754 13755 /* pointer types do not carry 32-bit bounds at the moment. */ 13756 __mark_reg32_unbounded(dst_reg); 13757 13758 if (sanitize_needed(opcode)) { 13759 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13760 &info, false); 13761 if (ret < 0) 13762 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13763 } 13764 13765 switch (opcode) { 13766 case BPF_ADD: 13767 /* 13768 * dst_reg gets the pointer type and since some positive 13769 * integer value was added to the pointer, give it a new 'id' 13770 * if it's a PTR_TO_PACKET. 13771 * this creates a new 'base' pointer, off_reg (variable) gets 13772 * added into the variable offset, and we copy the fixed offset 13773 * from ptr_reg. 13774 */ 13775 dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64); 13776 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13777 dst_reg->raw = ptr_reg->raw; 13778 if (reg_is_pkt_pointer(ptr_reg)) { 13779 if (!known) 13780 dst_reg->id = ++env->id_gen; 13781 /* 13782 * Clear range for unknown addends since we can't know 13783 * where the pkt pointer ended up. Also clear AT_PKT_END / 13784 * BEYOND_PKT_END from prior comparison as any pointer 13785 * arithmetic invalidates them. 13786 */ 13787 if (!known || dst_reg->range < 0) 13788 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13789 } 13790 break; 13791 case BPF_SUB: 13792 if (dst_reg == off_reg) { 13793 /* scalar -= pointer. Creates an unknown scalar */ 13794 verbose(env, "R%d tried to subtract pointer from scalar\n", 13795 dst); 13796 return -EACCES; 13797 } 13798 /* We don't allow subtraction from FP, because (according to 13799 * test_verifier.c test "invalid fp arithmetic", JITs might not 13800 * be able to deal with it. 13801 */ 13802 if (ptr_reg->type == PTR_TO_STACK) { 13803 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13804 dst); 13805 return -EACCES; 13806 } 13807 dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64)); 13808 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13809 dst_reg->raw = ptr_reg->raw; 13810 if (reg_is_pkt_pointer(ptr_reg)) { 13811 if (!known) 13812 dst_reg->id = ++env->id_gen; 13813 /* 13814 * Clear range if the subtrahend may be negative since 13815 * pkt pointer could move past its bounds. A positive 13816 * subtrahend moves it backwards keeping positive range 13817 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from 13818 * prior comparison as arithmetic invalidates them. 13819 */ 13820 if ((!known && smin_val < 0) || dst_reg->range < 0) 13821 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13822 } 13823 break; 13824 case BPF_AND: 13825 case BPF_OR: 13826 case BPF_XOR: 13827 /* bitwise ops on pointers are troublesome, prohibit. */ 13828 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13829 dst, bpf_alu_string[opcode >> 4]); 13830 return -EACCES; 13831 default: 13832 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13833 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13834 dst, bpf_alu_string[opcode >> 4]); 13835 return -EACCES; 13836 } 13837 13838 if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) 13839 return -EINVAL; 13840 reg_bounds_sync(dst_reg); 13841 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 13842 if (bounds_ret == -EACCES) 13843 return bounds_ret; 13844 if (sanitize_needed(opcode)) { 13845 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13846 &info, true); 13847 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 13848 && !env->cur_state->speculative 13849 && bounds_ret 13850 && !ret, 13851 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 13852 return -EFAULT; 13853 } 13854 if (ret < 0) 13855 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13856 } 13857 13858 return 0; 13859 } 13860 13861 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13862 struct bpf_reg_state *src_reg) 13863 { 13864 dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32); 13865 } 13866 13867 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13868 struct bpf_reg_state *src_reg) 13869 { 13870 dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64); 13871 } 13872 13873 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13874 struct bpf_reg_state *src_reg) 13875 { 13876 dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32)); 13877 } 13878 13879 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13880 struct bpf_reg_state *src_reg) 13881 { 13882 dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64)); 13883 } 13884 13885 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13886 struct bpf_reg_state *src_reg) 13887 { 13888 s32 smin = reg_s32_min(dst_reg); 13889 s32 smax = reg_s32_max(dst_reg); 13890 u32 umin = reg_u32_min(dst_reg); 13891 u32 umax = reg_u32_max(dst_reg); 13892 s32 tmp_prod[4]; 13893 13894 if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) || 13895 check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) { 13896 /* Overflow possible, we know nothing */ 13897 umin = 0; 13898 umax = U32_MAX; 13899 } 13900 if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) || 13901 check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) || 13902 check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) || 13903 check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) { 13904 /* Overflow possible, we know nothing */ 13905 smin = S32_MIN; 13906 smax = S32_MAX; 13907 } else { 13908 smin = min_array(tmp_prod, 4); 13909 smax = max_array(tmp_prod, 4); 13910 } 13911 13912 dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax), 13913 cnum32_from_srange(smin, smax)); 13914 } 13915 13916 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13917 struct bpf_reg_state *src_reg) 13918 { 13919 s64 smin = reg_smin(dst_reg); 13920 s64 smax = reg_smax(dst_reg); 13921 u64 umin = reg_umin(dst_reg); 13922 u64 umax = reg_umax(dst_reg); 13923 s64 tmp_prod[4]; 13924 13925 if (check_mul_overflow(umax, reg_umax(src_reg), &umax) || 13926 check_mul_overflow(umin, reg_umin(src_reg), &umin)) { 13927 /* Overflow possible, we know nothing */ 13928 umin = 0; 13929 umax = U64_MAX; 13930 } 13931 if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) || 13932 check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) || 13933 check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) || 13934 check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) { 13935 /* Overflow possible, we know nothing */ 13936 smin = S64_MIN; 13937 smax = S64_MAX; 13938 } else { 13939 smin = min_array(tmp_prod, 4); 13940 smax = max_array(tmp_prod, 4); 13941 } 13942 13943 dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax), 13944 cnum64_from_srange(smin, smax)); 13945 } 13946 13947 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg, 13948 struct bpf_reg_state *src_reg) 13949 { 13950 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 13951 13952 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val, 13953 reg_u32_max(dst_reg) / src_val); 13954 13955 /* Reset other ranges/tnum to unbounded/unknown. */ 13956 reset_reg64_and_tnum(dst_reg); 13957 } 13958 13959 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg, 13960 struct bpf_reg_state *src_reg) 13961 { 13962 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 13963 13964 reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val), 13965 div64_u64(reg_umax(dst_reg), src_val)); 13966 13967 /* Reset other ranges/tnum to unbounded/unknown. */ 13968 reset_reg32_and_tnum(dst_reg); 13969 } 13970 13971 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg, 13972 struct bpf_reg_state *src_reg) 13973 { 13974 s32 smin = reg_s32_min(dst_reg); 13975 s32 smax = reg_s32_max(dst_reg); 13976 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 13977 s32 res1, res2; 13978 13979 /* BPF div specification: S32_MIN / -1 = S32_MIN */ 13980 if (smin == S32_MIN && src_val == -1) { 13981 /* 13982 * If the dividend range contains more than just S32_MIN, 13983 * we cannot precisely track the result, so it becomes unbounded. 13984 * e.g., [S32_MIN, S32_MIN+10]/(-1), 13985 * = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)] 13986 * = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX] 13987 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN. 13988 */ 13989 if (smax != S32_MIN) { 13990 smin = S32_MIN; 13991 smax = S32_MAX; 13992 } 13993 goto reset; 13994 } 13995 13996 res1 = smin / src_val; 13997 res2 = smax / src_val; 13998 smin = min(res1, res2); 13999 smax = max(res1, res2); 14000 14001 reset: 14002 reg_set_srange32(dst_reg, smin, smax); 14003 /* Reset other ranges/tnum to unbounded/unknown. */ 14004 reset_reg64_and_tnum(dst_reg); 14005 } 14006 14007 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg, 14008 struct bpf_reg_state *src_reg) 14009 { 14010 s64 smin = reg_smin(dst_reg); 14011 s64 smax = reg_smax(dst_reg); 14012 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14013 s64 res1, res2; 14014 14015 /* BPF div specification: S64_MIN / -1 = S64_MIN */ 14016 if (smin == S64_MIN && src_val == -1) { 14017 /* 14018 * If the dividend range contains more than just S64_MIN, 14019 * we cannot precisely track the result, so it becomes unbounded. 14020 * e.g., [S64_MIN, S64_MIN+10]/(-1), 14021 * = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)] 14022 * = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX] 14023 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN. 14024 */ 14025 if (smax != S64_MIN) { 14026 smin = S64_MIN; 14027 smax = S64_MAX; 14028 } 14029 goto reset; 14030 } 14031 14032 res1 = div64_s64(smin, src_val); 14033 res2 = div64_s64(smax, src_val); 14034 smin = min(res1, res2); 14035 smax = max(res1, res2); 14036 14037 reset: 14038 reg_set_srange64(dst_reg, smin, smax); 14039 /* Reset other ranges/tnum to unbounded/unknown. */ 14040 reset_reg32_and_tnum(dst_reg); 14041 } 14042 14043 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg, 14044 struct bpf_reg_state *src_reg) 14045 { 14046 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 14047 u32 res_max = src_val - 1; 14048 14049 /* 14050 * If dst_umax <= res_max, the result remains unchanged. 14051 * e.g., [2, 5] % 10 = [2, 5]. 14052 */ 14053 if (reg_u32_max(dst_reg) <= res_max) 14054 return; 14055 14056 reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max)); 14057 14058 /* Reset other ranges/tnum to unbounded/unknown. */ 14059 reset_reg64_and_tnum(dst_reg); 14060 } 14061 14062 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg, 14063 struct bpf_reg_state *src_reg) 14064 { 14065 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 14066 u64 res_max = src_val - 1; 14067 14068 /* 14069 * If dst_umax <= res_max, the result remains unchanged. 14070 * e.g., [2, 5] % 10 = [2, 5]. 14071 */ 14072 if (reg_umax(dst_reg) <= res_max) 14073 return; 14074 14075 reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max)); 14076 14077 /* Reset other ranges/tnum to unbounded/unknown. */ 14078 reset_reg32_and_tnum(dst_reg); 14079 } 14080 14081 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg, 14082 struct bpf_reg_state *src_reg) 14083 { 14084 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 14085 14086 /* 14087 * Safe absolute value calculation: 14088 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648. 14089 * Here use unsigned integer to avoid overflow. 14090 */ 14091 u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val; 14092 14093 /* 14094 * Calculate the maximum possible absolute value of the result. 14095 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives 14096 * 2147483647 (S32_MAX), which fits perfectly in s32. 14097 */ 14098 s32 res_max_abs = src_abs - 1; 14099 14100 /* 14101 * If the dividend is already within the result range, 14102 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14103 */ 14104 if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs) 14105 return; 14106 14107 /* General case: result has the same sign as the dividend. */ 14108 if (reg_s32_min(dst_reg) >= 0) { 14109 reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs)); 14110 } else if (reg_s32_max(dst_reg) <= 0) { 14111 reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0); 14112 } else { 14113 reg_set_srange32(dst_reg, -res_max_abs, res_max_abs); 14114 } 14115 14116 /* Reset other ranges/tnum to unbounded/unknown. */ 14117 reset_reg64_and_tnum(dst_reg); 14118 } 14119 14120 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg, 14121 struct bpf_reg_state *src_reg) 14122 { 14123 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14124 14125 /* 14126 * Safe absolute value calculation: 14127 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63. 14128 * Here use unsigned integer to avoid overflow. 14129 */ 14130 u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val; 14131 14132 /* 14133 * Calculate the maximum possible absolute value of the result. 14134 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives 14135 * 2^63 - 1 (S64_MAX), which fits perfectly in s64. 14136 */ 14137 s64 res_max_abs = src_abs - 1; 14138 14139 /* 14140 * If the dividend is already within the result range, 14141 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14142 */ 14143 if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs) 14144 return; 14145 14146 /* General case: result has the same sign as the dividend. */ 14147 if (reg_smin(dst_reg) >= 0) { 14148 reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs)); 14149 } else if (reg_smax(dst_reg) <= 0) { 14150 reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0); 14151 } else { 14152 reg_set_srange64(dst_reg, -res_max_abs, res_max_abs); 14153 } 14154 14155 /* Reset other ranges/tnum to unbounded/unknown. */ 14156 reset_reg32_and_tnum(dst_reg); 14157 } 14158 14159 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14160 struct bpf_reg_state *src_reg) 14161 { 14162 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14163 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14164 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14165 u32 umax_val = reg_u32_max(src_reg); 14166 14167 if (src_known && dst_known) { 14168 __mark_reg32_known(dst_reg, var32_off.value); 14169 return; 14170 } 14171 14172 /* We get our minimum from the var_off, since that's inherently 14173 * bitwise. Our maximum is the minimum of the operands' maxima. 14174 */ 14175 reg_set_urange32(dst_reg, 14176 var32_off.value, 14177 min(reg_u32_max(dst_reg), umax_val)); 14178 } 14179 14180 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14181 struct bpf_reg_state *src_reg) 14182 { 14183 bool src_known = tnum_is_const(src_reg->var_off); 14184 bool dst_known = tnum_is_const(dst_reg->var_off); 14185 u64 umax_val = reg_umax(src_reg); 14186 14187 if (src_known && dst_known) { 14188 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14189 return; 14190 } 14191 14192 /* We get our minimum from the var_off, since that's inherently 14193 * bitwise. Our maximum is the minimum of the operands' maxima. 14194 */ 14195 reg_set_urange64(dst_reg, 14196 dst_reg->var_off.value, 14197 min(reg_umax(dst_reg), umax_val)); 14198 14199 /* We may learn something more from the var_off */ 14200 __update_reg_bounds(dst_reg); 14201 } 14202 14203 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14204 struct bpf_reg_state *src_reg) 14205 { 14206 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14207 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14208 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14209 u32 umin_val = reg_u32_min(src_reg); 14210 14211 if (src_known && dst_known) { 14212 __mark_reg32_known(dst_reg, var32_off.value); 14213 return; 14214 } 14215 14216 /* We get our maximum from the var_off, and our minimum is the 14217 * maximum of the operands' minima 14218 */ 14219 reg_set_urange32(dst_reg, 14220 max(reg_u32_min(dst_reg), umin_val), 14221 var32_off.value | var32_off.mask); 14222 } 14223 14224 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14225 struct bpf_reg_state *src_reg) 14226 { 14227 bool src_known = tnum_is_const(src_reg->var_off); 14228 bool dst_known = tnum_is_const(dst_reg->var_off); 14229 u64 umin_val = reg_umin(src_reg); 14230 14231 if (src_known && dst_known) { 14232 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14233 return; 14234 } 14235 14236 /* We get our maximum from the var_off, and our minimum is the 14237 * maximum of the operands' minima 14238 */ 14239 reg_set_urange64(dst_reg, 14240 max(reg_umin(dst_reg), umin_val), 14241 dst_reg->var_off.value | dst_reg->var_off.mask); 14242 14243 /* We may learn something more from the var_off */ 14244 __update_reg_bounds(dst_reg); 14245 } 14246 14247 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 14248 struct bpf_reg_state *src_reg) 14249 { 14250 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14251 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14252 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14253 14254 if (src_known && dst_known) { 14255 __mark_reg32_known(dst_reg, var32_off.value); 14256 return; 14257 } 14258 14259 /* We get both minimum and maximum from the var32_off. */ 14260 reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask); 14261 } 14262 14263 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 14264 struct bpf_reg_state *src_reg) 14265 { 14266 bool src_known = tnum_is_const(src_reg->var_off); 14267 bool dst_known = tnum_is_const(dst_reg->var_off); 14268 14269 if (src_known && dst_known) { 14270 /* dst_reg->var_off.value has been updated earlier */ 14271 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14272 return; 14273 } 14274 14275 /* We get both minimum and maximum from the var_off. */ 14276 reg_set_urange64(dst_reg, 14277 dst_reg->var_off.value, 14278 dst_reg->var_off.value | dst_reg->var_off.mask); 14279 } 14280 14281 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14282 u64 umin_val, u64 umax_val) 14283 { 14284 /* If we might shift our top bit out, then we know nothing */ 14285 if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val)) 14286 reg_set_urange32(dst_reg, 0, U32_MAX); 14287 else 14288 /* We lose all sign bit information (except what we can pick 14289 * up from var_off) 14290 */ 14291 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val, 14292 reg_u32_max(dst_reg) << umax_val); 14293 } 14294 14295 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14296 struct bpf_reg_state *src_reg) 14297 { 14298 u32 umax_val = reg_u32_max(src_reg); 14299 u32 umin_val = reg_u32_min(src_reg); 14300 /* u32 alu operation will zext upper bits */ 14301 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14302 14303 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14304 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 14305 /* Not required but being careful mark reg64 bounds as unknown so 14306 * that we are forced to pick them up from tnum and zext later and 14307 * if some path skips this step we are still safe. 14308 */ 14309 __mark_reg64_unbounded(dst_reg); 14310 __update_reg32_bounds(dst_reg); 14311 } 14312 14313 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 14314 u64 umin_val, u64 umax_val) 14315 { 14316 struct cnum64 u, s; 14317 14318 /* Special case <<32 because it is a common compiler pattern to sign 14319 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct 14320 * because s32 bounds don't flip sign when shifting to the left by 14321 * 32bits. 14322 */ 14323 if (umin_val == 32 && umax_val == 32) 14324 s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32, 14325 (s64)reg_s32_max(dst_reg) << 32); 14326 else 14327 s = CNUM64_UNBOUNDED; 14328 14329 /* If we might shift our top bit out, then we know nothing */ 14330 if (reg_umax(dst_reg) > 1ULL << (63 - umax_val)) 14331 u = CNUM64_UNBOUNDED; 14332 else 14333 u = cnum64_from_urange(reg_umin(dst_reg) << umin_val, 14334 reg_umax(dst_reg) << umax_val); 14335 14336 dst_reg->r64 = cnum64_intersect(u, s); 14337 } 14338 14339 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 14340 struct bpf_reg_state *src_reg) 14341 { 14342 u64 umax_val = reg_umax(src_reg); 14343 u64 umin_val = reg_umin(src_reg); 14344 14345 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 14346 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 14347 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14348 14349 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 14350 /* We may learn something more from the var_off */ 14351 __update_reg_bounds(dst_reg); 14352 } 14353 14354 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 14355 struct bpf_reg_state *src_reg) 14356 { 14357 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14358 u32 umax_val = reg_u32_max(src_reg); 14359 u32 umin_val = reg_u32_min(src_reg); 14360 14361 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14362 * be negative, then either: 14363 * 1) src_reg might be zero, so the sign bit of the result is 14364 * unknown, so we lose our signed bounds 14365 * 2) it's known negative, thus the unsigned bounds capture the 14366 * signed bounds 14367 * 3) the signed bounds cross zero, so they tell us nothing 14368 * about the result 14369 * If the value in dst_reg is known nonnegative, then again the 14370 * unsigned bounds capture the signed bounds. 14371 * Thus, in all cases it suffices to blow away our signed bounds 14372 * and rely on inferring new ones from the unsigned bounds and 14373 * var_off of the result. 14374 */ 14375 14376 dst_reg->var_off = tnum_rshift(subreg, umin_val); 14377 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val, 14378 reg_u32_max(dst_reg) >> umin_val); 14379 14380 __mark_reg64_unbounded(dst_reg); 14381 __update_reg32_bounds(dst_reg); 14382 } 14383 14384 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 14385 struct bpf_reg_state *src_reg) 14386 { 14387 u64 umax_val = reg_umax(src_reg); 14388 u64 umin_val = reg_umin(src_reg); 14389 14390 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14391 * be negative, then either: 14392 * 1) src_reg might be zero, so the sign bit of the result is 14393 * unknown, so we lose our signed bounds 14394 * 2) it's known negative, thus the unsigned bounds capture the 14395 * signed bounds 14396 * 3) the signed bounds cross zero, so they tell us nothing 14397 * about the result 14398 * If the value in dst_reg is known nonnegative, then again the 14399 * unsigned bounds capture the signed bounds. 14400 * Thus, in all cases it suffices to blow away our signed bounds 14401 * and rely on inferring new ones from the unsigned bounds and 14402 * var_off of the result. 14403 */ 14404 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 14405 reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val, 14406 reg_umax(dst_reg) >> umin_val); 14407 14408 /* Its not easy to operate on alu32 bounds here because it depends 14409 * on bits being shifted in. Take easy way out and mark unbounded 14410 * so we can recalculate later from tnum. 14411 */ 14412 __mark_reg32_unbounded(dst_reg); 14413 __update_reg_bounds(dst_reg); 14414 } 14415 14416 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 14417 struct bpf_reg_state *src_reg) 14418 { 14419 u64 umin_val = reg_u32_min(src_reg); 14420 14421 /* Upon reaching here, src_known is true and 14422 * umax_val is equal to umin_val. 14423 * Blow away the dst_reg umin_value/umax_value and rely on 14424 * dst_reg var_off to refine the result. 14425 */ 14426 reg_set_srange32(dst_reg, 14427 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val), 14428 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val)); 14429 14430 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 14431 14432 __mark_reg64_unbounded(dst_reg); 14433 __update_reg32_bounds(dst_reg); 14434 } 14435 14436 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 14437 struct bpf_reg_state *src_reg) 14438 { 14439 u64 umin_val = reg_umin(src_reg); 14440 14441 /* Upon reaching here, src_known is true and umax_val is equal 14442 * to umin_val. 14443 */ 14444 reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val, 14445 reg_smax(dst_reg) >> umin_val); 14446 14447 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14448 14449 /* Its not easy to operate on alu32 bounds here because it depends 14450 * on bits being shifted in from upper 32-bits. Take easy way out 14451 * and mark unbounded so we can recalculate later from tnum. 14452 */ 14453 __mark_reg32_unbounded(dst_reg); 14454 __update_reg_bounds(dst_reg); 14455 } 14456 14457 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn) 14458 { 14459 /* 14460 * Byte swap operation - update var_off using tnum_bswap. 14461 * Three cases: 14462 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE) 14463 * unconditional swap 14464 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE) 14465 * swap on big-endian, truncation or no-op on little-endian 14466 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE) 14467 * swap on little-endian, truncation or no-op on big-endian 14468 */ 14469 14470 bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64; 14471 bool to_le = BPF_SRC(insn->code) == BPF_TO_LE; 14472 bool is_big_endian; 14473 #ifdef CONFIG_CPU_BIG_ENDIAN 14474 is_big_endian = true; 14475 #else 14476 is_big_endian = false; 14477 #endif 14478 /* Apply bswap if alu64 or switch between big-endian and little-endian machines */ 14479 bool need_bswap = alu64 || (to_le == is_big_endian); 14480 14481 /* 14482 * If the register is mutated, manually reset its scalar ID to break 14483 * any existing ties and avoid incorrect bounds propagation. 14484 */ 14485 if (need_bswap || insn->imm == 16 || insn->imm == 32) 14486 clear_scalar_id(dst_reg); 14487 14488 if (need_bswap) { 14489 if (insn->imm == 16) 14490 dst_reg->var_off = tnum_bswap16(dst_reg->var_off); 14491 else if (insn->imm == 32) 14492 dst_reg->var_off = tnum_bswap32(dst_reg->var_off); 14493 else if (insn->imm == 64) 14494 dst_reg->var_off = tnum_bswap64(dst_reg->var_off); 14495 /* 14496 * Byteswap scrambles the range, so we must reset bounds. 14497 * Bounds will be re-derived from the new tnum later. 14498 */ 14499 __mark_reg_unbounded(dst_reg); 14500 } 14501 /* For bswap16/32, truncate dst register to match the swapped size */ 14502 if (insn->imm == 16 || insn->imm == 32) 14503 coerce_reg_to_size(dst_reg, insn->imm / 8); 14504 } 14505 14506 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14507 const struct bpf_reg_state *src_reg) 14508 { 14509 bool src_is_const = false; 14510 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14511 14512 if (insn_bitness == 32) { 14513 if (tnum_subreg_is_const(src_reg->var_off) 14514 && reg_s32_min(src_reg) == reg_s32_max(src_reg) 14515 && reg_u32_min(src_reg) == reg_u32_max(src_reg)) 14516 src_is_const = true; 14517 } else { 14518 if (tnum_is_const(src_reg->var_off) 14519 && reg_smin(src_reg) == reg_smax(src_reg) 14520 && reg_umin(src_reg) == reg_umax(src_reg)) 14521 src_is_const = true; 14522 } 14523 14524 switch (BPF_OP(insn->code)) { 14525 case BPF_ADD: 14526 case BPF_SUB: 14527 case BPF_NEG: 14528 case BPF_AND: 14529 case BPF_XOR: 14530 case BPF_OR: 14531 case BPF_MUL: 14532 case BPF_END: 14533 return true; 14534 14535 /* 14536 * Division and modulo operators range is only safe to compute when the 14537 * divisor is a constant. 14538 */ 14539 case BPF_DIV: 14540 case BPF_MOD: 14541 return src_is_const; 14542 14543 /* Shift operators range is only computable if shift dimension operand 14544 * is a constant. Shifts greater than 31 or 63 are undefined. This 14545 * includes shifts by a negative number. 14546 */ 14547 case BPF_LSH: 14548 case BPF_RSH: 14549 case BPF_ARSH: 14550 return (src_is_const && reg_umax(src_reg) < insn_bitness); 14551 default: 14552 return false; 14553 } 14554 } 14555 14556 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn, 14557 struct bpf_reg_state *dst_reg) 14558 { 14559 struct bpf_verifier_state *branch; 14560 struct bpf_reg_state *regs; 14561 bool alu32; 14562 14563 if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0) 14564 alu32 = false; 14565 else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0) 14566 alu32 = true; 14567 else 14568 return 0; 14569 14570 branch = push_stack(env, env->insn_idx, env->insn_idx, false); 14571 if (IS_ERR(branch)) 14572 return PTR_ERR(branch); 14573 14574 regs = branch->frame[branch->curframe]->regs; 14575 if (alu32) { 14576 __mark_reg32_known(®s[insn->dst_reg], 0); 14577 __mark_reg32_known(dst_reg, -1ull); 14578 } else { 14579 __mark_reg_known(®s[insn->dst_reg], 0); 14580 __mark_reg_known(dst_reg, -1ull); 14581 } 14582 return 0; 14583 } 14584 14585 /* WARNING: This function does calculations on 64-bit values, but the actual 14586 * execution may occur on 32-bit values. Therefore, things like bitshifts 14587 * need extra checks in the 32-bit case. 14588 */ 14589 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14590 struct bpf_insn *insn, 14591 struct bpf_reg_state *dst_reg, 14592 struct bpf_reg_state src_reg) 14593 { 14594 u8 opcode = BPF_OP(insn->code); 14595 s16 off = insn->off; 14596 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14597 int ret; 14598 14599 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14600 __mark_reg_unknown(env, dst_reg); 14601 return 0; 14602 } 14603 14604 if (sanitize_needed(opcode)) { 14605 ret = sanitize_val_alu(env, insn); 14606 if (ret < 0) 14607 return sanitize_err(env, insn, ret, NULL, NULL); 14608 } 14609 14610 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14611 * There are two classes of instructions: The first class we track both 14612 * alu32 and alu64 sign/unsigned bounds independently this provides the 14613 * greatest amount of precision when alu operations are mixed with jmp32 14614 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14615 * and BPF_OR. This is possible because these ops have fairly easy to 14616 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14617 * See alu32 verifier tests for examples. The second class of 14618 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14619 * with regards to tracking sign/unsigned bounds because the bits may 14620 * cross subreg boundaries in the alu64 case. When this happens we mark 14621 * the reg unbounded in the subreg bound space and use the resulting 14622 * tnum to calculate an approximation of the sign/unsigned bounds. 14623 */ 14624 switch (opcode) { 14625 case BPF_ADD: 14626 scalar32_min_max_add(dst_reg, &src_reg); 14627 scalar_min_max_add(dst_reg, &src_reg); 14628 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14629 break; 14630 case BPF_SUB: 14631 scalar32_min_max_sub(dst_reg, &src_reg); 14632 scalar_min_max_sub(dst_reg, &src_reg); 14633 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14634 break; 14635 case BPF_NEG: 14636 env->fake_reg[0] = *dst_reg; 14637 __mark_reg_known(dst_reg, 0); 14638 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 14639 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 14640 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 14641 break; 14642 case BPF_MUL: 14643 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14644 scalar32_min_max_mul(dst_reg, &src_reg); 14645 scalar_min_max_mul(dst_reg, &src_reg); 14646 break; 14647 case BPF_DIV: 14648 /* BPF div specification: x / 0 = 0 */ 14649 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) { 14650 ___mark_reg_known(dst_reg, 0); 14651 break; 14652 } 14653 if (alu32) 14654 if (off == 1) 14655 scalar32_min_max_sdiv(dst_reg, &src_reg); 14656 else 14657 scalar32_min_max_udiv(dst_reg, &src_reg); 14658 else 14659 if (off == 1) 14660 scalar_min_max_sdiv(dst_reg, &src_reg); 14661 else 14662 scalar_min_max_udiv(dst_reg, &src_reg); 14663 break; 14664 case BPF_MOD: 14665 /* BPF mod specification: x % 0 = x */ 14666 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) 14667 break; 14668 if (alu32) 14669 if (off == 1) 14670 scalar32_min_max_smod(dst_reg, &src_reg); 14671 else 14672 scalar32_min_max_umod(dst_reg, &src_reg); 14673 else 14674 if (off == 1) 14675 scalar_min_max_smod(dst_reg, &src_reg); 14676 else 14677 scalar_min_max_umod(dst_reg, &src_reg); 14678 break; 14679 case BPF_AND: 14680 if (tnum_is_const(src_reg.var_off)) { 14681 ret = maybe_fork_scalars(env, insn, dst_reg); 14682 if (ret) 14683 return ret; 14684 } 14685 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14686 scalar32_min_max_and(dst_reg, &src_reg); 14687 scalar_min_max_and(dst_reg, &src_reg); 14688 break; 14689 case BPF_OR: 14690 if (tnum_is_const(src_reg.var_off)) { 14691 ret = maybe_fork_scalars(env, insn, dst_reg); 14692 if (ret) 14693 return ret; 14694 } 14695 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14696 scalar32_min_max_or(dst_reg, &src_reg); 14697 scalar_min_max_or(dst_reg, &src_reg); 14698 break; 14699 case BPF_XOR: 14700 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14701 scalar32_min_max_xor(dst_reg, &src_reg); 14702 scalar_min_max_xor(dst_reg, &src_reg); 14703 break; 14704 case BPF_LSH: 14705 if (alu32) 14706 scalar32_min_max_lsh(dst_reg, &src_reg); 14707 else 14708 scalar_min_max_lsh(dst_reg, &src_reg); 14709 break; 14710 case BPF_RSH: 14711 if (alu32) 14712 scalar32_min_max_rsh(dst_reg, &src_reg); 14713 else 14714 scalar_min_max_rsh(dst_reg, &src_reg); 14715 break; 14716 case BPF_ARSH: 14717 if (alu32) 14718 scalar32_min_max_arsh(dst_reg, &src_reg); 14719 else 14720 scalar_min_max_arsh(dst_reg, &src_reg); 14721 break; 14722 case BPF_END: 14723 scalar_byte_swap(dst_reg, insn); 14724 break; 14725 default: 14726 break; 14727 } 14728 14729 /* 14730 * ALU32 ops are zero extended into 64bit register. 14731 * 14732 * BPF_END is already handled inside the helper (truncation), 14733 * so skip zext here to avoid unexpected zero extension. 14734 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40 14735 * This is a 64bit byte swap operation with alu32==true, 14736 * but we should not zero extend the result. 14737 */ 14738 if (alu32 && opcode != BPF_END) 14739 zext_32_to_64(dst_reg); 14740 reg_bounds_sync(dst_reg); 14741 return 0; 14742 } 14743 14744 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14745 * and var_off. 14746 */ 14747 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14748 struct bpf_insn *insn) 14749 { 14750 struct bpf_verifier_state *vstate = env->cur_state; 14751 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14752 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14753 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14754 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14755 u8 opcode = BPF_OP(insn->code); 14756 int err; 14757 14758 dst_reg = ®s[insn->dst_reg]; 14759 if (BPF_SRC(insn->code) == BPF_X) 14760 src_reg = ®s[insn->src_reg]; 14761 else 14762 src_reg = NULL; 14763 14764 /* Case where at least one operand is an arena. */ 14765 if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) { 14766 struct bpf_insn_aux_data *aux = cur_aux(env); 14767 14768 if (dst_reg->type != PTR_TO_ARENA) 14769 *dst_reg = *src_reg; 14770 14771 dst_reg->subreg_def = env->insn_idx + 1; 14772 14773 if (BPF_CLASS(insn->code) == BPF_ALU64) 14774 /* 14775 * 32-bit operations zero upper bits automatically. 14776 * 64-bit operations need to be converted to 32. 14777 */ 14778 aux->needs_zext = true; 14779 14780 /* Any arithmetic operations are allowed on arena pointers */ 14781 return 0; 14782 } 14783 14784 if (dst_reg->type != SCALAR_VALUE) 14785 ptr_reg = dst_reg; 14786 14787 if (BPF_SRC(insn->code) == BPF_X) { 14788 if (src_reg->type != SCALAR_VALUE) { 14789 if (dst_reg->type != SCALAR_VALUE) { 14790 /* Combining two pointers by any ALU op yields 14791 * an arbitrary scalar. Disallow all math except 14792 * pointer subtraction 14793 */ 14794 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14795 mark_reg_unknown(env, regs, insn->dst_reg); 14796 return 0; 14797 } 14798 verbose(env, "R%d pointer %s pointer prohibited\n", 14799 insn->dst_reg, 14800 bpf_alu_string[opcode >> 4]); 14801 return -EACCES; 14802 } else { 14803 /* scalar += pointer 14804 * This is legal, but we have to reverse our 14805 * src/dest handling in computing the range 14806 */ 14807 err = mark_chain_precision(env, insn->dst_reg); 14808 if (err) 14809 return err; 14810 return adjust_ptr_min_max_vals(env, insn, 14811 src_reg, dst_reg); 14812 } 14813 } else if (ptr_reg) { 14814 /* pointer += scalar */ 14815 err = mark_chain_precision(env, insn->src_reg); 14816 if (err) 14817 return err; 14818 return adjust_ptr_min_max_vals(env, insn, 14819 dst_reg, src_reg); 14820 } else if (dst_reg->precise) { 14821 /* if dst_reg is precise, src_reg should be precise as well */ 14822 err = mark_chain_precision(env, insn->src_reg); 14823 if (err) 14824 return err; 14825 } 14826 } else { 14827 /* Pretend the src is a reg with a known value, since we only 14828 * need to be able to read from this state. 14829 */ 14830 off_reg.type = SCALAR_VALUE; 14831 __mark_reg_known(&off_reg, insn->imm); 14832 src_reg = &off_reg; 14833 if (ptr_reg) /* pointer += K */ 14834 return adjust_ptr_min_max_vals(env, insn, 14835 ptr_reg, src_reg); 14836 } 14837 14838 /* Got here implies adding two SCALAR_VALUEs */ 14839 if (WARN_ON_ONCE(ptr_reg)) { 14840 print_verifier_state(env, vstate, vstate->curframe, true); 14841 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14842 return -EFAULT; 14843 } 14844 if (WARN_ON(!src_reg)) { 14845 print_verifier_state(env, vstate, vstate->curframe, true); 14846 verbose(env, "verifier internal error: no src_reg\n"); 14847 return -EFAULT; 14848 } 14849 /* 14850 * For alu32 linked register tracking, we need to check dst_reg's 14851 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(), 14852 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX. 14853 */ 14854 u64 dst_umax = reg_umax(dst_reg); 14855 14856 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14857 if (err) 14858 return err; 14859 /* 14860 * Compilers can generate the code 14861 * r1 = r2 14862 * r1 += 0x1 14863 * if r2 < 1000 goto ... 14864 * use r1 in memory access 14865 * So remember constant delta between r2 and r1 and update r1 after 14866 * 'if' condition. 14867 */ 14868 if (env->bpf_capable && 14869 (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) && 14870 dst_reg->id && is_reg_const(src_reg, alu32) && 14871 !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) { 14872 u64 val = reg_const_value(src_reg, alu32); 14873 s32 off; 14874 14875 if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX)) 14876 goto clear_id; 14877 14878 if (alu32 && (dst_umax > U32_MAX)) 14879 goto clear_id; 14880 14881 off = (s32)val; 14882 14883 if (BPF_OP(insn->code) == BPF_SUB) { 14884 /* Negating S32_MIN would overflow */ 14885 if (off == S32_MIN) 14886 goto clear_id; 14887 off = -off; 14888 } 14889 14890 if (dst_reg->id & BPF_ADD_CONST) { 14891 /* 14892 * If the register already went through rX += val 14893 * we cannot accumulate another val into rx->off. 14894 */ 14895 clear_id: 14896 clear_scalar_id(dst_reg); 14897 } else { 14898 if (alu32) 14899 dst_reg->id |= BPF_ADD_CONST32; 14900 else 14901 dst_reg->id |= BPF_ADD_CONST64; 14902 dst_reg->delta = off; 14903 } 14904 } else { 14905 /* 14906 * Make sure ID is cleared otherwise dst_reg min/max could be 14907 * incorrectly propagated into other registers by sync_linked_regs() 14908 */ 14909 clear_scalar_id(dst_reg); 14910 } 14911 return 0; 14912 } 14913 14914 /* check validity of 32-bit and 64-bit arithmetic operations */ 14915 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14916 { 14917 struct bpf_reg_state *regs = cur_regs(env); 14918 u8 opcode = BPF_OP(insn->code); 14919 int err; 14920 14921 if (opcode == BPF_END || opcode == BPF_NEG) { 14922 /* check src operand */ 14923 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14924 if (err) 14925 return err; 14926 14927 if (is_pointer_value(env, insn->dst_reg)) { 14928 verbose(env, "R%d pointer arithmetic prohibited\n", 14929 insn->dst_reg); 14930 return -EACCES; 14931 } 14932 14933 /* check dest operand */ 14934 if (regs[insn->dst_reg].type == SCALAR_VALUE) { 14935 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14936 err = err ?: adjust_scalar_min_max_vals(env, insn, 14937 ®s[insn->dst_reg], 14938 regs[insn->dst_reg]); 14939 } else { 14940 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14941 } 14942 if (err) 14943 return err; 14944 14945 } else if (opcode == BPF_MOV) { 14946 14947 if (BPF_SRC(insn->code) == BPF_X) { 14948 if (insn->off == BPF_ADDR_SPACE_CAST) { 14949 if (!env->prog->aux->arena) { 14950 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14951 return -EINVAL; 14952 } 14953 } 14954 14955 /* check src operand */ 14956 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14957 if (err) 14958 return err; 14959 } 14960 14961 /* check dest operand, mark as required later */ 14962 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14963 if (err) 14964 return err; 14965 14966 if (BPF_SRC(insn->code) == BPF_X) { 14967 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14968 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14969 14970 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14971 if (insn->imm) { 14972 /* off == BPF_ADDR_SPACE_CAST */ 14973 mark_reg_unknown(env, regs, insn->dst_reg); 14974 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14975 dst_reg->type = PTR_TO_ARENA; 14976 /* PTR_TO_ARENA is 32-bit */ 14977 dst_reg->subreg_def = env->insn_idx + 1; 14978 } 14979 } else if (insn->off == 0) { 14980 /* case: R1 = R2 14981 * copy register state to dest reg 14982 */ 14983 assign_scalar_id_before_mov(env, src_reg); 14984 *dst_reg = *src_reg; 14985 dst_reg->subreg_def = DEF_NOT_SUBREG; 14986 } else { 14987 /* case: R1 = (s8, s16 s32)R2 */ 14988 if (is_pointer_value(env, insn->src_reg)) { 14989 verbose(env, 14990 "R%d sign-extension part of pointer\n", 14991 insn->src_reg); 14992 return -EACCES; 14993 } else if (src_reg->type == SCALAR_VALUE) { 14994 bool no_sext; 14995 14996 no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 14997 if (no_sext) 14998 assign_scalar_id_before_mov(env, src_reg); 14999 *dst_reg = *src_reg; 15000 if (!no_sext) 15001 clear_scalar_id(dst_reg); 15002 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 15003 dst_reg->subreg_def = DEF_NOT_SUBREG; 15004 } else { 15005 mark_reg_unknown(env, regs, insn->dst_reg); 15006 } 15007 } 15008 } else { 15009 /* R1 = (u32) R2 */ 15010 if (is_pointer_value(env, insn->src_reg)) { 15011 verbose(env, 15012 "R%d partial copy of pointer\n", 15013 insn->src_reg); 15014 return -EACCES; 15015 } else if (src_reg->type == SCALAR_VALUE) { 15016 if (insn->off == 0) { 15017 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 15018 15019 if (is_src_reg_u32) 15020 assign_scalar_id_before_mov(env, src_reg); 15021 *dst_reg = *src_reg; 15022 /* Make sure ID is cleared if src_reg is not in u32 15023 * range otherwise dst_reg min/max could be incorrectly 15024 * propagated into src_reg by sync_linked_regs() 15025 */ 15026 if (!is_src_reg_u32) 15027 clear_scalar_id(dst_reg); 15028 dst_reg->subreg_def = env->insn_idx + 1; 15029 } else { 15030 /* case: W1 = (s8, s16)W2 */ 15031 bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 15032 15033 if (no_sext) 15034 assign_scalar_id_before_mov(env, src_reg); 15035 *dst_reg = *src_reg; 15036 if (!no_sext) 15037 clear_scalar_id(dst_reg); 15038 dst_reg->subreg_def = env->insn_idx + 1; 15039 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 15040 } 15041 } else { 15042 mark_reg_unknown(env, regs, 15043 insn->dst_reg); 15044 } 15045 zext_32_to_64(dst_reg); 15046 reg_bounds_sync(dst_reg); 15047 } 15048 } else { 15049 /* case: R = imm 15050 * remember the value we stored into this reg 15051 */ 15052 /* clear any state __mark_reg_known doesn't set */ 15053 mark_reg_unknown(env, regs, insn->dst_reg); 15054 regs[insn->dst_reg].type = SCALAR_VALUE; 15055 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15056 __mark_reg_known(regs + insn->dst_reg, 15057 insn->imm); 15058 } else { 15059 __mark_reg_known(regs + insn->dst_reg, 15060 (u32)insn->imm); 15061 } 15062 } 15063 15064 } else { /* all other ALU ops: and, sub, xor, add, ... */ 15065 15066 if (BPF_SRC(insn->code) == BPF_X) { 15067 /* check src1 operand */ 15068 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15069 if (err) 15070 return err; 15071 } 15072 15073 /* check src2 operand */ 15074 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15075 if (err) 15076 return err; 15077 15078 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 15079 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 15080 verbose(env, "div by zero\n"); 15081 return -EINVAL; 15082 } 15083 15084 if ((opcode == BPF_LSH || opcode == BPF_RSH || 15085 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 15086 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 15087 15088 if (insn->imm < 0 || insn->imm >= size) { 15089 verbose(env, "invalid shift %d\n", insn->imm); 15090 return -EINVAL; 15091 } 15092 } 15093 15094 /* check dest operand */ 15095 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15096 err = err ?: adjust_reg_min_max_vals(env, insn); 15097 if (err) 15098 return err; 15099 } 15100 15101 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 15102 } 15103 15104 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 15105 struct bpf_reg_state *dst_reg, 15106 enum bpf_reg_type type, 15107 bool range_right_open) 15108 { 15109 struct bpf_func_state *state; 15110 struct bpf_reg_state *reg; 15111 int new_range; 15112 15113 if (reg_umax(dst_reg) == 0 && range_right_open) 15114 /* This doesn't give us any range */ 15115 return; 15116 15117 if (reg_umax(dst_reg) > MAX_PACKET_OFF) 15118 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15119 * than pkt_end, but that's because it's also less than pkt. 15120 */ 15121 return; 15122 15123 new_range = reg_umax(dst_reg); 15124 if (range_right_open) 15125 new_range++; 15126 15127 /* Examples for register markings: 15128 * 15129 * pkt_data in dst register: 15130 * 15131 * r2 = r3; 15132 * r2 += 8; 15133 * if (r2 > pkt_end) goto <handle exception> 15134 * <access okay> 15135 * 15136 * r2 = r3; 15137 * r2 += 8; 15138 * if (r2 < pkt_end) goto <access okay> 15139 * <handle exception> 15140 * 15141 * Where: 15142 * r2 == dst_reg, pkt_end == src_reg 15143 * r2=pkt(id=n,off=8,r=0) 15144 * r3=pkt(id=n,off=0,r=0) 15145 * 15146 * pkt_data in src register: 15147 * 15148 * r2 = r3; 15149 * r2 += 8; 15150 * if (pkt_end >= r2) goto <access okay> 15151 * <handle exception> 15152 * 15153 * r2 = r3; 15154 * r2 += 8; 15155 * if (pkt_end <= r2) goto <handle exception> 15156 * <access okay> 15157 * 15158 * Where: 15159 * pkt_end == dst_reg, r2 == src_reg 15160 * r2=pkt(id=n,off=8,r=0) 15161 * r3=pkt(id=n,off=0,r=0) 15162 * 15163 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15164 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15165 * and [r3, r3 + 8-1) respectively is safe to access depending on 15166 * the check. 15167 */ 15168 15169 /* If our ids match, then we must have the same max_value. And we 15170 * don't care about the other reg's fixed offset, since if it's too big 15171 * the range won't allow anything. 15172 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16. 15173 */ 15174 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15175 if (reg->type == type && reg->id == dst_reg->id) 15176 /* keep the maximum range already checked */ 15177 reg->range = max(reg->range, new_range); 15178 })); 15179 } 15180 15181 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15182 u8 opcode, bool is_jmp32); 15183 static u8 rev_opcode(u8 opcode); 15184 15185 /* 15186 * Learn more information about live branches by simulating refinement on both branches. 15187 * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means 15188 * that branch is dead. 15189 */ 15190 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32) 15191 { 15192 /* Fallthrough (FALSE) branch */ 15193 regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32); 15194 reg_bounds_sync(&env->false_reg1); 15195 reg_bounds_sync(&env->false_reg2); 15196 /* 15197 * If there is a range bounds violation in *any* of the abstract values in either 15198 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only 15199 * TRUE branch will be taken. 15200 */ 15201 if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2)) 15202 return 1; 15203 15204 /* Jump (TRUE) branch */ 15205 regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32); 15206 reg_bounds_sync(&env->true_reg1); 15207 reg_bounds_sync(&env->true_reg2); 15208 /* 15209 * If there is a range bounds violation in *any* of the abstract values in either 15210 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead. 15211 * Only FALSE branch will be taken. 15212 */ 15213 if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2)) 15214 return 0; 15215 15216 /* Both branches are possible, we can't determine which one will be taken. */ 15217 return -1; 15218 } 15219 15220 /* 15221 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15222 */ 15223 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15224 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15225 { 15226 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15227 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15228 u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1); 15229 u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1); 15230 s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1); 15231 s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1); 15232 u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2); 15233 u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2); 15234 s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2); 15235 s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2); 15236 15237 if (reg1 == reg2) { 15238 switch (opcode) { 15239 case BPF_JGE: 15240 case BPF_JLE: 15241 case BPF_JSGE: 15242 case BPF_JSLE: 15243 case BPF_JEQ: 15244 return 1; 15245 case BPF_JGT: 15246 case BPF_JLT: 15247 case BPF_JSGT: 15248 case BPF_JSLT: 15249 case BPF_JNE: 15250 return 0; 15251 case BPF_JSET: 15252 if (tnum_is_const(t1)) 15253 return t1.value != 0; 15254 else 15255 return (smin1 <= 0 && smax1 >= 0) ? -1 : 1; 15256 default: 15257 return -1; 15258 } 15259 } 15260 15261 switch (opcode) { 15262 case BPF_JEQ: 15263 /* constants, umin/umax and smin/smax checks would be 15264 * redundant in this case because they all should match 15265 */ 15266 if (tnum_is_const(t1) && tnum_is_const(t2)) 15267 return t1.value == t2.value; 15268 if (!tnum_overlap(t1, t2)) 15269 return 0; 15270 /* non-overlapping ranges */ 15271 if (umin1 > umax2 || umax1 < umin2) 15272 return 0; 15273 if (smin1 > smax2 || smax1 < smin2) 15274 return 0; 15275 if (!is_jmp32) { 15276 /* if 64-bit ranges are inconclusive, see if we can 15277 * utilize 32-bit subrange knowledge to eliminate 15278 * branches that can't be taken a priori 15279 */ 15280 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15281 reg_u32_max(reg1) < reg_u32_min(reg2)) 15282 return 0; 15283 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15284 reg_s32_max(reg1) < reg_s32_min(reg2)) 15285 return 0; 15286 } 15287 break; 15288 case BPF_JNE: 15289 /* constants, umin/umax and smin/smax checks would be 15290 * redundant in this case because they all should match 15291 */ 15292 if (tnum_is_const(t1) && tnum_is_const(t2)) 15293 return t1.value != t2.value; 15294 if (!tnum_overlap(t1, t2)) 15295 return 1; 15296 /* non-overlapping ranges */ 15297 if (umin1 > umax2 || umax1 < umin2) 15298 return 1; 15299 if (smin1 > smax2 || smax1 < smin2) 15300 return 1; 15301 if (!is_jmp32) { 15302 /* if 64-bit ranges are inconclusive, see if we can 15303 * utilize 32-bit subrange knowledge to eliminate 15304 * branches that can't be taken a priori 15305 */ 15306 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15307 reg_u32_max(reg1) < reg_u32_min(reg2)) 15308 return 1; 15309 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15310 reg_s32_max(reg1) < reg_s32_min(reg2)) 15311 return 1; 15312 } 15313 break; 15314 case BPF_JSET: 15315 if (!is_reg_const(reg2, is_jmp32)) { 15316 swap(reg1, reg2); 15317 swap(t1, t2); 15318 } 15319 if (!is_reg_const(reg2, is_jmp32)) 15320 return -1; 15321 if ((~t1.mask & t1.value) & t2.value) 15322 return 1; 15323 if (!((t1.mask | t1.value) & t2.value)) 15324 return 0; 15325 break; 15326 case BPF_JGT: 15327 if (umin1 > umax2) 15328 return 1; 15329 else if (umax1 <= umin2) 15330 return 0; 15331 break; 15332 case BPF_JSGT: 15333 if (smin1 > smax2) 15334 return 1; 15335 else if (smax1 <= smin2) 15336 return 0; 15337 break; 15338 case BPF_JLT: 15339 if (umax1 < umin2) 15340 return 1; 15341 else if (umin1 >= umax2) 15342 return 0; 15343 break; 15344 case BPF_JSLT: 15345 if (smax1 < smin2) 15346 return 1; 15347 else if (smin1 >= smax2) 15348 return 0; 15349 break; 15350 case BPF_JGE: 15351 if (umin1 >= umax2) 15352 return 1; 15353 else if (umax1 < umin2) 15354 return 0; 15355 break; 15356 case BPF_JSGE: 15357 if (smin1 >= smax2) 15358 return 1; 15359 else if (smax1 < smin2) 15360 return 0; 15361 break; 15362 case BPF_JLE: 15363 if (umax1 <= umin2) 15364 return 1; 15365 else if (umin1 > umax2) 15366 return 0; 15367 break; 15368 case BPF_JSLE: 15369 if (smax1 <= smin2) 15370 return 1; 15371 else if (smin1 > smax2) 15372 return 0; 15373 break; 15374 } 15375 15376 return simulate_both_branches_taken(env, opcode, is_jmp32); 15377 } 15378 15379 static int flip_opcode(u32 opcode) 15380 { 15381 /* How can we transform "a <op> b" into "b <op> a"? */ 15382 static const u8 opcode_flip[16] = { 15383 /* these stay the same */ 15384 [BPF_JEQ >> 4] = BPF_JEQ, 15385 [BPF_JNE >> 4] = BPF_JNE, 15386 [BPF_JSET >> 4] = BPF_JSET, 15387 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 15388 [BPF_JGE >> 4] = BPF_JLE, 15389 [BPF_JGT >> 4] = BPF_JLT, 15390 [BPF_JLE >> 4] = BPF_JGE, 15391 [BPF_JLT >> 4] = BPF_JGT, 15392 [BPF_JSGE >> 4] = BPF_JSLE, 15393 [BPF_JSGT >> 4] = BPF_JSLT, 15394 [BPF_JSLE >> 4] = BPF_JSGE, 15395 [BPF_JSLT >> 4] = BPF_JSGT 15396 }; 15397 return opcode_flip[opcode >> 4]; 15398 } 15399 15400 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 15401 struct bpf_reg_state *src_reg, 15402 u8 opcode) 15403 { 15404 struct bpf_reg_state *pkt; 15405 15406 if (src_reg->type == PTR_TO_PACKET_END) { 15407 pkt = dst_reg; 15408 } else if (dst_reg->type == PTR_TO_PACKET_END) { 15409 pkt = src_reg; 15410 opcode = flip_opcode(opcode); 15411 } else { 15412 return -1; 15413 } 15414 15415 if (pkt->range >= 0) 15416 return -1; 15417 15418 switch (opcode) { 15419 case BPF_JLE: 15420 /* pkt <= pkt_end */ 15421 fallthrough; 15422 case BPF_JGT: 15423 /* pkt > pkt_end */ 15424 if (pkt->range == BEYOND_PKT_END) 15425 /* pkt has at last one extra byte beyond pkt_end */ 15426 return opcode == BPF_JGT; 15427 break; 15428 case BPF_JLT: 15429 /* pkt < pkt_end */ 15430 fallthrough; 15431 case BPF_JGE: 15432 /* pkt >= pkt_end */ 15433 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 15434 return opcode == BPF_JGE; 15435 break; 15436 } 15437 return -1; 15438 } 15439 15440 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 15441 * and return: 15442 * 1 - branch will be taken and "goto target" will be executed 15443 * 0 - branch will not be taken and fall-through to next insn 15444 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 15445 * range [0,10] 15446 */ 15447 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15448 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15449 { 15450 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 15451 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 15452 15453 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 15454 u64 val; 15455 15456 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 15457 if (!is_reg_const(reg2, is_jmp32)) { 15458 opcode = flip_opcode(opcode); 15459 swap(reg1, reg2); 15460 } 15461 /* and ensure that reg2 is a constant */ 15462 if (!is_reg_const(reg2, is_jmp32)) 15463 return -1; 15464 15465 if (!reg_not_null(env, reg1)) 15466 return -1; 15467 15468 /* If pointer is valid tests against zero will fail so we can 15469 * use this to direct branch taken. 15470 */ 15471 val = reg_const_value(reg2, is_jmp32); 15472 if (val != 0) 15473 return -1; 15474 15475 switch (opcode) { 15476 case BPF_JEQ: 15477 return 0; 15478 case BPF_JNE: 15479 return 1; 15480 default: 15481 return -1; 15482 } 15483 } 15484 15485 /* now deal with two scalars, but not necessarily constants */ 15486 return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32); 15487 } 15488 15489 /* Opcode that corresponds to a *false* branch condition. 15490 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 15491 */ 15492 static u8 rev_opcode(u8 opcode) 15493 { 15494 switch (opcode) { 15495 case BPF_JEQ: return BPF_JNE; 15496 case BPF_JNE: return BPF_JEQ; 15497 /* JSET doesn't have it's reverse opcode in BPF, so add 15498 * BPF_X flag to denote the reverse of that operation 15499 */ 15500 case BPF_JSET: return BPF_JSET | BPF_X; 15501 case BPF_JSET | BPF_X: return BPF_JSET; 15502 case BPF_JGE: return BPF_JLT; 15503 case BPF_JGT: return BPF_JLE; 15504 case BPF_JLE: return BPF_JGT; 15505 case BPF_JLT: return BPF_JGE; 15506 case BPF_JSGE: return BPF_JSLT; 15507 case BPF_JSGT: return BPF_JSLE; 15508 case BPF_JSLE: return BPF_JSGT; 15509 case BPF_JSLT: return BPF_JSGE; 15510 default: return 0; 15511 } 15512 } 15513 15514 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 15515 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15516 u8 opcode, bool is_jmp32) 15517 { 15518 struct tnum t; 15519 u64 val; 15520 15521 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 15522 switch (opcode) { 15523 case BPF_JGE: 15524 case BPF_JGT: 15525 case BPF_JSGE: 15526 case BPF_JSGT: 15527 opcode = flip_opcode(opcode); 15528 swap(reg1, reg2); 15529 break; 15530 default: 15531 break; 15532 } 15533 15534 switch (opcode) { 15535 case BPF_JEQ: 15536 if (is_jmp32) { 15537 reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32); 15538 reg2->r32 = reg1->r32; 15539 15540 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 15541 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15542 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 15543 } else { 15544 reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64); 15545 reg2->r64 = reg1->r64; 15546 15547 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 15548 reg2->var_off = reg1->var_off; 15549 } 15550 break; 15551 case BPF_JNE: 15552 if (!is_reg_const(reg2, is_jmp32)) 15553 swap(reg1, reg2); 15554 if (!is_reg_const(reg2, is_jmp32)) 15555 break; 15556 15557 /* try to recompute the bound of reg1 if reg2 is a const and 15558 * is exactly the edge of reg1. 15559 */ 15560 val = reg_const_value(reg2, is_jmp32); 15561 if (is_jmp32) { 15562 /* Complement of the range [val, val] as cnum32. */ 15563 cnum32_intersect_with(®1->r32, (struct cnum32){ val + 1, U32_MAX - 1 }); 15564 } else { 15565 /* Complement of the range [val, val] as cnum64. */ 15566 cnum64_intersect_with(®1->r64, (struct cnum64){ val + 1, U64_MAX - 1 }); 15567 } 15568 break; 15569 case BPF_JSET: 15570 if (!is_reg_const(reg2, is_jmp32)) 15571 swap(reg1, reg2); 15572 if (!is_reg_const(reg2, is_jmp32)) 15573 break; 15574 val = reg_const_value(reg2, is_jmp32); 15575 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 15576 * requires single bit to learn something useful. E.g., if we 15577 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 15578 * are actually set? We can learn something definite only if 15579 * it's a single-bit value to begin with. 15580 * 15581 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 15582 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 15583 * bit 1 is set, which we can readily use in adjustments. 15584 */ 15585 if (!is_power_of_2(val)) 15586 break; 15587 if (is_jmp32) { 15588 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 15589 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15590 } else { 15591 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 15592 } 15593 break; 15594 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 15595 if (!is_reg_const(reg2, is_jmp32)) 15596 swap(reg1, reg2); 15597 if (!is_reg_const(reg2, is_jmp32)) 15598 break; 15599 val = reg_const_value(reg2, is_jmp32); 15600 /* Forget the ranges before narrowing tnums, to avoid invariant 15601 * violations if we're on a dead branch. 15602 */ 15603 __mark_reg_unbounded(reg1); 15604 if (is_jmp32) { 15605 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 15606 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15607 } else { 15608 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15609 } 15610 break; 15611 case BPF_JLE: 15612 if (is_jmp32) { 15613 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2)); 15614 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1), U32_MAX); 15615 } else { 15616 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2)); 15617 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1), U64_MAX); 15618 } 15619 break; 15620 case BPF_JLT: 15621 if (is_jmp32) { 15622 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2) - 1); 15623 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1) + 1, U32_MAX); 15624 } else { 15625 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2) - 1); 15626 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1) + 1, U64_MAX); 15627 } 15628 break; 15629 case BPF_JSLE: 15630 if (is_jmp32) { 15631 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2)); 15632 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1), S32_MAX); 15633 } else { 15634 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2)); 15635 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1), S64_MAX); 15636 } 15637 break; 15638 case BPF_JSLT: 15639 if (is_jmp32) { 15640 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2) - 1); 15641 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1) + 1, S32_MAX); 15642 } else { 15643 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2) - 1); 15644 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1) + 1, S64_MAX); 15645 } 15646 break; 15647 default: 15648 return; 15649 } 15650 } 15651 15652 /* Check for invariant violations on the registers for both branches of a condition */ 15653 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env) 15654 { 15655 int err; 15656 15657 err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1"); 15658 err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2"); 15659 err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1"); 15660 err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2"); 15661 return err; 15662 } 15663 15664 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 15665 struct bpf_reg_state *reg, u32 id, 15666 bool is_null) 15667 { 15668 if (type_may_be_null(reg->type) && reg->id == id && 15669 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 15670 /* Old offset should have been known-zero, because we don't 15671 * allow pointer arithmetic on pointers that might be NULL. 15672 * If we see this happening, don't convert the register. 15673 * 15674 * But in some cases, some helpers that return local kptrs 15675 * advance offset for the returned pointer. In those cases, 15676 * it is fine to expect to see reg->var_off. 15677 */ 15678 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 15679 WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0))) 15680 return; 15681 if (is_null) { 15682 /* We don't need id from this point 15683 * onwards anymore, thus we should better reset it, 15684 * so that state pruning has chances to take effect. 15685 */ 15686 __mark_reg_known_zero(reg); 15687 reg->type = SCALAR_VALUE; 15688 15689 return; 15690 } 15691 15692 mark_ptr_not_null_reg(reg); 15693 15694 /* 15695 * reg->id is preserved for object relationship tracking 15696 * and spin_lock lock state tracking 15697 */ 15698 } 15699 } 15700 15701 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15702 * be folded together at some point. 15703 */ 15704 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15705 bool is_null) 15706 { 15707 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15708 struct bpf_reg_state *regs = state->regs, *reg; 15709 u32 id = regs[regno].id; 15710 15711 if (is_null && find_reference_state(vstate, id)) 15712 /* regs[regno] is in the " == NULL" branch. 15713 * No one could have freed the reference state before 15714 * doing the NULL check. 15715 */ 15716 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 15717 15718 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15719 mark_ptr_or_null_reg(state, reg, id, is_null); 15720 })); 15721 } 15722 15723 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15724 struct bpf_reg_state *dst_reg, 15725 struct bpf_reg_state *src_reg, 15726 struct bpf_verifier_state *this_branch, 15727 struct bpf_verifier_state *other_branch) 15728 { 15729 if (BPF_SRC(insn->code) != BPF_X) 15730 return false; 15731 15732 /* Pointers are always 64-bit. */ 15733 if (BPF_CLASS(insn->code) == BPF_JMP32) 15734 return false; 15735 15736 switch (BPF_OP(insn->code)) { 15737 case BPF_JGT: 15738 if ((dst_reg->type == PTR_TO_PACKET && 15739 src_reg->type == PTR_TO_PACKET_END) || 15740 (dst_reg->type == PTR_TO_PACKET_META && 15741 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15742 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15743 find_good_pkt_pointers(this_branch, dst_reg, 15744 dst_reg->type, false); 15745 mark_pkt_end(other_branch, insn->dst_reg, true); 15746 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15747 src_reg->type == PTR_TO_PACKET) || 15748 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15749 src_reg->type == PTR_TO_PACKET_META)) { 15750 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15751 find_good_pkt_pointers(other_branch, src_reg, 15752 src_reg->type, true); 15753 mark_pkt_end(this_branch, insn->src_reg, false); 15754 } else { 15755 return false; 15756 } 15757 break; 15758 case BPF_JLT: 15759 if ((dst_reg->type == PTR_TO_PACKET && 15760 src_reg->type == PTR_TO_PACKET_END) || 15761 (dst_reg->type == PTR_TO_PACKET_META && 15762 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15763 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15764 find_good_pkt_pointers(other_branch, dst_reg, 15765 dst_reg->type, true); 15766 mark_pkt_end(this_branch, insn->dst_reg, false); 15767 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15768 src_reg->type == PTR_TO_PACKET) || 15769 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15770 src_reg->type == PTR_TO_PACKET_META)) { 15771 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15772 find_good_pkt_pointers(this_branch, src_reg, 15773 src_reg->type, false); 15774 mark_pkt_end(other_branch, insn->src_reg, true); 15775 } else { 15776 return false; 15777 } 15778 break; 15779 case BPF_JGE: 15780 if ((dst_reg->type == PTR_TO_PACKET && 15781 src_reg->type == PTR_TO_PACKET_END) || 15782 (dst_reg->type == PTR_TO_PACKET_META && 15783 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15784 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15785 find_good_pkt_pointers(this_branch, dst_reg, 15786 dst_reg->type, true); 15787 mark_pkt_end(other_branch, insn->dst_reg, false); 15788 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15789 src_reg->type == PTR_TO_PACKET) || 15790 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15791 src_reg->type == PTR_TO_PACKET_META)) { 15792 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15793 find_good_pkt_pointers(other_branch, src_reg, 15794 src_reg->type, false); 15795 mark_pkt_end(this_branch, insn->src_reg, true); 15796 } else { 15797 return false; 15798 } 15799 break; 15800 case BPF_JLE: 15801 if ((dst_reg->type == PTR_TO_PACKET && 15802 src_reg->type == PTR_TO_PACKET_END) || 15803 (dst_reg->type == PTR_TO_PACKET_META && 15804 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15805 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15806 find_good_pkt_pointers(other_branch, dst_reg, 15807 dst_reg->type, false); 15808 mark_pkt_end(this_branch, insn->dst_reg, true); 15809 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15810 src_reg->type == PTR_TO_PACKET) || 15811 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15812 src_reg->type == PTR_TO_PACKET_META)) { 15813 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15814 find_good_pkt_pointers(this_branch, src_reg, 15815 src_reg->type, true); 15816 mark_pkt_end(other_branch, insn->src_reg, false); 15817 } else { 15818 return false; 15819 } 15820 break; 15821 default: 15822 return false; 15823 } 15824 15825 return true; 15826 } 15827 15828 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 15829 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 15830 { 15831 struct linked_reg *e; 15832 15833 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 15834 return; 15835 15836 e = linked_regs_push(reg_set); 15837 if (e) { 15838 e->frameno = frameno; 15839 e->is_reg = is_reg; 15840 e->regno = spi_or_reg; 15841 } else { 15842 clear_scalar_id(reg); 15843 } 15844 } 15845 15846 /* For all R being scalar registers or spilled scalar registers 15847 * in verifier state, save R in linked_regs if R->id == id. 15848 * If there are too many Rs sharing same id, reset id for leftover Rs. 15849 */ 15850 static void collect_linked_regs(struct bpf_verifier_env *env, 15851 struct bpf_verifier_state *vstate, 15852 u32 id, 15853 struct linked_regs *linked_regs) 15854 { 15855 struct bpf_insn_aux_data *aux = env->insn_aux_data; 15856 struct bpf_func_state *func; 15857 struct bpf_reg_state *reg; 15858 u16 live_regs; 15859 int i, j; 15860 15861 id = id & ~BPF_ADD_CONST; 15862 for (i = vstate->curframe; i >= 0; i--) { 15863 live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before; 15864 func = vstate->frame[i]; 15865 for (j = 0; j < BPF_REG_FP; j++) { 15866 if (!(live_regs & BIT(j))) 15867 continue; 15868 reg = &func->regs[j]; 15869 __collect_linked_regs(linked_regs, reg, id, i, j, true); 15870 } 15871 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 15872 if (!bpf_is_spilled_reg(&func->stack[j])) 15873 continue; 15874 reg = &func->stack[j].spilled_ptr; 15875 __collect_linked_regs(linked_regs, reg, id, i, j, false); 15876 } 15877 } 15878 } 15879 15880 /* For all R in linked_regs, copy known_reg range into R 15881 * if R->id == known_reg->id. 15882 */ 15883 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate, 15884 struct bpf_reg_state *known_reg, struct linked_regs *linked_regs) 15885 { 15886 struct bpf_reg_state fake_reg; 15887 struct bpf_reg_state *reg; 15888 struct linked_reg *e; 15889 int i; 15890 15891 for (i = 0; i < linked_regs->cnt; ++i) { 15892 e = &linked_regs->entries[i]; 15893 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 15894 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 15895 if (reg->type != SCALAR_VALUE || reg == known_reg) 15896 continue; 15897 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15898 continue; 15899 /* 15900 * Skip mixed 32/64-bit links: the delta relationship doesn't 15901 * hold across different ALU widths. 15902 */ 15903 if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST) 15904 continue; 15905 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15906 reg->delta == known_reg->delta) { 15907 s32 saved_subreg_def = reg->subreg_def; 15908 15909 *reg = *known_reg; 15910 reg->subreg_def = saved_subreg_def; 15911 } else { 15912 s32 saved_subreg_def = reg->subreg_def; 15913 s32 saved_off = reg->delta; 15914 u32 saved_id = reg->id; 15915 15916 fake_reg.type = SCALAR_VALUE; 15917 __mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta); 15918 15919 /* reg = known_reg; reg += delta */ 15920 *reg = *known_reg; 15921 /* 15922 * Must preserve off, id and subreg_def flag, 15923 * otherwise another sync_linked_regs() will be incorrect. 15924 */ 15925 reg->delta = saved_off; 15926 reg->id = saved_id; 15927 reg->subreg_def = saved_subreg_def; 15928 15929 scalar32_min_max_add(reg, &fake_reg); 15930 scalar_min_max_add(reg, &fake_reg); 15931 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15932 if ((reg->id | known_reg->id) & BPF_ADD_CONST32) 15933 zext_32_to_64(reg); 15934 reg_bounds_sync(reg); 15935 } 15936 if (e->is_reg) 15937 mark_reg_scratched(env, e->regno); 15938 else 15939 mark_stack_slot_scratched(env, e->spi); 15940 } 15941 } 15942 15943 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15944 struct bpf_insn *insn, int *insn_idx) 15945 { 15946 struct bpf_verifier_state *this_branch = env->cur_state; 15947 struct bpf_verifier_state *other_branch; 15948 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15949 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15950 struct bpf_reg_state *eq_branch_regs; 15951 struct linked_regs linked_regs = {}; 15952 u8 opcode = BPF_OP(insn->code); 15953 int insn_flags = 0; 15954 bool is_jmp32; 15955 int pred = -1; 15956 int err; 15957 15958 /* Only conditional jumps are expected to reach here. */ 15959 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15960 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15961 return -EINVAL; 15962 } 15963 15964 if (opcode == BPF_JCOND) { 15965 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15966 int idx = *insn_idx; 15967 15968 prev_st = find_prev_entry(env, cur_st->parent, idx); 15969 15970 /* branch out 'fallthrough' insn as a new state to explore */ 15971 queued_st = push_stack(env, idx + 1, idx, false); 15972 if (IS_ERR(queued_st)) 15973 return PTR_ERR(queued_st); 15974 15975 queued_st->may_goto_depth++; 15976 if (prev_st) 15977 widen_imprecise_scalars(env, prev_st, queued_st); 15978 *insn_idx += insn->off; 15979 return 0; 15980 } 15981 15982 /* check src2 operand */ 15983 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15984 if (err) 15985 return err; 15986 15987 dst_reg = ®s[insn->dst_reg]; 15988 if (BPF_SRC(insn->code) == BPF_X) { 15989 /* check src1 operand */ 15990 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15991 if (err) 15992 return err; 15993 15994 src_reg = ®s[insn->src_reg]; 15995 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15996 is_pointer_value(env, insn->src_reg)) { 15997 verbose(env, "R%d pointer comparison prohibited\n", 15998 insn->src_reg); 15999 return -EACCES; 16000 } 16001 16002 if (src_reg->type == PTR_TO_STACK) 16003 insn_flags |= INSN_F_SRC_REG_STACK; 16004 if (dst_reg->type == PTR_TO_STACK) 16005 insn_flags |= INSN_F_DST_REG_STACK; 16006 } else { 16007 src_reg = &env->fake_reg[0]; 16008 memset(src_reg, 0, sizeof(*src_reg)); 16009 src_reg->type = SCALAR_VALUE; 16010 __mark_reg_known(src_reg, insn->imm); 16011 16012 if (dst_reg->type == PTR_TO_STACK) 16013 insn_flags |= INSN_F_DST_REG_STACK; 16014 } 16015 16016 if (insn_flags) { 16017 err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, 0); 16018 if (err) 16019 return err; 16020 } 16021 16022 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 16023 env->false_reg1 = *dst_reg; 16024 env->false_reg2 = *src_reg; 16025 env->true_reg1 = *dst_reg; 16026 env->true_reg2 = *src_reg; 16027 pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32); 16028 if (pred >= 0) { 16029 /* If we get here with a dst_reg pointer type it is because 16030 * above is_branch_taken() special cased the 0 comparison. 16031 */ 16032 if (!__is_pointer_value(false, dst_reg)) 16033 err = mark_chain_precision(env, insn->dst_reg); 16034 if (BPF_SRC(insn->code) == BPF_X && !err && 16035 !__is_pointer_value(false, src_reg)) 16036 err = mark_chain_precision(env, insn->src_reg); 16037 if (err) 16038 return err; 16039 } 16040 16041 if (pred == 1) { 16042 /* Only follow the goto, ignore fall-through. If needed, push 16043 * the fall-through branch for simulation under speculative 16044 * execution. 16045 */ 16046 if (!env->bypass_spec_v1) { 16047 err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx); 16048 if (err < 0) 16049 return err; 16050 } 16051 if (env->log.level & BPF_LOG_LEVEL) 16052 print_insn_state(env, this_branch, this_branch->curframe); 16053 *insn_idx += insn->off; 16054 return 0; 16055 } else if (pred == 0) { 16056 /* Only follow the fall-through branch, since that's where the 16057 * program will go. If needed, push the goto branch for 16058 * simulation under speculative execution. 16059 */ 16060 if (!env->bypass_spec_v1) { 16061 err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1, 16062 *insn_idx); 16063 if (err < 0) 16064 return err; 16065 } 16066 if (env->log.level & BPF_LOG_LEVEL) 16067 print_insn_state(env, this_branch, this_branch->curframe); 16068 return 0; 16069 } 16070 16071 /* Push scalar registers sharing same ID to jump history, 16072 * do this before creating 'other_branch', so that both 16073 * 'this_branch' and 'other_branch' share this history 16074 * if parent state is created. 16075 */ 16076 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 16077 collect_linked_regs(env, this_branch, src_reg->id, &linked_regs); 16078 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 16079 collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs); 16080 if (linked_regs.cnt > 1) { 16081 err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, linked_regs_pack(&linked_regs)); 16082 if (err) 16083 return err; 16084 } 16085 16086 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); 16087 if (IS_ERR(other_branch)) 16088 return PTR_ERR(other_branch); 16089 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 16090 16091 err = regs_bounds_sanity_check_branches(env); 16092 if (err) 16093 return err; 16094 16095 *dst_reg = env->false_reg1; 16096 *src_reg = env->false_reg2; 16097 other_branch_regs[insn->dst_reg] = env->true_reg1; 16098 if (BPF_SRC(insn->code) == BPF_X) 16099 other_branch_regs[insn->src_reg] = env->true_reg2; 16100 16101 if (BPF_SRC(insn->code) == BPF_X && 16102 src_reg->type == SCALAR_VALUE && src_reg->id && 16103 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 16104 sync_linked_regs(env, this_branch, src_reg, &linked_regs); 16105 sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg], 16106 &linked_regs); 16107 } 16108 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 16109 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 16110 sync_linked_regs(env, this_branch, dst_reg, &linked_regs); 16111 sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg], 16112 &linked_regs); 16113 } 16114 16115 /* if one pointer register is compared to another pointer 16116 * register check if PTR_MAYBE_NULL could be lifted. 16117 * E.g. register A - maybe null 16118 * register B - not null 16119 * for JNE A, B, ... - A is not null in the false branch; 16120 * for JEQ A, B, ... - A is not null in the true branch. 16121 * 16122 * Since PTR_TO_BTF_ID points to a kernel struct that does 16123 * not need to be null checked by the BPF program, i.e., 16124 * could be null even without PTR_MAYBE_NULL marking, so 16125 * only propagate nullness when neither reg is that type. 16126 */ 16127 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16128 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16129 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16130 base_type(src_reg->type) != PTR_TO_BTF_ID && 16131 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16132 eq_branch_regs = NULL; 16133 switch (opcode) { 16134 case BPF_JEQ: 16135 eq_branch_regs = other_branch_regs; 16136 break; 16137 case BPF_JNE: 16138 eq_branch_regs = regs; 16139 break; 16140 default: 16141 /* do nothing */ 16142 break; 16143 } 16144 if (eq_branch_regs) { 16145 if (type_may_be_null(src_reg->type)) 16146 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16147 else 16148 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16149 } 16150 } 16151 16152 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16153 * Also does the same detection for a register whose the value is 16154 * known to be 0. 16155 * NOTE: these optimizations below are related with pointer comparison 16156 * which will never be JMP32. 16157 */ 16158 if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16159 type_may_be_null(dst_reg->type) && 16160 ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) || 16161 (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) { 16162 /* Mark all identical registers in each branch as either 16163 * safe or unknown depending R == 0 or R != 0 conditional. 16164 */ 16165 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16166 opcode == BPF_JNE); 16167 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16168 opcode == BPF_JEQ); 16169 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16170 this_branch, other_branch) && 16171 is_pointer_value(env, insn->dst_reg)) { 16172 verbose(env, "R%d pointer comparison prohibited\n", 16173 insn->dst_reg); 16174 return -EACCES; 16175 } 16176 if (env->log.level & BPF_LOG_LEVEL) 16177 print_insn_state(env, this_branch, this_branch->curframe); 16178 return 0; 16179 } 16180 16181 /* verify BPF_LD_IMM64 instruction */ 16182 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16183 { 16184 struct bpf_insn_aux_data *aux = cur_aux(env); 16185 struct bpf_reg_state *regs = cur_regs(env); 16186 struct bpf_reg_state *dst_reg; 16187 struct bpf_map *map; 16188 int err; 16189 16190 if (BPF_SIZE(insn->code) != BPF_DW) { 16191 verbose(env, "invalid BPF_LD_IMM insn\n"); 16192 return -EINVAL; 16193 } 16194 16195 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16196 if (err) 16197 return err; 16198 16199 dst_reg = ®s[insn->dst_reg]; 16200 if (insn->src_reg == 0) { 16201 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16202 16203 dst_reg->type = SCALAR_VALUE; 16204 __mark_reg_known(®s[insn->dst_reg], imm); 16205 return 0; 16206 } 16207 16208 /* All special src_reg cases are listed below. From this point onwards 16209 * we either succeed and assign a corresponding dst_reg->type after 16210 * zeroing the offset, or fail and reject the program. 16211 */ 16212 mark_reg_known_zero(env, regs, insn->dst_reg); 16213 16214 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16215 dst_reg->type = aux->btf_var.reg_type; 16216 switch (base_type(dst_reg->type)) { 16217 case PTR_TO_MEM: 16218 dst_reg->mem_size = aux->btf_var.mem_size; 16219 break; 16220 case PTR_TO_BTF_ID: 16221 dst_reg->btf = aux->btf_var.btf; 16222 dst_reg->btf_id = aux->btf_var.btf_id; 16223 break; 16224 default: 16225 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 16226 return -EFAULT; 16227 } 16228 return 0; 16229 } 16230 16231 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16232 struct bpf_prog_aux *aux = env->prog->aux; 16233 u32 subprogno = bpf_find_subprog(env, 16234 env->insn_idx + insn->imm + 1); 16235 16236 if (!aux->func_info) { 16237 verbose(env, "missing btf func_info\n"); 16238 return -EINVAL; 16239 } 16240 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16241 verbose(env, "callback function not static\n"); 16242 return -EINVAL; 16243 } 16244 16245 dst_reg->type = PTR_TO_FUNC; 16246 dst_reg->subprogno = subprogno; 16247 return 0; 16248 } 16249 16250 map = env->used_maps[aux->map_index]; 16251 16252 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16253 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16254 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16255 __mark_reg_unknown(env, dst_reg); 16256 dst_reg->map_ptr = map; 16257 return 0; 16258 } 16259 __mark_reg_known(dst_reg, aux->map_off); 16260 dst_reg->type = PTR_TO_MAP_VALUE; 16261 dst_reg->map_ptr = map; 16262 WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY && 16263 map->max_entries != 1); 16264 /* We want reg->id to be same (0) as map_value is not distinct */ 16265 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16266 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16267 dst_reg->type = CONST_PTR_TO_MAP; 16268 dst_reg->map_ptr = map; 16269 } else { 16270 verifier_bug(env, "unexpected src reg value for ldimm64"); 16271 return -EFAULT; 16272 } 16273 16274 return 0; 16275 } 16276 16277 static bool may_access_skb(enum bpf_prog_type type) 16278 { 16279 switch (type) { 16280 case BPF_PROG_TYPE_SOCKET_FILTER: 16281 case BPF_PROG_TYPE_SCHED_CLS: 16282 case BPF_PROG_TYPE_SCHED_ACT: 16283 return true; 16284 default: 16285 return false; 16286 } 16287 } 16288 16289 /* verify safety of LD_ABS|LD_IND instructions: 16290 * - they can only appear in the programs where ctx == skb 16291 * - since they are wrappers of function calls, they scratch R1-R5 registers, 16292 * preserve R6-R9, and store return value into R0 16293 * 16294 * Implicit input: 16295 * ctx == skb == R6 == CTX 16296 * 16297 * Explicit input: 16298 * SRC == any register 16299 * IMM == 32-bit immediate 16300 * 16301 * Output: 16302 * R0 - 8/16/32-bit skb data converted to cpu endianness 16303 */ 16304 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 16305 { 16306 struct bpf_reg_state *regs = cur_regs(env); 16307 static const int ctx_reg = BPF_REG_6; 16308 u8 mode = BPF_MODE(insn->code); 16309 int i, err; 16310 16311 if (!may_access_skb(resolve_prog_type(env->prog))) { 16312 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 16313 return -EINVAL; 16314 } 16315 16316 if (!env->ops->gen_ld_abs) { 16317 verifier_bug(env, "gen_ld_abs is null"); 16318 return -EFAULT; 16319 } 16320 16321 /* check whether implicit source operand (register R6) is readable */ 16322 err = check_reg_arg(env, ctx_reg, SRC_OP); 16323 if (err) 16324 return err; 16325 16326 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 16327 * gen_ld_abs() may terminate the program at runtime, leading to 16328 * reference leak. 16329 */ 16330 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 16331 if (err) 16332 return err; 16333 16334 if (regs[ctx_reg].type != PTR_TO_CTX) { 16335 verbose(env, 16336 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 16337 return -EINVAL; 16338 } 16339 16340 if (mode == BPF_IND) { 16341 /* check explicit source operand */ 16342 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16343 if (err) 16344 return err; 16345 } 16346 16347 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 16348 if (err < 0) 16349 return err; 16350 16351 /* reset caller saved regs to unreadable */ 16352 for (i = 0; i < CALLER_SAVED_REGS; i++) { 16353 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 16354 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 16355 } 16356 16357 /* mark destination R0 register as readable, since it contains 16358 * the value fetched from the packet. 16359 * Already marked as written above. 16360 */ 16361 mark_reg_unknown(env, regs, BPF_REG_0); 16362 /* ld_abs load up to 32-bit skb data. */ 16363 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 16364 /* 16365 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0 16366 * which must be explored by the verifier when in a subprog. 16367 */ 16368 if (env->cur_state->curframe) { 16369 struct bpf_verifier_state *branch; 16370 16371 mark_reg_scratched(env, BPF_REG_0); 16372 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 16373 if (IS_ERR(branch)) 16374 return PTR_ERR(branch); 16375 mark_reg_known_zero(env, regs, BPF_REG_0); 16376 err = prepare_func_exit(env, &env->insn_idx); 16377 if (err) 16378 return err; 16379 env->insn_idx--; 16380 } 16381 return 0; 16382 } 16383 16384 16385 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range) 16386 { 16387 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16388 16389 /* Default return value range. */ 16390 *range = retval_range(0, 1); 16391 16392 switch (prog_type) { 16393 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 16394 switch (env->prog->expected_attach_type) { 16395 case BPF_CGROUP_UDP4_RECVMSG: 16396 case BPF_CGROUP_UDP6_RECVMSG: 16397 case BPF_CGROUP_UNIX_RECVMSG: 16398 case BPF_CGROUP_INET4_GETPEERNAME: 16399 case BPF_CGROUP_INET6_GETPEERNAME: 16400 case BPF_CGROUP_UNIX_GETPEERNAME: 16401 case BPF_CGROUP_INET4_GETSOCKNAME: 16402 case BPF_CGROUP_INET6_GETSOCKNAME: 16403 case BPF_CGROUP_UNIX_GETSOCKNAME: 16404 *range = retval_range(1, 1); 16405 break; 16406 case BPF_CGROUP_INET4_BIND: 16407 case BPF_CGROUP_INET6_BIND: 16408 *range = retval_range(0, 3); 16409 break; 16410 default: 16411 break; 16412 } 16413 break; 16414 case BPF_PROG_TYPE_CGROUP_SKB: 16415 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) 16416 *range = retval_range(0, 3); 16417 break; 16418 case BPF_PROG_TYPE_CGROUP_SOCK: 16419 case BPF_PROG_TYPE_SOCK_OPS: 16420 case BPF_PROG_TYPE_CGROUP_DEVICE: 16421 case BPF_PROG_TYPE_CGROUP_SYSCTL: 16422 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 16423 break; 16424 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16425 if (!env->prog->aux->attach_btf_id) 16426 return false; 16427 *range = retval_range(0, 0); 16428 break; 16429 case BPF_PROG_TYPE_TRACING: 16430 switch (env->prog->expected_attach_type) { 16431 case BPF_TRACE_FENTRY: 16432 case BPF_TRACE_FEXIT: 16433 case BPF_TRACE_FSESSION: 16434 case BPF_TRACE_FENTRY_MULTI: 16435 case BPF_TRACE_FEXIT_MULTI: 16436 case BPF_TRACE_FSESSION_MULTI: 16437 *range = retval_range(0, 0); 16438 break; 16439 case BPF_TRACE_RAW_TP: 16440 case BPF_MODIFY_RETURN: 16441 return false; 16442 case BPF_TRACE_ITER: 16443 default: 16444 break; 16445 } 16446 break; 16447 case BPF_PROG_TYPE_KPROBE: 16448 switch (env->prog->expected_attach_type) { 16449 case BPF_TRACE_KPROBE_SESSION: 16450 case BPF_TRACE_UPROBE_SESSION: 16451 break; 16452 default: 16453 return false; 16454 } 16455 break; 16456 case BPF_PROG_TYPE_SK_LOOKUP: 16457 *range = retval_range(SK_DROP, SK_PASS); 16458 break; 16459 16460 case BPF_PROG_TYPE_LSM: 16461 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 16462 /* no range found, any return value is allowed */ 16463 if (!get_func_retval_range(env->prog, range)) 16464 return false; 16465 /* no restricted range, any return value is allowed */ 16466 if (range->minval == S32_MIN && range->maxval == S32_MAX) 16467 return false; 16468 range->return_32bit = true; 16469 } else if (!env->prog->aux->attach_func_proto->type) { 16470 /* Make sure programs that attach to void 16471 * hooks don't try to modify return value. 16472 */ 16473 *range = retval_range(1, 1); 16474 } 16475 break; 16476 16477 case BPF_PROG_TYPE_NETFILTER: 16478 *range = retval_range(NF_DROP, NF_ACCEPT); 16479 break; 16480 case BPF_PROG_TYPE_STRUCT_OPS: 16481 *range = retval_range(0, 0); 16482 break; 16483 case BPF_PROG_TYPE_EXT: 16484 /* freplace program can return anything as its return value 16485 * depends on the to-be-replaced kernel func or bpf program. 16486 */ 16487 default: 16488 return false; 16489 } 16490 16491 /* Continue calculating. */ 16492 16493 return true; 16494 } 16495 16496 static bool program_returns_void(struct bpf_verifier_env *env) 16497 { 16498 const struct bpf_prog *prog = env->prog; 16499 enum bpf_prog_type prog_type = prog->type; 16500 16501 switch (prog_type) { 16502 case BPF_PROG_TYPE_LSM: 16503 /* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */ 16504 if (prog->expected_attach_type != BPF_LSM_CGROUP && 16505 !prog->aux->attach_func_proto->type) 16506 return true; 16507 break; 16508 case BPF_PROG_TYPE_STRUCT_OPS: 16509 if (!prog->aux->attach_func_proto->type) 16510 return true; 16511 break; 16512 case BPF_PROG_TYPE_EXT: 16513 /* 16514 * If the actual program is an extension, let it 16515 * return void - attaching will succeed only if the 16516 * program being replaced also returns void, and since 16517 * it has passed verification its actual type doesn't matter. 16518 */ 16519 if (subprog_returns_void(env, 0)) 16520 return true; 16521 break; 16522 default: 16523 break; 16524 } 16525 return false; 16526 } 16527 16528 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 16529 { 16530 const char *exit_ctx = "At program exit"; 16531 struct tnum enforce_attach_type_range = tnum_unknown; 16532 const struct bpf_prog *prog = env->prog; 16533 struct bpf_reg_state *reg = reg_state(env, regno); 16534 struct bpf_retval_range range = retval_range(0, 1); 16535 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16536 struct bpf_func_state *frame = env->cur_state->frame[0]; 16537 const struct btf_type *reg_type, *ret_type = NULL; 16538 int err; 16539 16540 /* LSM and struct_ops func-ptr's return type could be "void" */ 16541 if (!frame->in_async_callback_fn && program_returns_void(env)) 16542 return 0; 16543 16544 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) { 16545 /* Allow a struct_ops program to return a referenced kptr if it 16546 * matches the operator's return type and is in its unmodified 16547 * form. A scalar zero (i.e., a null pointer) is also allowed. 16548 */ 16549 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 16550 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 16551 prog->aux->attach_func_proto->type, 16552 NULL); 16553 if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg)) 16554 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 16555 } 16556 16557 /* eBPF calling convention is such that R0 is used 16558 * to return the value from eBPF program. 16559 * Make sure that it's readable at this time 16560 * of bpf_exit, which means that program wrote 16561 * something into it earlier 16562 */ 16563 err = check_reg_arg(env, regno, SRC_OP); 16564 if (err) 16565 return err; 16566 16567 if (is_pointer_value(env, regno)) { 16568 verbose(env, "R%d leaks addr as return value\n", regno); 16569 return -EACCES; 16570 } 16571 16572 if (frame->in_async_callback_fn) { 16573 exit_ctx = "At async callback return"; 16574 range = frame->callback_ret_range; 16575 goto enforce_retval; 16576 } 16577 16578 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type) 16579 return 0; 16580 16581 if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)) 16582 enforce_attach_type_range = tnum_range(2, 3); 16583 16584 if (!return_retval_range(env, &range)) 16585 return 0; 16586 16587 enforce_retval: 16588 if (reg->type != SCALAR_VALUE) { 16589 verbose(env, "%s the register R%d is not a known value (%s)\n", 16590 exit_ctx, regno, reg_type_str(env, reg->type)); 16591 return -EINVAL; 16592 } 16593 16594 err = mark_chain_precision(env, regno); 16595 if (err) 16596 return err; 16597 16598 if (!retval_range_within(range, reg)) { 16599 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 16600 if (prog->expected_attach_type == BPF_LSM_CGROUP && 16601 prog_type == BPF_PROG_TYPE_LSM && 16602 !prog->aux->attach_func_proto->type) 16603 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 16604 return -EINVAL; 16605 } 16606 16607 if (!tnum_is_unknown(enforce_attach_type_range) && 16608 tnum_in(enforce_attach_type_range, reg->var_off)) 16609 env->prog->enforce_expected_attach_type = 1; 16610 return 0; 16611 } 16612 16613 static int check_global_subprog_return_code(struct bpf_verifier_env *env) 16614 { 16615 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 16616 struct bpf_func_state *cur_frame = cur_func(env); 16617 int err; 16618 16619 if (subprog_returns_void(env, cur_frame->subprogno)) 16620 return 0; 16621 16622 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 16623 if (err) 16624 return err; 16625 16626 /* Pointers to arena are safe to pass between subprograms. */ 16627 if (is_arena_reg(env, BPF_REG_0)) 16628 return 0; 16629 16630 if (is_pointer_value(env, BPF_REG_0)) { 16631 verbose(env, "R%d leaks addr as return value\n", BPF_REG_0); 16632 return -EACCES; 16633 } 16634 16635 if (reg->type != SCALAR_VALUE) { 16636 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 16637 reg_type_str(env, reg->type)); 16638 return -EINVAL; 16639 } 16640 16641 return 0; 16642 } 16643 16644 /* Bitmask with 1s for all caller saved registers */ 16645 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16646 16647 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16648 * replacement patch is presumed to follow bpf_fastcall contract 16649 * (see mark_fastcall_pattern_for_call() below). 16650 */ 16651 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 16652 { 16653 switch (imm) { 16654 #ifdef CONFIG_X86_64 16655 case BPF_FUNC_get_smp_processor_id: 16656 #ifdef CONFIG_SMP 16657 case BPF_FUNC_get_current_task_btf: 16658 case BPF_FUNC_get_current_task: 16659 #endif 16660 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 16661 #endif 16662 default: 16663 return false; 16664 } 16665 } 16666 16667 /* If @call is a kfunc or helper call, fills @cs and returns true, 16668 * otherwise returns false. 16669 */ 16670 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 16671 struct bpf_call_summary *cs) 16672 { 16673 struct bpf_kfunc_call_arg_meta meta; 16674 const struct bpf_func_proto *fn; 16675 int i; 16676 16677 if (bpf_helper_call(call)) { 16678 16679 if (bpf_get_helper_proto(env, call->imm, &fn) < 0) 16680 /* error would be reported later */ 16681 return false; 16682 cs->fastcall = fn->allow_fastcall && 16683 (bpf_verifier_inlines_helper_call(env, call->imm) || 16684 bpf_jit_inlines_helper_call(call->imm)); 16685 cs->is_void = fn->ret_type == RET_VOID; 16686 cs->num_params = 0; 16687 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 16688 if (fn->arg_type[i] == ARG_DONTCARE) 16689 break; 16690 cs->num_params++; 16691 } 16692 return true; 16693 } 16694 16695 if (bpf_pseudo_kfunc_call(call)) { 16696 int err; 16697 16698 err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta); 16699 if (err < 0) 16700 /* error would be reported later */ 16701 return false; 16702 cs->num_params = btf_type_vlen(meta.func_proto); 16703 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 16704 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 16705 return true; 16706 } 16707 16708 return false; 16709 } 16710 16711 /* LLVM define a bpf_fastcall function attribute. 16712 * This attribute means that function scratches only some of 16713 * the caller saved registers defined by ABI. 16714 * For BPF the set of such registers could be defined as follows: 16715 * - R0 is scratched only if function is non-void; 16716 * - R1-R5 are scratched only if corresponding parameter type is defined 16717 * in the function prototype. 16718 * 16719 * The contract between kernel and clang allows to simultaneously use 16720 * such functions and maintain backwards compatibility with old 16721 * kernels that don't understand bpf_fastcall calls: 16722 * 16723 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 16724 * registers are not scratched by the call; 16725 * 16726 * - as a post-processing step, clang visits each bpf_fastcall call and adds 16727 * spill/fill for every live r0-r5; 16728 * 16729 * - stack offsets used for the spill/fill are allocated as lowest 16730 * stack offsets in whole function and are not used for any other 16731 * purposes; 16732 * 16733 * - when kernel loads a program, it looks for such patterns 16734 * (bpf_fastcall function surrounded by spills/fills) and checks if 16735 * spill/fill stack offsets are used exclusively in fastcall patterns; 16736 * 16737 * - if so, and if verifier or current JIT inlines the call to the 16738 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 16739 * spill/fill pairs; 16740 * 16741 * - when old kernel loads a program, presence of spill/fill pairs 16742 * keeps BPF program valid, albeit slightly less efficient. 16743 * 16744 * For example: 16745 * 16746 * r1 = 1; 16747 * r2 = 2; 16748 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16749 * *(u64 *)(r10 - 16) = r2; r2 = 2; 16750 * call %[to_be_inlined] --> call %[to_be_inlined] 16751 * r2 = *(u64 *)(r10 - 16); r0 = r1; 16752 * r1 = *(u64 *)(r10 - 8); r0 += r2; 16753 * r0 = r1; exit; 16754 * r0 += r2; 16755 * exit; 16756 * 16757 * The purpose of mark_fastcall_pattern_for_call is to: 16758 * - look for such patterns; 16759 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 16760 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 16761 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 16762 * at which bpf_fastcall spill/fill stack slots start; 16763 * - update env->subprog_info[*]->keep_fastcall_stack. 16764 * 16765 * The .fastcall_pattern and .fastcall_stack_off are used by 16766 * check_fastcall_stack_contract() to check if every stack access to 16767 * fastcall spill/fill stack slot originates from spill/fill 16768 * instructions, members of fastcall patterns. 16769 * 16770 * If such condition holds true for a subprogram, fastcall patterns could 16771 * be rewritten by remove_fastcall_spills_fills(). 16772 * Otherwise bpf_fastcall patterns are not changed in the subprogram 16773 * (code, presumably, generated by an older clang version). 16774 * 16775 * For example, it is *not* safe to remove spill/fill below: 16776 * 16777 * r1 = 1; 16778 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16779 * call %[to_be_inlined] --> call %[to_be_inlined] 16780 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 16781 * r0 = *(u64 *)(r10 - 8); r0 += r1; 16782 * r0 += r1; exit; 16783 * exit; 16784 */ 16785 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 16786 struct bpf_subprog_info *subprog, 16787 int insn_idx, s16 lowest_off) 16788 { 16789 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 16790 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 16791 u32 clobbered_regs_mask; 16792 struct bpf_call_summary cs; 16793 u32 expected_regs_mask; 16794 s16 off; 16795 int i; 16796 16797 if (!bpf_get_call_summary(env, call, &cs)) 16798 return; 16799 16800 /* A bitmask specifying which caller saved registers are clobbered 16801 * by a call to a helper/kfunc *as if* this helper/kfunc follows 16802 * bpf_fastcall contract: 16803 * - includes R0 if function is non-void; 16804 * - includes R1-R5 if corresponding parameter has is described 16805 * in the function prototype. 16806 */ 16807 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 16808 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 16809 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 16810 16811 /* match pairs of form: 16812 * 16813 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 16814 * ... 16815 * call %[to_be_inlined] 16816 * ... 16817 * rX = *(u64 *)(r10 - Y) 16818 */ 16819 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 16820 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 16821 break; 16822 stx = &insns[insn_idx - i]; 16823 ldx = &insns[insn_idx + i]; 16824 /* must be a stack spill/fill pair */ 16825 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 16826 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 16827 stx->dst_reg != BPF_REG_10 || 16828 ldx->src_reg != BPF_REG_10) 16829 break; 16830 /* must be a spill/fill for the same reg */ 16831 if (stx->src_reg != ldx->dst_reg) 16832 break; 16833 /* must be one of the previously unseen registers */ 16834 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 16835 break; 16836 /* must be a spill/fill for the same expected offset, 16837 * no need to check offset alignment, BPF_DW stack access 16838 * is always 8-byte aligned. 16839 */ 16840 if (stx->off != off || ldx->off != off) 16841 break; 16842 expected_regs_mask &= ~BIT(stx->src_reg); 16843 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 16844 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 16845 } 16846 if (i == 1) 16847 return; 16848 16849 /* Conditionally set 'fastcall_spills_num' to allow forward 16850 * compatibility when more helper functions are marked as 16851 * bpf_fastcall at compile time than current kernel supports, e.g: 16852 * 16853 * 1: *(u64 *)(r10 - 8) = r1 16854 * 2: call A ;; assume A is bpf_fastcall for current kernel 16855 * 3: r1 = *(u64 *)(r10 - 8) 16856 * 4: *(u64 *)(r10 - 8) = r1 16857 * 5: call B ;; assume B is not bpf_fastcall for current kernel 16858 * 6: r1 = *(u64 *)(r10 - 8) 16859 * 16860 * There is no need to block bpf_fastcall rewrite for such program. 16861 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 16862 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 16863 * does not remove spill/fill pair {4,6}. 16864 */ 16865 if (cs.fastcall) 16866 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 16867 else 16868 subprog->keep_fastcall_stack = 1; 16869 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 16870 } 16871 16872 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 16873 { 16874 struct bpf_subprog_info *subprog = env->subprog_info; 16875 struct bpf_insn *insn; 16876 s16 lowest_off; 16877 int s, i; 16878 16879 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 16880 /* find lowest stack spill offset used in this subprog */ 16881 lowest_off = 0; 16882 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16883 insn = env->prog->insnsi + i; 16884 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 16885 insn->dst_reg != BPF_REG_10) 16886 continue; 16887 lowest_off = min(lowest_off, insn->off); 16888 } 16889 /* use this offset to find fastcall patterns */ 16890 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16891 insn = env->prog->insnsi + i; 16892 if (insn->code != (BPF_JMP | BPF_CALL)) 16893 continue; 16894 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 16895 } 16896 } 16897 return 0; 16898 } 16899 16900 static void adjust_btf_func(struct bpf_verifier_env *env) 16901 { 16902 struct bpf_prog_aux *aux = env->prog->aux; 16903 int i; 16904 16905 if (!aux->func_info) 16906 return; 16907 16908 /* func_info is not available for hidden subprogs */ 16909 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16910 aux->func_info[i].insn_off = env->subprog_info[i].start; 16911 } 16912 16913 /* Find id in idset and increment its count, or add new entry */ 16914 static void idset_cnt_inc(struct bpf_idset *idset, u32 id) 16915 { 16916 u32 i; 16917 16918 for (i = 0; i < idset->num_ids; i++) { 16919 if (idset->entries[i].id == id) { 16920 idset->entries[i].cnt++; 16921 return; 16922 } 16923 } 16924 /* New id */ 16925 if (idset->num_ids < BPF_ID_MAP_SIZE) { 16926 idset->entries[idset->num_ids].id = id; 16927 idset->entries[idset->num_ids].cnt = 1; 16928 idset->num_ids++; 16929 } 16930 } 16931 16932 /* Find id in idset and return its count, or 0 if not found */ 16933 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id) 16934 { 16935 u32 i; 16936 16937 for (i = 0; i < idset->num_ids; i++) { 16938 if (idset->entries[i].id == id) 16939 return idset->entries[i].cnt; 16940 } 16941 return 0; 16942 } 16943 16944 /* 16945 * Clear singular scalar ids in a state. 16946 * A register with a non-zero id is called singular if no other register shares 16947 * the same base id. Such registers can be treated as independent (id=0). 16948 */ 16949 void bpf_clear_singular_ids(struct bpf_verifier_env *env, 16950 struct bpf_verifier_state *st) 16951 { 16952 struct bpf_idset *idset = &env->idset_scratch; 16953 struct bpf_func_state *func; 16954 struct bpf_reg_state *reg; 16955 16956 idset->num_ids = 0; 16957 16958 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16959 if (reg->type != SCALAR_VALUE) 16960 continue; 16961 if (!reg->id) 16962 continue; 16963 idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST); 16964 })); 16965 16966 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16967 if (reg->type != SCALAR_VALUE) 16968 continue; 16969 if (!reg->id) 16970 continue; 16971 if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1) 16972 clear_scalar_id(reg); 16973 })); 16974 } 16975 16976 /* Return true if it's OK to have the same insn return a different type. */ 16977 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16978 { 16979 switch (base_type(type)) { 16980 case PTR_TO_CTX: 16981 case PTR_TO_SOCKET: 16982 case PTR_TO_SOCK_COMMON: 16983 case PTR_TO_TCP_SOCK: 16984 case PTR_TO_XDP_SOCK: 16985 case PTR_TO_BTF_ID: 16986 case PTR_TO_ARENA: 16987 return false; 16988 default: 16989 return true; 16990 } 16991 } 16992 16993 /* If an instruction was previously used with particular pointer types, then we 16994 * need to be careful to avoid cases such as the below, where it may be ok 16995 * for one branch accessing the pointer, but not ok for the other branch: 16996 * 16997 * R1 = sock_ptr 16998 * goto X; 16999 * ... 17000 * R1 = some_other_valid_ptr; 17001 * goto X; 17002 * ... 17003 * R2 = *(u32 *)(R1 + 0); 17004 */ 17005 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17006 { 17007 return src != prev && (!reg_type_mismatch_ok(src) || 17008 !reg_type_mismatch_ok(prev)); 17009 } 17010 17011 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type) 17012 { 17013 switch (base_type(type)) { 17014 case PTR_TO_MEM: 17015 case PTR_TO_BTF_ID: 17016 return true; 17017 default: 17018 return false; 17019 } 17020 } 17021 17022 static bool is_ptr_to_mem(enum bpf_reg_type type) 17023 { 17024 return base_type(type) == PTR_TO_MEM; 17025 } 17026 17027 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17028 bool allow_trust_mismatch) 17029 { 17030 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17031 enum bpf_reg_type merged_type; 17032 17033 if (*prev_type == NOT_INIT) { 17034 /* Saw a valid insn 17035 * dst_reg = *(u32 *)(src_reg + off) 17036 * save type to validate intersecting paths 17037 */ 17038 *prev_type = type; 17039 } else if (reg_type_mismatch(type, *prev_type)) { 17040 /* Abuser program is trying to use the same insn 17041 * dst_reg = *(u32*) (src_reg + off) 17042 * with different pointer types: 17043 * src_reg == ctx in one branch and 17044 * src_reg == stack|map in some other branch. 17045 * Reject it. 17046 */ 17047 if (allow_trust_mismatch && 17048 is_ptr_to_mem_or_btf_id(type) && 17049 is_ptr_to_mem_or_btf_id(*prev_type)) { 17050 /* 17051 * Have to support a use case when one path through 17052 * the program yields TRUSTED pointer while another 17053 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17054 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17055 * Same behavior of MEM_RDONLY flag. 17056 */ 17057 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type)) 17058 merged_type = PTR_TO_MEM; 17059 else 17060 merged_type = PTR_TO_BTF_ID; 17061 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED)) 17062 merged_type |= PTR_UNTRUSTED; 17063 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY)) 17064 merged_type |= MEM_RDONLY; 17065 *prev_type = merged_type; 17066 } else { 17067 verbose(env, "same insn cannot be used with different pointers\n"); 17068 return -EINVAL; 17069 } 17070 } 17071 17072 return 0; 17073 } 17074 17075 enum { 17076 PROCESS_BPF_EXIT = 1, 17077 INSN_IDX_UPDATED = 2, 17078 }; 17079 17080 static int process_bpf_exit_full(struct bpf_verifier_env *env, 17081 bool *do_print_state, 17082 bool exception_exit) 17083 { 17084 struct bpf_func_state *cur_frame = cur_func(env); 17085 17086 /* We must do check_reference_leak here before 17087 * prepare_func_exit to handle the case when 17088 * state->curframe > 0, it may be a callback function, 17089 * for which reference_state must match caller reference 17090 * state when it exits. 17091 */ 17092 int err = check_resource_leak(env, exception_exit, 17093 exception_exit || !env->cur_state->curframe, 17094 exception_exit ? "bpf_throw" : 17095 "BPF_EXIT instruction in main prog"); 17096 if (err) 17097 return err; 17098 17099 /* The side effect of the prepare_func_exit which is 17100 * being skipped is that it frees bpf_func_state. 17101 * Typically, process_bpf_exit will only be hit with 17102 * outermost exit. copy_verifier_state in pop_stack will 17103 * handle freeing of any extra bpf_func_state left over 17104 * from not processing all nested function exits. We 17105 * also skip return code checks as they are not needed 17106 * for exceptional exits. 17107 */ 17108 if (exception_exit) 17109 return PROCESS_BPF_EXIT; 17110 17111 if (env->cur_state->curframe) { 17112 /* exit from nested function */ 17113 err = prepare_func_exit(env, &env->insn_idx); 17114 if (err) 17115 return err; 17116 *do_print_state = true; 17117 return INSN_IDX_UPDATED; 17118 } 17119 17120 /* 17121 * Return from a regular global subprogram differs from return 17122 * from the main program or async/exception callback. 17123 * Main program exit implies return code restrictions 17124 * that depend on program type. 17125 * Exit from exception callback is equivalent to main program exit. 17126 * Exit from async callback implies return code restrictions 17127 * that depend on async scheduling mechanism. 17128 */ 17129 if (cur_frame->subprogno && 17130 !cur_frame->in_async_callback_fn && 17131 !cur_frame->in_exception_callback_fn) 17132 err = check_global_subprog_return_code(env); 17133 else 17134 err = check_return_code(env, BPF_REG_0, "R0"); 17135 if (err) 17136 return err; 17137 return PROCESS_BPF_EXIT; 17138 } 17139 17140 static int indirect_jump_min_max_index(struct bpf_verifier_env *env, 17141 int regno, 17142 struct bpf_map *map, 17143 u32 *pmin_index, u32 *pmax_index) 17144 { 17145 struct bpf_reg_state *reg = reg_state(env, regno); 17146 u64 min_index = reg_umin(reg); 17147 u64 max_index = reg_umax(reg); 17148 const u32 size = 8; 17149 17150 if (min_index > (u64) U32_MAX * size) { 17151 verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg)); 17152 return -ERANGE; 17153 } 17154 if (max_index > (u64) U32_MAX * size) { 17155 verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg)); 17156 return -ERANGE; 17157 } 17158 17159 min_index /= size; 17160 max_index /= size; 17161 17162 if (max_index >= map->max_entries) { 17163 verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n", 17164 regno, min_index, max_index, map->max_entries); 17165 return -EINVAL; 17166 } 17167 17168 *pmin_index = min_index; 17169 *pmax_index = max_index; 17170 return 0; 17171 } 17172 17173 /* gotox *dst_reg */ 17174 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn) 17175 { 17176 struct bpf_verifier_state *other_branch; 17177 struct bpf_reg_state *dst_reg; 17178 struct bpf_map *map; 17179 u32 min_index, max_index; 17180 int err = 0; 17181 int n; 17182 int i; 17183 17184 dst_reg = reg_state(env, insn->dst_reg); 17185 if (dst_reg->type != PTR_TO_INSN) { 17186 verbose(env, "R%d has type %s, expected PTR_TO_INSN\n", 17187 insn->dst_reg, reg_type_str(env, dst_reg->type)); 17188 return -EINVAL; 17189 } 17190 17191 map = dst_reg->map_ptr; 17192 if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg)) 17193 return -EFAULT; 17194 17195 if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env, 17196 "R%d has incorrect map type %d", insn->dst_reg, map->map_type)) 17197 return -EFAULT; 17198 17199 err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index); 17200 if (err) 17201 return err; 17202 17203 /* Ensure that the buffer is large enough */ 17204 if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) { 17205 env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf, 17206 max_index - min_index + 1); 17207 if (!env->gotox_tmp_buf) 17208 return -ENOMEM; 17209 } 17210 17211 n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items); 17212 if (n < 0) 17213 return n; 17214 if (n == 0) { 17215 verbose(env, "register R%d doesn't point to any offset in map id=%d\n", 17216 insn->dst_reg, map->id); 17217 return -EINVAL; 17218 } 17219 17220 for (i = 0; i < n - 1; i++) { 17221 mark_indirect_target(env, env->gotox_tmp_buf->items[i]); 17222 other_branch = push_stack(env, env->gotox_tmp_buf->items[i], 17223 env->insn_idx, env->cur_state->speculative); 17224 if (IS_ERR(other_branch)) 17225 return PTR_ERR(other_branch); 17226 } 17227 env->insn_idx = env->gotox_tmp_buf->items[n-1]; 17228 mark_indirect_target(env, env->insn_idx); 17229 return INSN_IDX_UPDATED; 17230 } 17231 17232 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 17233 { 17234 int err; 17235 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 17236 u8 class = BPF_CLASS(insn->code); 17237 17238 switch (class) { 17239 case BPF_ALU: 17240 case BPF_ALU64: 17241 return check_alu_op(env, insn); 17242 17243 case BPF_LDX: 17244 return check_load_mem(env, insn, false, 17245 BPF_MODE(insn->code) == BPF_MEMSX, 17246 true, "ldx"); 17247 17248 case BPF_STX: 17249 if (BPF_MODE(insn->code) == BPF_ATOMIC) 17250 return check_atomic(env, insn); 17251 return check_store_reg(env, insn, false); 17252 17253 case BPF_ST: { 17254 /* Handle stack arg write (store immediate) */ 17255 if (is_stack_arg_st(insn)) { 17256 struct bpf_verifier_state *vstate = env->cur_state; 17257 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 17258 17259 return check_stack_arg_write(env, state, insn->off, NULL); 17260 } 17261 17262 enum bpf_reg_type dst_reg_type; 17263 17264 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17265 if (err) 17266 return err; 17267 17268 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 17269 17270 err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg, argno_from_reg(insn->dst_reg), 17271 insn->off, BPF_SIZE(insn->code), 17272 BPF_WRITE, -1, false, false); 17273 if (err) 17274 return err; 17275 17276 return save_aux_ptr_type(env, dst_reg_type, false); 17277 } 17278 case BPF_JMP: 17279 case BPF_JMP32: { 17280 u8 opcode = BPF_OP(insn->code); 17281 17282 env->jmps_processed++; 17283 if (opcode == BPF_CALL) { 17284 if (env->cur_state->active_locks) { 17285 if ((insn->src_reg == BPF_REG_0 && 17286 insn->imm != BPF_FUNC_spin_unlock && 17287 insn->imm != BPF_FUNC_kptr_xchg) || 17288 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17289 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) { 17290 verbose(env, 17291 "function calls are not allowed while holding a lock\n"); 17292 return -EINVAL; 17293 } 17294 } 17295 mark_reg_scratched(env, BPF_REG_0); 17296 if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno])) 17297 cur_func(env)->no_stack_arg_load = true; 17298 if (insn->src_reg == BPF_PSEUDO_CALL) 17299 return check_func_call(env, insn, &env->insn_idx); 17300 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17301 return check_kfunc_call(env, insn, &env->insn_idx); 17302 return check_helper_call(env, insn, &env->insn_idx); 17303 } else if (opcode == BPF_JA) { 17304 if (BPF_SRC(insn->code) == BPF_X) 17305 return check_indirect_jump(env, insn); 17306 17307 if (class == BPF_JMP) 17308 env->insn_idx += insn->off + 1; 17309 else 17310 env->insn_idx += insn->imm + 1; 17311 return INSN_IDX_UPDATED; 17312 } else if (opcode == BPF_EXIT) { 17313 return process_bpf_exit_full(env, do_print_state, false); 17314 } 17315 return check_cond_jmp_op(env, insn, &env->insn_idx); 17316 } 17317 case BPF_LD: { 17318 u8 mode = BPF_MODE(insn->code); 17319 17320 if (mode == BPF_ABS || mode == BPF_IND) 17321 return check_ld_abs(env, insn); 17322 17323 if (mode == BPF_IMM) { 17324 err = check_ld_imm(env, insn); 17325 if (err) 17326 return err; 17327 17328 env->insn_idx++; 17329 sanitize_mark_insn_seen(env); 17330 } 17331 return 0; 17332 } 17333 } 17334 /* all class values are handled above. silence compiler warning */ 17335 return -EFAULT; 17336 } 17337 17338 static int do_check(struct bpf_verifier_env *env) 17339 { 17340 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17341 struct bpf_verifier_state *state = env->cur_state; 17342 struct bpf_insn *insns = env->prog->insnsi; 17343 int insn_cnt = env->prog->len; 17344 bool do_print_state = false; 17345 int prev_insn_idx = -1; 17346 17347 for (;;) { 17348 struct bpf_insn *insn; 17349 struct bpf_insn_aux_data *insn_aux; 17350 int err; 17351 17352 /* reset current history entry on each new instruction */ 17353 env->cur_hist_ent = NULL; 17354 17355 env->prev_insn_idx = prev_insn_idx; 17356 if (env->insn_idx >= insn_cnt) { 17357 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17358 env->insn_idx, insn_cnt); 17359 return -EFAULT; 17360 } 17361 17362 insn = &insns[env->insn_idx]; 17363 insn_aux = &env->insn_aux_data[env->insn_idx]; 17364 17365 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17366 verbose(env, 17367 "BPF program is too large. Processed %d insn\n", 17368 env->insn_processed); 17369 return -E2BIG; 17370 } 17371 17372 state->last_insn_idx = env->prev_insn_idx; 17373 state->insn_idx = env->insn_idx; 17374 17375 if (bpf_is_prune_point(env, env->insn_idx)) { 17376 err = bpf_is_state_visited(env, env->insn_idx); 17377 if (err < 0) 17378 return err; 17379 if (err == 1) { 17380 /* found equivalent state, can prune the search */ 17381 if (env->log.level & BPF_LOG_LEVEL) { 17382 if (do_print_state) 17383 verbose(env, "\nfrom %d to %d%s: safe\n", 17384 env->prev_insn_idx, env->insn_idx, 17385 env->cur_state->speculative ? 17386 " (speculative execution)" : ""); 17387 else 17388 verbose(env, "%d: safe\n", env->insn_idx); 17389 } 17390 goto process_bpf_exit; 17391 } 17392 } 17393 17394 if (bpf_is_jmp_point(env, env->insn_idx)) { 17395 err = bpf_push_jmp_history(env, state, 0, 0, 0, 0); 17396 if (err) 17397 return err; 17398 } 17399 17400 if (signal_pending(current)) 17401 return -EAGAIN; 17402 17403 if (need_resched()) 17404 cond_resched(); 17405 17406 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17407 verbose(env, "\nfrom %d to %d%s:", 17408 env->prev_insn_idx, env->insn_idx, 17409 env->cur_state->speculative ? 17410 " (speculative execution)" : ""); 17411 print_verifier_state(env, state, state->curframe, true); 17412 do_print_state = false; 17413 } 17414 17415 if (env->log.level & BPF_LOG_LEVEL) { 17416 if (verifier_state_scratched(env)) 17417 print_insn_state(env, state, state->curframe); 17418 17419 verbose_linfo(env, env->insn_idx, "; "); 17420 env->prev_log_pos = env->log.end_pos; 17421 verbose(env, "%d: ", env->insn_idx); 17422 bpf_verbose_insn(env, insn); 17423 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17424 env->prev_log_pos = env->log.end_pos; 17425 } 17426 17427 if (bpf_prog_is_offloaded(env->prog->aux)) { 17428 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17429 env->prev_insn_idx); 17430 if (err) 17431 return err; 17432 } 17433 17434 sanitize_mark_insn_seen(env); 17435 prev_insn_idx = env->insn_idx; 17436 17437 /* Sanity check: precomputed constants must match verifier state */ 17438 if (!state->speculative && insn_aux->const_reg_mask) { 17439 struct bpf_reg_state *regs = cur_regs(env); 17440 u16 mask = insn_aux->const_reg_mask; 17441 17442 for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) { 17443 u32 cval = insn_aux->const_reg_vals[r]; 17444 17445 if (!(mask & BIT(r))) 17446 continue; 17447 if (regs[r].type != SCALAR_VALUE) 17448 continue; 17449 if (!tnum_is_const(regs[r].var_off)) 17450 continue; 17451 if (verifier_bug_if((u32)regs[r].var_off.value != cval, 17452 env, "const R%d: %u != %llu", 17453 r, cval, regs[r].var_off.value)) 17454 return -EFAULT; 17455 } 17456 } 17457 17458 /* Reduce verification complexity by stopping speculative path 17459 * verification when a nospec is encountered. 17460 */ 17461 if (state->speculative && insn_aux->nospec) 17462 goto process_bpf_exit; 17463 17464 err = do_check_insn(env, &do_print_state); 17465 if (error_recoverable_with_nospec(err) && state->speculative) { 17466 /* Prevent this speculative path from ever reaching the 17467 * insn that would have been unsafe to execute. 17468 */ 17469 insn_aux->nospec = true; 17470 /* If it was an ADD/SUB insn, potentially remove any 17471 * markings for alu sanitization. 17472 */ 17473 insn_aux->alu_state = 0; 17474 goto process_bpf_exit; 17475 } else if (err < 0) { 17476 return err; 17477 } else if (err == PROCESS_BPF_EXIT) { 17478 goto process_bpf_exit; 17479 } else if (err == INSN_IDX_UPDATED) { 17480 } else if (err == 0) { 17481 env->insn_idx++; 17482 } 17483 17484 if (state->speculative && insn_aux->nospec_result) { 17485 /* If we are on a path that performed a jump-op, this 17486 * may skip a nospec patched-in after the jump. This can 17487 * currently never happen because nospec_result is only 17488 * used for the write-ops 17489 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper 17490 * calls. These must never skip the following insn 17491 * (i.e., bpf_insn_successors()'s opcode_info.can_jump 17492 * is false). Still, add a warning to document this in 17493 * case nospec_result is used elsewhere in the future. 17494 * 17495 * All non-branch instructions have a single 17496 * fall-through edge. For these, nospec_result should 17497 * already work. 17498 */ 17499 if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP || 17500 BPF_CLASS(insn->code) == BPF_JMP32) && 17501 BPF_OP(insn->code) != BPF_CALL, env, 17502 "speculation barrier after jump instruction may not have the desired effect")) 17503 return -EFAULT; 17504 process_bpf_exit: 17505 mark_verifier_state_scratched(env); 17506 err = bpf_update_branch_counts(env, env->cur_state); 17507 if (err) 17508 return err; 17509 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 17510 pop_log); 17511 if (err < 0) { 17512 if (err != -ENOENT) 17513 return err; 17514 break; 17515 } else { 17516 do_print_state = true; 17517 continue; 17518 } 17519 } 17520 } 17521 17522 return 0; 17523 } 17524 17525 static int find_btf_percpu_datasec(struct btf *btf) 17526 { 17527 const struct btf_type *t; 17528 const char *tname; 17529 int i, n; 17530 17531 /* 17532 * Both vmlinux and module each have their own ".data..percpu" 17533 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17534 * types to look at only module's own BTF types. 17535 */ 17536 n = btf_nr_types(btf); 17537 for (i = btf_named_start_id(btf, true); i < n; i++) { 17538 t = btf_type_by_id(btf, i); 17539 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17540 continue; 17541 17542 tname = btf_name_by_offset(btf, t->name_off); 17543 if (!strcmp(tname, ".data..percpu")) 17544 return i; 17545 } 17546 17547 return -ENOENT; 17548 } 17549 17550 /* 17551 * Add btf to the env->used_btfs array. If needed, refcount the 17552 * corresponding kernel module. To simplify caller's logic 17553 * in case of error or if btf was added before the function 17554 * decreases the btf refcount. 17555 */ 17556 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 17557 { 17558 struct btf_mod_pair *btf_mod; 17559 int ret = 0; 17560 int i; 17561 17562 /* check whether we recorded this BTF (and maybe module) already */ 17563 for (i = 0; i < env->used_btf_cnt; i++) 17564 if (env->used_btfs[i].btf == btf) 17565 goto ret_put; 17566 17567 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17568 verbose(env, "The total number of btfs per program has reached the limit of %u\n", 17569 MAX_USED_BTFS); 17570 ret = -E2BIG; 17571 goto ret_put; 17572 } 17573 17574 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17575 btf_mod->btf = btf; 17576 btf_mod->module = NULL; 17577 17578 /* if we reference variables from kernel module, bump its refcount */ 17579 if (btf_is_module(btf)) { 17580 btf_mod->module = btf_try_get_module(btf); 17581 if (!btf_mod->module) { 17582 ret = -ENXIO; 17583 goto ret_put; 17584 } 17585 } 17586 17587 env->used_btf_cnt++; 17588 return 0; 17589 17590 ret_put: 17591 /* Either error or this BTF was already added */ 17592 btf_put(btf); 17593 return ret; 17594 } 17595 17596 /* replace pseudo btf_id with kernel symbol address */ 17597 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 17598 struct bpf_insn *insn, 17599 struct bpf_insn_aux_data *aux, 17600 struct btf *btf) 17601 { 17602 const struct btf_var_secinfo *vsi; 17603 const struct btf_type *datasec; 17604 const struct btf_type *t; 17605 const char *sym_name; 17606 bool percpu = false; 17607 u32 type, id = insn->imm; 17608 s32 datasec_id; 17609 u64 addr; 17610 int i; 17611 17612 t = btf_type_by_id(btf, id); 17613 if (!t) { 17614 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17615 return -ENOENT; 17616 } 17617 17618 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17619 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17620 return -EINVAL; 17621 } 17622 17623 sym_name = btf_name_by_offset(btf, t->name_off); 17624 addr = kallsyms_lookup_name(sym_name); 17625 if (!addr) { 17626 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17627 sym_name); 17628 return -ENOENT; 17629 } 17630 insn[0].imm = (u32)addr; 17631 insn[1].imm = addr >> 32; 17632 17633 if (btf_type_is_func(t)) { 17634 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17635 aux->btf_var.mem_size = 0; 17636 return 0; 17637 } 17638 17639 datasec_id = find_btf_percpu_datasec(btf); 17640 if (datasec_id > 0) { 17641 datasec = btf_type_by_id(btf, datasec_id); 17642 for_each_vsi(i, datasec, vsi) { 17643 if (vsi->type == id) { 17644 percpu = true; 17645 break; 17646 } 17647 } 17648 } 17649 17650 type = t->type; 17651 t = btf_type_skip_modifiers(btf, type, NULL); 17652 if (percpu) { 17653 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17654 aux->btf_var.btf = btf; 17655 aux->btf_var.btf_id = type; 17656 } else if (!btf_type_is_struct(t)) { 17657 const struct btf_type *ret; 17658 const char *tname; 17659 u32 tsize; 17660 17661 /* resolve the type size of ksym. */ 17662 ret = btf_resolve_size(btf, t, &tsize); 17663 if (IS_ERR(ret)) { 17664 tname = btf_name_by_offset(btf, t->name_off); 17665 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17666 tname, PTR_ERR(ret)); 17667 return -EINVAL; 17668 } 17669 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17670 aux->btf_var.mem_size = tsize; 17671 } else { 17672 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17673 aux->btf_var.btf = btf; 17674 aux->btf_var.btf_id = type; 17675 } 17676 17677 return 0; 17678 } 17679 17680 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17681 struct bpf_insn *insn, 17682 struct bpf_insn_aux_data *aux) 17683 { 17684 struct btf *btf; 17685 int btf_fd; 17686 int err; 17687 17688 btf_fd = insn[1].imm; 17689 if (btf_fd) { 17690 btf = btf_get_by_fd(btf_fd); 17691 if (IS_ERR(btf)) { 17692 verbose(env, "invalid module BTF object FD specified.\n"); 17693 return -EINVAL; 17694 } 17695 } else { 17696 if (!btf_vmlinux) { 17697 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17698 return -EINVAL; 17699 } 17700 btf_get(btf_vmlinux); 17701 btf = btf_vmlinux; 17702 } 17703 17704 err = __check_pseudo_btf_id(env, insn, aux, btf); 17705 if (err) { 17706 btf_put(btf); 17707 return err; 17708 } 17709 17710 return __add_used_btf(env, btf); 17711 } 17712 17713 static bool is_tracing_prog_type(enum bpf_prog_type type) 17714 { 17715 switch (type) { 17716 case BPF_PROG_TYPE_KPROBE: 17717 case BPF_PROG_TYPE_TRACEPOINT: 17718 case BPF_PROG_TYPE_PERF_EVENT: 17719 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17720 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17721 return true; 17722 default: 17723 return false; 17724 } 17725 } 17726 17727 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17728 { 17729 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17730 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17731 } 17732 17733 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17734 struct bpf_map *map, 17735 struct bpf_prog *prog) 17736 17737 { 17738 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17739 17740 if (map->excl_prog_sha && 17741 memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) { 17742 verbose(env, "program's hash doesn't match map's excl_prog_hash\n"); 17743 return -EACCES; 17744 } 17745 17746 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17747 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17748 if (is_tracing_prog_type(prog_type)) { 17749 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17750 return -EINVAL; 17751 } 17752 } 17753 17754 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 17755 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17756 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17757 return -EINVAL; 17758 } 17759 17760 if (is_tracing_prog_type(prog_type)) { 17761 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17762 return -EINVAL; 17763 } 17764 } 17765 17766 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17767 !bpf_offload_prog_map_match(prog, map)) { 17768 verbose(env, "offload device mismatch between prog and map\n"); 17769 return -EINVAL; 17770 } 17771 17772 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17773 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17774 return -EINVAL; 17775 } 17776 17777 if (prog->sleepable) 17778 switch (map->map_type) { 17779 case BPF_MAP_TYPE_HASH: 17780 case BPF_MAP_TYPE_RHASH: 17781 case BPF_MAP_TYPE_LRU_HASH: 17782 case BPF_MAP_TYPE_ARRAY: 17783 case BPF_MAP_TYPE_PERCPU_HASH: 17784 case BPF_MAP_TYPE_PERCPU_ARRAY: 17785 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17786 case BPF_MAP_TYPE_LPM_TRIE: 17787 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17788 case BPF_MAP_TYPE_HASH_OF_MAPS: 17789 case BPF_MAP_TYPE_RINGBUF: 17790 case BPF_MAP_TYPE_USER_RINGBUF: 17791 case BPF_MAP_TYPE_INODE_STORAGE: 17792 case BPF_MAP_TYPE_SK_STORAGE: 17793 case BPF_MAP_TYPE_TASK_STORAGE: 17794 case BPF_MAP_TYPE_CGRP_STORAGE: 17795 case BPF_MAP_TYPE_QUEUE: 17796 case BPF_MAP_TYPE_STACK: 17797 case BPF_MAP_TYPE_ARENA: 17798 case BPF_MAP_TYPE_INSN_ARRAY: 17799 case BPF_MAP_TYPE_PROG_ARRAY: 17800 break; 17801 default: 17802 verbose(env, 17803 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17804 return -EINVAL; 17805 } 17806 17807 if (bpf_map_is_cgroup_storage(map) && 17808 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17809 verbose(env, "only one cgroup storage of each type is allowed\n"); 17810 return -EBUSY; 17811 } 17812 17813 if (map->map_type == BPF_MAP_TYPE_ARENA) { 17814 if (env->prog->aux->arena) { 17815 verbose(env, "Only one arena per program\n"); 17816 return -EBUSY; 17817 } 17818 if (!env->allow_ptr_leaks || !env->bpf_capable) { 17819 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 17820 return -EPERM; 17821 } 17822 if (!env->prog->jit_requested) { 17823 verbose(env, "JIT is required to use arena\n"); 17824 return -EOPNOTSUPP; 17825 } 17826 if (!bpf_jit_supports_arena()) { 17827 verbose(env, "JIT doesn't support arena\n"); 17828 return -EOPNOTSUPP; 17829 } 17830 env->prog->aux->arena = (void *)map; 17831 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 17832 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 17833 return -EINVAL; 17834 } 17835 } 17836 17837 return 0; 17838 } 17839 17840 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 17841 { 17842 int i, err; 17843 17844 /* check whether we recorded this map already */ 17845 for (i = 0; i < env->used_map_cnt; i++) 17846 if (env->used_maps[i] == map) 17847 return i; 17848 17849 if (env->used_map_cnt >= MAX_USED_MAPS) { 17850 verbose(env, "The total number of maps per program has reached the limit of %u\n", 17851 MAX_USED_MAPS); 17852 return -E2BIG; 17853 } 17854 17855 err = check_map_prog_compatibility(env, map, env->prog); 17856 if (err) 17857 return err; 17858 17859 if (env->prog->sleepable) 17860 atomic64_inc(&map->sleepable_refcnt); 17861 17862 /* hold the map. If the program is rejected by verifier, 17863 * the map will be released by release_maps() or it 17864 * will be used by the valid program until it's unloaded 17865 * and all maps are released in bpf_free_used_maps() 17866 */ 17867 bpf_map_inc(map); 17868 17869 env->used_maps[env->used_map_cnt++] = map; 17870 17871 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 17872 err = bpf_insn_array_init(map, env->prog); 17873 if (err) { 17874 verbose(env, "Failed to properly initialize insn array\n"); 17875 return err; 17876 } 17877 env->insn_array_maps[env->insn_array_map_cnt++] = map; 17878 } 17879 17880 return env->used_map_cnt - 1; 17881 } 17882 17883 /* Add map behind fd to used maps list, if it's not already there, and return 17884 * its index. 17885 * Returns <0 on error, or >= 0 index, on success. 17886 */ 17887 static int add_used_map(struct bpf_verifier_env *env, int fd) 17888 { 17889 struct bpf_map *map; 17890 CLASS(fd, f)(fd); 17891 17892 map = __bpf_map_get(f); 17893 if (IS_ERR(map)) { 17894 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 17895 return PTR_ERR(map); 17896 } 17897 17898 return __add_used_map(env, map); 17899 } 17900 17901 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17902 { 17903 u8 class = BPF_CLASS(insn->code); 17904 u8 opcode = BPF_OP(insn->code); 17905 17906 switch (opcode) { 17907 case BPF_NEG: 17908 if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 || 17909 insn->off != 0 || insn->imm != 0) { 17910 verbose(env, "BPF_NEG uses reserved fields\n"); 17911 return -EINVAL; 17912 } 17913 return 0; 17914 case BPF_END: 17915 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 17916 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 17917 (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) { 17918 verbose(env, "BPF_END uses reserved fields\n"); 17919 return -EINVAL; 17920 } 17921 return 0; 17922 case BPF_MOV: 17923 if (BPF_SRC(insn->code) == BPF_X) { 17924 if (class == BPF_ALU) { 17925 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 17926 insn->imm) { 17927 verbose(env, "BPF_MOV uses reserved fields\n"); 17928 return -EINVAL; 17929 } 17930 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 17931 if (insn->imm != 1 && insn->imm != 1u << 16) { 17932 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 17933 return -EINVAL; 17934 } 17935 } else if ((insn->off != 0 && insn->off != 8 && 17936 insn->off != 16 && insn->off != 32) || insn->imm) { 17937 verbose(env, "BPF_MOV uses reserved fields\n"); 17938 return -EINVAL; 17939 } 17940 } else if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 17941 verbose(env, "BPF_MOV uses reserved fields\n"); 17942 return -EINVAL; 17943 } 17944 return 0; 17945 case BPF_ADD: 17946 case BPF_SUB: 17947 case BPF_AND: 17948 case BPF_OR: 17949 case BPF_XOR: 17950 case BPF_LSH: 17951 case BPF_RSH: 17952 case BPF_ARSH: 17953 case BPF_MUL: 17954 case BPF_DIV: 17955 case BPF_MOD: 17956 if (BPF_SRC(insn->code) == BPF_X) { 17957 if (insn->imm != 0 || (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 } else if (insn->src_reg != BPF_REG_0 || 17963 (insn->off != 0 && insn->off != 1) || 17964 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 17965 verbose(env, "BPF_ALU uses reserved fields\n"); 17966 return -EINVAL; 17967 } 17968 return 0; 17969 default: 17970 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 17971 return -EINVAL; 17972 } 17973 } 17974 17975 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17976 { 17977 u8 class = BPF_CLASS(insn->code); 17978 u8 opcode = BPF_OP(insn->code); 17979 17980 switch (opcode) { 17981 case BPF_CALL: 17982 if (BPF_SRC(insn->code) != BPF_K || 17983 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) || 17984 (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL && 17985 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17986 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 17987 verbose(env, "BPF_CALL uses reserved fields\n"); 17988 return -EINVAL; 17989 } 17990 return 0; 17991 case BPF_JA: 17992 if (BPF_SRC(insn->code) == BPF_X) { 17993 if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) { 17994 verbose(env, "BPF_JA|BPF_X uses reserved fields\n"); 17995 return -EINVAL; 17996 } 17997 } else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 17998 (class == BPF_JMP && insn->imm != 0) || 17999 (class == BPF_JMP32 && insn->off != 0)) { 18000 verbose(env, "BPF_JA uses reserved fields\n"); 18001 return -EINVAL; 18002 } 18003 return 0; 18004 case BPF_EXIT: 18005 if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || 18006 insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 18007 class == BPF_JMP32) { 18008 verbose(env, "BPF_EXIT uses reserved fields\n"); 18009 return -EINVAL; 18010 } 18011 return 0; 18012 case BPF_JCOND: 18013 if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO || 18014 insn->dst_reg || insn->imm) { 18015 verbose(env, "invalid may_goto imm %d\n", insn->imm); 18016 return -EINVAL; 18017 } 18018 return 0; 18019 default: 18020 if (BPF_SRC(insn->code) == BPF_X) { 18021 if (insn->imm != 0) { 18022 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18023 return -EINVAL; 18024 } 18025 } else if (insn->src_reg != BPF_REG_0) { 18026 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18027 return -EINVAL; 18028 } 18029 return 0; 18030 } 18031 } 18032 18033 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 18034 { 18035 switch (BPF_CLASS(insn->code)) { 18036 case BPF_ALU: 18037 case BPF_ALU64: 18038 return check_alu_fields(env, insn); 18039 case BPF_LDX: 18040 if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18041 insn->imm != 0) { 18042 verbose(env, "BPF_LDX uses reserved fields\n"); 18043 return -EINVAL; 18044 } 18045 return 0; 18046 case BPF_STX: 18047 if (BPF_MODE(insn->code) == BPF_ATOMIC) 18048 return 0; 18049 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 18050 verbose(env, "BPF_STX uses reserved fields\n"); 18051 return -EINVAL; 18052 } 18053 return 0; 18054 case BPF_ST: 18055 if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { 18056 verbose(env, "BPF_ST uses reserved fields\n"); 18057 return -EINVAL; 18058 } 18059 return 0; 18060 case BPF_JMP: 18061 case BPF_JMP32: 18062 return check_jmp_fields(env, insn); 18063 case BPF_LD: { 18064 u8 mode = BPF_MODE(insn->code); 18065 18066 if (mode == BPF_ABS || mode == BPF_IND) { 18067 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 18068 BPF_SIZE(insn->code) == BPF_DW || 18069 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 18070 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 18071 return -EINVAL; 18072 } 18073 } else if (mode != BPF_IMM) { 18074 verbose(env, "invalid BPF_LD mode\n"); 18075 return -EINVAL; 18076 } 18077 return 0; 18078 } 18079 default: 18080 verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code)); 18081 return -EINVAL; 18082 } 18083 } 18084 18085 /* 18086 * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions: 18087 * 18088 * 1. if it accesses map FD, replace it with actual map pointer. 18089 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18090 * 18091 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18092 */ 18093 static int check_and_resolve_insns(struct bpf_verifier_env *env) 18094 { 18095 struct bpf_insn *insn = env->prog->insnsi; 18096 int insn_cnt = env->prog->len; 18097 int i, err; 18098 18099 err = bpf_prog_calc_tag(env->prog); 18100 if (err) 18101 return err; 18102 18103 for (i = 0; i < insn_cnt; i++, insn++) { 18104 if (insn->dst_reg >= MAX_BPF_REG && 18105 !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) { 18106 verbose(env, "R%d is invalid\n", insn->dst_reg); 18107 return -EINVAL; 18108 } 18109 if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) { 18110 verbose(env, "R%d is invalid\n", insn->src_reg); 18111 return -EINVAL; 18112 } 18113 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18114 struct bpf_insn_aux_data *aux; 18115 struct bpf_map *map; 18116 int map_idx; 18117 u64 addr; 18118 u32 fd; 18119 18120 if (i == insn_cnt - 1 || insn[1].code != 0 || 18121 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18122 insn[1].off != 0) { 18123 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18124 return -EINVAL; 18125 } 18126 18127 if (insn[0].off != 0) { 18128 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 18129 return -EINVAL; 18130 } 18131 18132 if (insn[0].src_reg == 0) 18133 /* valid generic load 64-bit imm */ 18134 goto next_insn; 18135 18136 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18137 aux = &env->insn_aux_data[i]; 18138 err = check_pseudo_btf_id(env, insn, aux); 18139 if (err) 18140 return err; 18141 goto next_insn; 18142 } 18143 18144 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18145 aux = &env->insn_aux_data[i]; 18146 aux->ptr_type = PTR_TO_FUNC; 18147 goto next_insn; 18148 } 18149 18150 /* In final convert_pseudo_ld_imm64() step, this is 18151 * converted into regular 64-bit imm load insn. 18152 */ 18153 switch (insn[0].src_reg) { 18154 case BPF_PSEUDO_MAP_VALUE: 18155 case BPF_PSEUDO_MAP_IDX_VALUE: 18156 break; 18157 case BPF_PSEUDO_MAP_FD: 18158 case BPF_PSEUDO_MAP_IDX: 18159 if (insn[1].imm == 0) 18160 break; 18161 fallthrough; 18162 default: 18163 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18164 return -EINVAL; 18165 } 18166 18167 switch (insn[0].src_reg) { 18168 case BPF_PSEUDO_MAP_IDX_VALUE: 18169 case BPF_PSEUDO_MAP_IDX: 18170 if (bpfptr_is_null(env->fd_array)) { 18171 verbose(env, "fd_idx without fd_array is invalid\n"); 18172 return -EPROTO; 18173 } 18174 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18175 insn[0].imm * sizeof(fd), 18176 sizeof(fd))) 18177 return -EFAULT; 18178 break; 18179 default: 18180 fd = insn[0].imm; 18181 break; 18182 } 18183 18184 map_idx = add_used_map(env, fd); 18185 if (map_idx < 0) 18186 return map_idx; 18187 map = env->used_maps[map_idx]; 18188 18189 aux = &env->insn_aux_data[i]; 18190 aux->map_index = map_idx; 18191 18192 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18193 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18194 addr = (unsigned long)map; 18195 } else { 18196 u32 off = insn[1].imm; 18197 18198 if (!map->ops->map_direct_value_addr) { 18199 verbose(env, "no direct value access support for this map type\n"); 18200 return -EINVAL; 18201 } 18202 18203 err = map->ops->map_direct_value_addr(map, &addr, off); 18204 if (err) { 18205 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18206 map->value_size, off); 18207 return err; 18208 } 18209 18210 aux->map_off = off; 18211 addr += off; 18212 } 18213 18214 insn[0].imm = (u32)addr; 18215 insn[1].imm = addr >> 32; 18216 18217 next_insn: 18218 insn++; 18219 i++; 18220 continue; 18221 } 18222 18223 /* Basic sanity check before we invest more work here. */ 18224 if (!bpf_opcode_in_insntable(insn->code)) { 18225 verbose(env, "unknown opcode %02x\n", insn->code); 18226 return -EINVAL; 18227 } 18228 18229 err = check_insn_fields(env, insn); 18230 if (err) 18231 return err; 18232 } 18233 18234 /* now all pseudo BPF_LD_IMM64 instructions load valid 18235 * 'struct bpf_map *' into a register instead of user map_fd. 18236 * These pointers will be used later by verifier to validate map access. 18237 */ 18238 return 0; 18239 } 18240 18241 /* drop refcnt of maps used by the rejected program */ 18242 static void release_maps(struct bpf_verifier_env *env) 18243 { 18244 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18245 env->used_map_cnt); 18246 } 18247 18248 /* drop refcnt of maps used by the rejected program */ 18249 static void release_btfs(struct bpf_verifier_env *env) 18250 { 18251 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 18252 } 18253 18254 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18255 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18256 { 18257 struct bpf_insn *insn = env->prog->insnsi; 18258 int insn_cnt = env->prog->len; 18259 int i; 18260 18261 for (i = 0; i < insn_cnt; i++, insn++) { 18262 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18263 continue; 18264 if (insn->src_reg == BPF_PSEUDO_FUNC) 18265 continue; 18266 insn->src_reg = 0; 18267 } 18268 } 18269 18270 static void release_insn_arrays(struct bpf_verifier_env *env) 18271 { 18272 int i; 18273 18274 for (i = 0; i < env->insn_array_map_cnt; i++) 18275 bpf_insn_array_release(env->insn_array_maps[i]); 18276 } 18277 18278 18279 18280 /* The verifier does more data flow analysis than llvm and will not 18281 * explore branches that are dead at run time. Malicious programs can 18282 * have dead code too. Therefore replace all dead at-run-time code 18283 * with 'ja -1'. 18284 * 18285 * Just nops are not optimal, e.g. if they would sit at the end of the 18286 * program and through another bug we would manage to jump there, then 18287 * we'd execute beyond program memory otherwise. Returning exception 18288 * code also wouldn't work since we can have subprogs where the dead 18289 * code could be located. 18290 */ 18291 static void sanitize_dead_code(struct bpf_verifier_env *env) 18292 { 18293 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18294 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18295 struct bpf_insn *insn = env->prog->insnsi; 18296 const int insn_cnt = env->prog->len; 18297 int i; 18298 18299 for (i = 0; i < insn_cnt; i++) { 18300 if (aux_data[i].seen) 18301 continue; 18302 memcpy(insn + i, &trap, sizeof(trap)); 18303 aux_data[i].zext_dst = false; 18304 } 18305 } 18306 18307 18308 18309 static void free_states(struct bpf_verifier_env *env) 18310 { 18311 struct bpf_verifier_state_list *sl; 18312 struct list_head *head, *pos, *tmp; 18313 struct bpf_scc_info *info; 18314 int i, j; 18315 18316 bpf_free_verifier_state(env->cur_state, true); 18317 env->cur_state = NULL; 18318 while (!pop_stack(env, NULL, NULL, false)); 18319 18320 list_for_each_safe(pos, tmp, &env->free_list) { 18321 sl = container_of(pos, struct bpf_verifier_state_list, node); 18322 bpf_free_verifier_state(&sl->state, false); 18323 kfree(sl); 18324 } 18325 INIT_LIST_HEAD(&env->free_list); 18326 18327 for (i = 0; i < env->scc_cnt; ++i) { 18328 info = env->scc_info[i]; 18329 if (!info) 18330 continue; 18331 for (j = 0; j < info->num_visits; j++) 18332 bpf_free_backedges(&info->visits[j]); 18333 kvfree(info); 18334 env->scc_info[i] = NULL; 18335 } 18336 18337 if (!env->explored_states) 18338 return; 18339 18340 for (i = 0; i < state_htab_size(env); i++) { 18341 head = &env->explored_states[i]; 18342 18343 list_for_each_safe(pos, tmp, head) { 18344 sl = container_of(pos, struct bpf_verifier_state_list, node); 18345 bpf_free_verifier_state(&sl->state, false); 18346 kfree(sl); 18347 } 18348 INIT_LIST_HEAD(&env->explored_states[i]); 18349 } 18350 } 18351 18352 static int do_check_common(struct bpf_verifier_env *env, int subprog) 18353 { 18354 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18355 struct bpf_subprog_info *sub = subprog_info(env, subprog); 18356 struct bpf_prog_aux *aux = env->prog->aux; 18357 struct bpf_verifier_state *state; 18358 struct bpf_reg_state *regs; 18359 int ret, i; 18360 18361 env->prev_linfo = NULL; 18362 env->pass_cnt++; 18363 18364 state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT); 18365 if (!state) 18366 return -ENOMEM; 18367 state->curframe = 0; 18368 state->speculative = false; 18369 state->branches = 1; 18370 state->in_sleepable = env->prog->sleepable; 18371 state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT); 18372 if (!state->frame[0]) { 18373 kfree(state); 18374 return -ENOMEM; 18375 } 18376 env->cur_state = state; 18377 init_func_state(env, state->frame[0], 18378 BPF_MAIN_FUNC /* callsite */, 18379 0 /* frameno */, 18380 subprog); 18381 state->first_insn_idx = env->subprog_info[subprog].start; 18382 state->last_insn_idx = -1; 18383 18384 regs = state->frame[state->curframe]->regs; 18385 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 18386 const char *sub_name = subprog_name(env, subprog); 18387 struct bpf_subprog_arg_info *arg; 18388 struct bpf_reg_state *reg; 18389 18390 if (env->log.level & BPF_LOG_LEVEL) 18391 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 18392 ret = btf_prepare_func_args(env, subprog); 18393 if (ret) 18394 goto out; 18395 18396 if (subprog_is_exc_cb(env, subprog)) { 18397 state->frame[0]->in_exception_callback_fn = true; 18398 18399 /* 18400 * Global functions are scalar or void, make sure 18401 * we return a scalar. 18402 */ 18403 if (subprog_returns_void(env, subprog)) { 18404 verbose(env, "exception cb cannot return void\n"); 18405 ret = -EINVAL; 18406 goto out; 18407 } 18408 18409 /* Also ensure the callback only has a single scalar argument. */ 18410 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 18411 verbose(env, "exception cb only supports single integer argument\n"); 18412 ret = -EINVAL; 18413 goto out; 18414 } 18415 } 18416 for (i = BPF_REG_1; i <= min_t(u32, sub->arg_cnt, MAX_BPF_FUNC_REG_ARGS); i++) { 18417 arg = &sub->args[i - BPF_REG_1]; 18418 reg = ®s[i]; 18419 18420 if (arg->arg_type == ARG_PTR_TO_CTX) { 18421 reg->type = PTR_TO_CTX; 18422 mark_reg_known_zero(env, regs, i); 18423 } else if (arg->arg_type == ARG_ANYTHING) { 18424 reg->type = SCALAR_VALUE; 18425 mark_reg_unknown(env, regs, i); 18426 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 18427 /* assume unspecial LOCAL dynptr type */ 18428 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen, 0); 18429 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 18430 reg->type = PTR_TO_MEM; 18431 reg->type |= arg->arg_type & 18432 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 18433 mark_reg_known_zero(env, regs, i); 18434 reg->mem_size = arg->mem_size; 18435 if (arg->arg_type & PTR_MAYBE_NULL) 18436 reg->id = ++env->id_gen; 18437 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 18438 reg->type = PTR_TO_BTF_ID; 18439 if (arg->arg_type & PTR_MAYBE_NULL) 18440 reg->type |= PTR_MAYBE_NULL; 18441 if (arg->arg_type & PTR_UNTRUSTED) 18442 reg->type |= PTR_UNTRUSTED; 18443 if (arg->arg_type & PTR_TRUSTED) 18444 reg->type |= PTR_TRUSTED; 18445 mark_reg_known_zero(env, regs, i); 18446 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 18447 reg->btf_id = arg->btf_id; 18448 reg->id = ++env->id_gen; 18449 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 18450 /* caller can pass either PTR_TO_ARENA or SCALAR */ 18451 mark_reg_unknown(env, regs, i); 18452 } else { 18453 verifier_bug(env, "unhandled arg#%d type %d", 18454 i - BPF_REG_1 + 1, arg->arg_type); 18455 ret = -EFAULT; 18456 goto out; 18457 } 18458 } 18459 if (env->prog->type == BPF_PROG_TYPE_EXT && sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS) { 18460 verbose(env, "freplace programs with >%d args not supported yet\n", 18461 MAX_BPF_FUNC_REG_ARGS); 18462 ret = -EINVAL; 18463 goto out; 18464 } 18465 } else { 18466 /* if main BPF program has associated BTF info, validate that 18467 * it's matching expected signature, and otherwise mark BTF 18468 * info for main program as unreliable 18469 */ 18470 if (env->prog->aux->func_info_aux) { 18471 ret = btf_prepare_func_args(env, 0); 18472 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) { 18473 env->prog->aux->func_info_aux[0].unreliable = true; 18474 sub->arg_cnt = 1; 18475 sub->stack_arg_cnt = 0; 18476 } 18477 } 18478 18479 /* 1st arg to a function */ 18480 regs[BPF_REG_1].type = PTR_TO_CTX; 18481 mark_reg_known_zero(env, regs, BPF_REG_1); 18482 } 18483 18484 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 18485 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 18486 for (i = 0; i < aux->ctx_arg_info_size; i++) { 18487 ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0; 18488 if (ret < 0) 18489 goto out; 18490 18491 aux->ctx_arg_info[i].ref_id = ret; 18492 } 18493 } 18494 18495 ret = do_check(env); 18496 out: 18497 if (!ret && pop_log) 18498 bpf_vlog_reset(&env->log, 0); 18499 free_states(env); 18500 return ret; 18501 } 18502 18503 /* Lazily verify all global functions based on their BTF, if they are called 18504 * from main BPF program or any of subprograms transitively. 18505 * BPF global subprogs called from dead code are not validated. 18506 * All callable global functions must pass verification. 18507 * Otherwise the whole program is rejected. 18508 * Consider: 18509 * int bar(int); 18510 * int foo(int f) 18511 * { 18512 * return bar(f); 18513 * } 18514 * int bar(int b) 18515 * { 18516 * ... 18517 * } 18518 * foo() will be verified first for R1=any_scalar_value. During verification it 18519 * will be assumed that bar() already verified successfully and call to bar() 18520 * from foo() will be checked for type match only. Later bar() will be verified 18521 * independently to check that it's safe for R1=any_scalar_value. 18522 */ 18523 static int do_check_subprogs(struct bpf_verifier_env *env) 18524 { 18525 struct bpf_prog_aux *aux = env->prog->aux; 18526 struct bpf_func_info_aux *sub_aux; 18527 int i, ret, new_cnt; 18528 u32 insn_processed; 18529 18530 if (!aux->func_info) 18531 return 0; 18532 18533 /* exception callback is presumed to be always called */ 18534 if (env->exception_callback_subprog) 18535 subprog_aux(env, env->exception_callback_subprog)->called = true; 18536 18537 again: 18538 new_cnt = 0; 18539 for (i = 1; i < env->subprog_cnt; i++) { 18540 if (!bpf_subprog_is_global(env, i)) 18541 continue; 18542 18543 insn_processed = env->insn_processed; 18544 18545 sub_aux = subprog_aux(env, i); 18546 if (!sub_aux->called || sub_aux->verified) 18547 continue; 18548 18549 env->insn_idx = env->subprog_info[i].start; 18550 WARN_ON_ONCE(env->insn_idx == 0); 18551 ret = do_check_common(env, i); 18552 env->subprog_info[i].insn_processed = env->insn_processed - insn_processed; 18553 if (ret) { 18554 return ret; 18555 } else if (env->log.level & BPF_LOG_LEVEL) { 18556 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 18557 i, subprog_name(env, i)); 18558 } 18559 18560 /* We verified new global subprog, it might have called some 18561 * more global subprogs that we haven't verified yet, so we 18562 * need to do another pass over subprogs to verify those. 18563 */ 18564 sub_aux->verified = true; 18565 new_cnt++; 18566 } 18567 18568 /* We can't loop forever as we verify at least one global subprog on 18569 * each pass. 18570 */ 18571 if (new_cnt) 18572 goto again; 18573 18574 return 0; 18575 } 18576 18577 static int do_check_main(struct bpf_verifier_env *env) 18578 { 18579 u32 insn_processed = env->insn_processed; 18580 int ret; 18581 18582 env->insn_idx = 0; 18583 ret = do_check_common(env, 0); 18584 env->subprog_info[0].insn_processed = env->insn_processed - insn_processed; 18585 if (!ret) 18586 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18587 return ret; 18588 } 18589 18590 18591 static void print_verification_stats(struct bpf_verifier_env *env) 18592 { 18593 /* Skip over hidden subprogs which are not verified. */ 18594 int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18595 18596 if (env->log.level & BPF_LOG_STATS) { 18597 verbose(env, "verification time %lld usec\n", 18598 div_u64(env->verification_time, 1000)); 18599 verbose(env, "stack depth %d", env->subprog_info[0].stack_depth); 18600 for (i = 1; i < subprog_cnt; i++) 18601 verbose(env, "+%d", env->subprog_info[i].stack_depth); 18602 verbose(env, " max %d\n", env->max_stack_depth); 18603 verbose(env, "insns processed %d", env->subprog_info[0].insn_processed); 18604 for (i = 1; i < subprog_cnt; i++) 18605 if (bpf_subprog_is_global(env, i)) 18606 verbose(env, "+%d", env->subprog_info[i].insn_processed); 18607 verbose(env, "\n"); 18608 } 18609 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 18610 "total_states %d peak_states %d mark_read %d\n", 18611 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 18612 env->max_states_per_insn, env->total_states, 18613 env->peak_states, env->longest_mark_read_walk); 18614 } 18615 18616 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 18617 const struct bpf_ctx_arg_aux *info, u32 cnt) 18618 { 18619 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 18620 prog->aux->ctx_arg_info_size = cnt; 18621 18622 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 18623 } 18624 18625 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 18626 { 18627 const struct btf_type *t, *func_proto; 18628 const struct bpf_struct_ops_desc *st_ops_desc; 18629 const struct bpf_struct_ops *st_ops; 18630 const struct btf_member *member; 18631 struct bpf_prog *prog = env->prog; 18632 bool has_refcounted_arg = false; 18633 u32 btf_id, member_idx, member_off; 18634 struct btf *btf; 18635 const char *mname; 18636 int i, err; 18637 18638 if (!prog->gpl_compatible) { 18639 verbose(env, "struct ops programs must have a GPL compatible license\n"); 18640 return -EINVAL; 18641 } 18642 18643 if (!prog->aux->attach_btf_id) 18644 return -ENOTSUPP; 18645 18646 btf = prog->aux->attach_btf; 18647 if (btf_is_module(btf)) { 18648 /* Make sure st_ops is valid through the lifetime of env */ 18649 env->attach_btf_mod = btf_try_get_module(btf); 18650 if (!env->attach_btf_mod) { 18651 verbose(env, "struct_ops module %s is not found\n", 18652 btf_get_name(btf)); 18653 return -ENOTSUPP; 18654 } 18655 } 18656 18657 btf_id = prog->aux->attach_btf_id; 18658 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 18659 if (!st_ops_desc) { 18660 verbose(env, "attach_btf_id %u is not a supported struct\n", 18661 btf_id); 18662 return -ENOTSUPP; 18663 } 18664 st_ops = st_ops_desc->st_ops; 18665 18666 t = st_ops_desc->type; 18667 member_idx = prog->expected_attach_type; 18668 if (member_idx >= btf_type_vlen(t)) { 18669 verbose(env, "attach to invalid member idx %u of struct %s\n", 18670 member_idx, st_ops->name); 18671 return -EINVAL; 18672 } 18673 18674 member = &btf_type_member(t)[member_idx]; 18675 mname = btf_name_by_offset(btf, member->name_off); 18676 func_proto = btf_type_resolve_func_ptr(btf, member->type, 18677 NULL); 18678 if (!func_proto) { 18679 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 18680 mname, member_idx, st_ops->name); 18681 return -EINVAL; 18682 } 18683 18684 member_off = __btf_member_bit_offset(t, member) / 8; 18685 err = bpf_struct_ops_supported(st_ops, member_off); 18686 if (err) { 18687 verbose(env, "attach to unsupported member %s of struct %s\n", 18688 mname, st_ops->name); 18689 return err; 18690 } 18691 18692 if (st_ops->check_member) { 18693 err = st_ops->check_member(t, member, prog); 18694 18695 if (err) { 18696 verbose(env, "attach to unsupported member %s of struct %s\n", 18697 mname, st_ops->name); 18698 return err; 18699 } 18700 } 18701 18702 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 18703 verbose(env, "Private stack not supported by jit\n"); 18704 return -EACCES; 18705 } 18706 18707 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) { 18708 if (st_ops_desc->arg_info[member_idx].info[i].refcounted) { 18709 has_refcounted_arg = true; 18710 break; 18711 } 18712 } 18713 18714 /* Tail call is not allowed for programs with refcounted arguments since we 18715 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 18716 */ 18717 for (i = 0; i < env->subprog_cnt; i++) { 18718 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 18719 verbose(env, "program with __ref argument cannot tail call\n"); 18720 return -EINVAL; 18721 } 18722 } 18723 18724 prog->aux->st_ops = st_ops; 18725 prog->aux->attach_st_ops_member_off = member_off; 18726 18727 prog->aux->attach_func_proto = func_proto; 18728 prog->aux->attach_func_name = mname; 18729 env->ops = st_ops->verifier_ops; 18730 18731 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info, 18732 st_ops_desc->arg_info[member_idx].cnt); 18733 } 18734 #define SECURITY_PREFIX "security_" 18735 18736 #ifdef CONFIG_FUNCTION_ERROR_INJECTION 18737 18738 /* list of non-sleepable functions that are otherwise on 18739 * ALLOW_ERROR_INJECTION list 18740 */ 18741 BTF_SET_START(btf_non_sleepable_error_inject) 18742 /* Three functions below can be called from sleepable and non-sleepable context. 18743 * Assume non-sleepable from bpf safety point of view. 18744 */ 18745 BTF_ID(func, __filemap_add_folio) 18746 #ifdef CONFIG_FAIL_PAGE_ALLOC 18747 BTF_ID(func, should_fail_alloc_page) 18748 #endif 18749 #ifdef CONFIG_FAILSLAB 18750 BTF_ID(func, should_failslab) 18751 #endif 18752 BTF_SET_END(btf_non_sleepable_error_inject) 18753 18754 static int check_non_sleepable_error_inject(u32 btf_id) 18755 { 18756 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 18757 } 18758 18759 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18760 { 18761 /* fentry/fexit/fmod_ret progs can be sleepable if they are 18762 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 18763 */ 18764 if (!check_non_sleepable_error_inject(btf_id) && 18765 within_error_injection_list(addr)) 18766 return 0; 18767 18768 return -EINVAL; 18769 } 18770 18771 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18772 { 18773 if (within_error_injection_list(addr) || 18774 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18775 return 0; 18776 18777 return -EINVAL; 18778 } 18779 18780 #else 18781 18782 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code 18783 * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name() 18784 * but that just compares two concrete function names. 18785 */ 18786 static bool has_arch_syscall_prefix(const char *func_name) 18787 { 18788 #if defined(__x86_64__) 18789 return !strncmp(func_name, "__x64_", 6); 18790 #elif defined(__i386__) 18791 return !strncmp(func_name, "__ia32_", 7); 18792 #elif defined(__s390x__) 18793 return !strncmp(func_name, "__s390x_", 8); 18794 #elif defined(__aarch64__) 18795 return !strncmp(func_name, "__arm64_", 8); 18796 #elif defined(__riscv) 18797 return !strncmp(func_name, "__riscv_", 8); 18798 #elif defined(__powerpc__) || defined(__powerpc64__) 18799 return !strncmp(func_name, "sys_", 4); 18800 #elif defined(__loongarch__) 18801 return !strncmp(func_name, "sys_", 4); 18802 #else 18803 return false; 18804 #endif 18805 } 18806 18807 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */ 18808 18809 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18810 { 18811 if (has_arch_syscall_prefix(func_name)) 18812 return 0; 18813 18814 return -EINVAL; 18815 } 18816 18817 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18818 { 18819 if (has_arch_syscall_prefix(func_name) || 18820 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18821 return 0; 18822 18823 return -EINVAL; 18824 } 18825 18826 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */ 18827 18828 static bool is_tracing_multi_id(const struct bpf_prog *prog, u32 btf_id) 18829 { 18830 return is_tracing_multi(prog->expected_attach_type) && bpf_multi_func_btf_id[0] == btf_id; 18831 } 18832 18833 static int btf_id_allow_sleepable(u32 btf_id, unsigned long addr, const struct bpf_prog *prog, 18834 const struct btf *btf) 18835 { 18836 const struct btf_type *t; 18837 const char *tname; 18838 18839 switch (prog->type) { 18840 case BPF_PROG_TYPE_TRACING: 18841 t = btf_type_by_id(btf, btf_id); 18842 if (!t) 18843 return -EINVAL; 18844 tname = btf_name_by_offset(btf, t->name_off); 18845 if (!tname) 18846 return -EINVAL; 18847 18848 /* 18849 * *.multi sleepable programs will pass initial sleepable check, 18850 * the actual attached btf ids are checked later during the link 18851 * attachment. 18852 */ 18853 if (is_tracing_multi_id(prog, btf_id)) 18854 return 0; 18855 if (!check_attach_sleepable(btf_id, addr, tname)) 18856 return 0; 18857 /* 18858 * fentry/fexit/fmod_ret progs can also be sleepable if they are 18859 * in the fmodret id set with the KF_SLEEPABLE flag. 18860 */ 18861 else { 18862 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, prog); 18863 18864 if (flags && (*flags & KF_SLEEPABLE)) 18865 return 0; 18866 } 18867 break; 18868 case BPF_PROG_TYPE_LSM: 18869 /* 18870 * LSM progs check that they are attached to bpf_lsm_*() funcs. 18871 * Only some of them are sleepable. 18872 */ 18873 if (bpf_lsm_is_sleepable_hook(btf_id)) 18874 return 0; 18875 break; 18876 default: 18877 break; 18878 } 18879 return -EINVAL; 18880 } 18881 18882 int bpf_check_attach_target(struct bpf_verifier_log *log, 18883 const struct bpf_prog *prog, 18884 const struct bpf_prog *tgt_prog, 18885 u32 btf_id, 18886 struct bpf_attach_target_info *tgt_info) 18887 { 18888 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 18889 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 18890 char trace_symbol[KSYM_SYMBOL_LEN]; 18891 const char prefix[] = "btf_trace_"; 18892 struct bpf_raw_event_map *btp; 18893 int ret = 0, subprog = -1, i; 18894 const struct btf_type *t; 18895 bool conservative = true; 18896 const char *tname, *fname; 18897 struct btf *btf; 18898 long addr = 0; 18899 struct module *mod = NULL; 18900 18901 if (!btf_id) { 18902 bpf_log(log, "Tracing programs must provide btf_id\n"); 18903 return -EINVAL; 18904 } 18905 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 18906 if (!btf) { 18907 bpf_log(log, 18908 "Tracing program can only be attached to another program annotated with BTF\n"); 18909 return -EINVAL; 18910 } 18911 t = btf_type_by_id(btf, btf_id); 18912 if (!t) { 18913 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 18914 return -EINVAL; 18915 } 18916 tname = btf_name_by_offset(btf, t->name_off); 18917 if (!tname) { 18918 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 18919 return -EINVAL; 18920 } 18921 if (tgt_prog) { 18922 struct bpf_prog_aux *aux = tgt_prog->aux; 18923 bool tgt_changes_pkt_data; 18924 bool tgt_might_sleep; 18925 18926 if (bpf_prog_is_dev_bound(prog->aux) && 18927 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 18928 bpf_log(log, "Target program bound device mismatch"); 18929 return -EINVAL; 18930 } 18931 18932 for (i = 0; i < aux->func_info_cnt; i++) 18933 if (aux->func_info[i].type_id == btf_id) { 18934 subprog = i; 18935 break; 18936 } 18937 if (subprog == -1) { 18938 bpf_log(log, "Subprog %s doesn't exist\n", tname); 18939 return -EINVAL; 18940 } 18941 if (aux->func && aux->func[subprog]->aux->exception_cb) { 18942 bpf_log(log, 18943 "%s programs cannot attach to exception callback\n", 18944 prog_extension ? "Extension" : "Tracing"); 18945 return -EINVAL; 18946 } 18947 conservative = aux->func_info_aux[subprog].unreliable; 18948 if (prog_extension) { 18949 if (conservative) { 18950 bpf_log(log, 18951 "Cannot replace static functions\n"); 18952 return -EINVAL; 18953 } 18954 if (!prog->jit_requested) { 18955 bpf_log(log, 18956 "Extension programs should be JITed\n"); 18957 return -EINVAL; 18958 } 18959 tgt_changes_pkt_data = aux->func 18960 ? aux->func[subprog]->aux->changes_pkt_data 18961 : aux->changes_pkt_data; 18962 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 18963 bpf_log(log, 18964 "Extension program changes packet data, while original does not\n"); 18965 return -EINVAL; 18966 } 18967 18968 tgt_might_sleep = aux->func 18969 ? aux->func[subprog]->aux->might_sleep 18970 : aux->might_sleep; 18971 if (prog->aux->might_sleep && !tgt_might_sleep) { 18972 bpf_log(log, 18973 "Extension program may sleep, while original does not\n"); 18974 return -EINVAL; 18975 } 18976 } 18977 if (!tgt_prog->jited) { 18978 bpf_log(log, "Can attach to only JITed progs\n"); 18979 return -EINVAL; 18980 } 18981 if (prog_tracing) { 18982 if (aux->attach_tracing_prog) { 18983 /* 18984 * Target program is an fentry/fexit which is already attached 18985 * to another tracing program. More levels of nesting 18986 * attachment are not allowed. 18987 */ 18988 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 18989 return -EINVAL; 18990 } 18991 } else if (tgt_prog->type == prog->type) { 18992 /* 18993 * To avoid potential call chain cycles, prevent attaching of a 18994 * program extension to another extension. It's ok to attach 18995 * fentry/fexit to extension program. 18996 */ 18997 bpf_log(log, "Cannot recursively attach\n"); 18998 return -EINVAL; 18999 } 19000 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19001 prog_extension && 19002 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19003 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT || 19004 tgt_prog->expected_attach_type == BPF_TRACE_FENTRY_MULTI || 19005 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || 19006 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION || 19007 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19008 /* Program extensions can extend all program types 19009 * except fentry/fexit. The reason is the following. 19010 * The fentry/fexit programs are used for performance 19011 * analysis, stats and can be attached to any program 19012 * type. When extension program is replacing XDP function 19013 * it is necessary to allow performance analysis of all 19014 * functions. Both original XDP program and its program 19015 * extension. Hence attaching fentry/fexit to 19016 * BPF_PROG_TYPE_EXT is allowed. If extending of 19017 * fentry/fexit was allowed it would be possible to create 19018 * long call chain fentry->extension->fentry->extension 19019 * beyond reasonable stack size. Hence extending fentry 19020 * is not allowed. 19021 */ 19022 bpf_log(log, "Cannot extend fentry/fexit/fsession\n"); 19023 return -EINVAL; 19024 } 19025 } else { 19026 if (prog_extension) { 19027 bpf_log(log, "Cannot replace kernel functions\n"); 19028 return -EINVAL; 19029 } 19030 } 19031 19032 switch (prog->expected_attach_type) { 19033 case BPF_TRACE_RAW_TP: 19034 if (tgt_prog) { 19035 bpf_log(log, 19036 "Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n"); 19037 return -EINVAL; 19038 } 19039 if (!btf_type_is_typedef(t)) { 19040 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19041 btf_id); 19042 return -EINVAL; 19043 } 19044 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19045 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19046 btf_id, tname); 19047 return -EINVAL; 19048 } 19049 tname += sizeof(prefix) - 1; 19050 19051 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 19052 * names. Thus using bpf_raw_event_map to get argument names. 19053 */ 19054 btp = bpf_get_raw_tracepoint(tname); 19055 if (!btp) 19056 return -EINVAL; 19057 if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) { 19058 bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n", 19059 tname); 19060 bpf_put_raw_tracepoint(btp); 19061 return -EINVAL; 19062 } 19063 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 19064 trace_symbol); 19065 bpf_put_raw_tracepoint(btp); 19066 19067 if (fname) 19068 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 19069 19070 if (!fname || ret < 0) { 19071 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 19072 prefix, tname); 19073 t = btf_type_by_id(btf, t->type); 19074 if (!btf_type_is_ptr(t)) 19075 /* should never happen in valid vmlinux build */ 19076 return -EINVAL; 19077 } else { 19078 t = btf_type_by_id(btf, ret); 19079 if (!btf_type_is_func(t)) 19080 /* should never happen in valid vmlinux build */ 19081 return -EINVAL; 19082 } 19083 19084 t = btf_type_by_id(btf, t->type); 19085 if (!btf_type_is_func_proto(t)) 19086 /* should never happen in valid vmlinux build */ 19087 return -EINVAL; 19088 19089 break; 19090 case BPF_TRACE_ITER: 19091 if (!btf_type_is_func(t)) { 19092 bpf_log(log, "attach_btf_id %u is not a function\n", 19093 btf_id); 19094 return -EINVAL; 19095 } 19096 t = btf_type_by_id(btf, t->type); 19097 if (!btf_type_is_func_proto(t)) 19098 return -EINVAL; 19099 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19100 if (ret) 19101 return ret; 19102 break; 19103 default: 19104 if (!prog_extension) 19105 return -EINVAL; 19106 fallthrough; 19107 case BPF_MODIFY_RETURN: 19108 case BPF_LSM_MAC: 19109 case BPF_LSM_CGROUP: 19110 case BPF_TRACE_FENTRY: 19111 case BPF_TRACE_FEXIT: 19112 case BPF_TRACE_FSESSION: 19113 case BPF_TRACE_FSESSION_MULTI: 19114 case BPF_TRACE_FENTRY_MULTI: 19115 case BPF_TRACE_FEXIT_MULTI: 19116 if ((prog->expected_attach_type == BPF_TRACE_FSESSION || 19117 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) && 19118 !bpf_jit_supports_fsession()) { 19119 bpf_log(log, "JIT does not support fsession\n"); 19120 return -EOPNOTSUPP; 19121 } 19122 if (!btf_type_is_func(t)) { 19123 bpf_log(log, "attach_btf_id %u is not a function\n", 19124 btf_id); 19125 return -EINVAL; 19126 } 19127 if (prog_extension && 19128 btf_check_type_match(log, prog, btf, t)) 19129 return -EINVAL; 19130 t = btf_type_by_id(btf, t->type); 19131 if (!btf_type_is_func_proto(t)) 19132 return -EINVAL; 19133 19134 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 19135 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 19136 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 19137 return -EINVAL; 19138 19139 if (tgt_prog && conservative) 19140 t = NULL; 19141 19142 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19143 if (ret < 0) 19144 return ret; 19145 19146 /* 19147 * *.multi programs don't need an address during program 19148 * verification, we just take the module ref if needed. 19149 */ 19150 if (is_tracing_multi_id(prog, btf_id)) { 19151 if (btf_is_module(btf)) { 19152 mod = btf_try_get_module(btf); 19153 if (!mod) 19154 return -ENOENT; 19155 } 19156 addr = 0; 19157 } else if (tgt_prog) { 19158 if (subprog == 0) 19159 addr = (long) tgt_prog->bpf_func; 19160 else 19161 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 19162 } else { 19163 if (btf_is_module(btf)) { 19164 mod = btf_try_get_module(btf); 19165 if (mod) 19166 addr = find_kallsyms_symbol_value(mod, tname); 19167 else 19168 addr = 0; 19169 } else { 19170 addr = kallsyms_lookup_name(tname); 19171 } 19172 if (!addr) { 19173 module_put(mod); 19174 bpf_log(log, 19175 "The address of function %s cannot be found\n", 19176 tname); 19177 return -ENOENT; 19178 } 19179 } 19180 19181 if (prog->sleepable) { 19182 ret = btf_id_allow_sleepable(btf_id, addr, prog, btf); 19183 if (ret) { 19184 module_put(mod); 19185 bpf_log(log, "%s is not sleepable\n", tname); 19186 return ret; 19187 } 19188 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19189 if (tgt_prog) { 19190 module_put(mod); 19191 bpf_log(log, "can't modify return codes of BPF programs\n"); 19192 return -EINVAL; 19193 } 19194 ret = -EINVAL; 19195 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19196 !check_attach_modify_return(addr, tname)) 19197 ret = 0; 19198 if (ret) { 19199 module_put(mod); 19200 bpf_log(log, "%s() is not modifiable\n", tname); 19201 return ret; 19202 } 19203 } 19204 19205 break; 19206 } 19207 tgt_info->tgt_addr = addr; 19208 tgt_info->tgt_name = tname; 19209 tgt_info->tgt_type = t; 19210 tgt_info->tgt_mod = mod; 19211 return 0; 19212 } 19213 19214 BTF_SET_START(btf_id_deny) 19215 BTF_ID_UNUSED 19216 #ifdef CONFIG_SMP 19217 BTF_ID(func, ___migrate_enable) 19218 BTF_ID(func, migrate_disable) 19219 BTF_ID(func, migrate_enable) 19220 #endif 19221 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19222 BTF_ID(func, rcu_read_unlock_strict) 19223 #endif 19224 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19225 BTF_ID(func, preempt_count_add) 19226 BTF_ID(func, preempt_count_sub) 19227 #endif 19228 #ifdef CONFIG_PREEMPT_RCU 19229 BTF_ID(func, __rcu_read_lock) 19230 BTF_ID(func, __rcu_read_unlock) 19231 #endif 19232 BTF_SET_END(btf_id_deny) 19233 19234 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 19235 * Currently, we must manually list all __noreturn functions here. Once a more 19236 * robust solution is implemented, this workaround can be removed. 19237 */ 19238 BTF_SET_START(noreturn_deny) 19239 #ifdef CONFIG_IA32_EMULATION 19240 BTF_ID(func, __ia32_sys_exit) 19241 BTF_ID(func, __ia32_sys_exit_group) 19242 #endif 19243 #ifdef CONFIG_KUNIT 19244 BTF_ID(func, __kunit_abort) 19245 BTF_ID(func, kunit_try_catch_throw) 19246 #endif 19247 #ifdef CONFIG_MODULES 19248 BTF_ID(func, __module_put_and_kthread_exit) 19249 #endif 19250 #ifdef CONFIG_X86_64 19251 BTF_ID(func, __x64_sys_exit) 19252 BTF_ID(func, __x64_sys_exit_group) 19253 #endif 19254 BTF_ID(func, do_exit) 19255 BTF_ID(func, do_group_exit) 19256 BTF_ID(func, kthread_complete_and_exit) 19257 BTF_ID(func, make_task_dead) 19258 BTF_SET_END(noreturn_deny) 19259 19260 static bool can_be_sleepable(struct bpf_prog *prog) 19261 { 19262 if (prog->type == BPF_PROG_TYPE_TRACING) { 19263 switch (prog->expected_attach_type) { 19264 case BPF_TRACE_FENTRY: 19265 case BPF_TRACE_FEXIT: 19266 case BPF_MODIFY_RETURN: 19267 case BPF_TRACE_ITER: 19268 case BPF_TRACE_FSESSION: 19269 case BPF_TRACE_RAW_TP: 19270 case BPF_TRACE_FENTRY_MULTI: 19271 case BPF_TRACE_FEXIT_MULTI: 19272 case BPF_TRACE_FSESSION_MULTI: 19273 return true; 19274 default: 19275 return false; 19276 } 19277 } 19278 if (prog->type == BPF_PROG_TYPE_LSM) 19279 return prog->expected_attach_type != BPF_LSM_CGROUP; 19280 19281 return prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 19282 prog->type == BPF_PROG_TYPE_STRUCT_OPS || 19283 prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT || 19284 prog->type == BPF_PROG_TYPE_TRACEPOINT; 19285 } 19286 19287 static int check_attach_btf_id(struct bpf_verifier_env *env) 19288 { 19289 struct bpf_prog *prog = env->prog; 19290 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 19291 struct bpf_attach_target_info tgt_info = {}; 19292 u32 btf_id = prog->aux->attach_btf_id; 19293 struct bpf_trampoline *tr; 19294 int ret; 19295 u64 key; 19296 19297 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 19298 if (prog->sleepable) 19299 /* attach_btf_id checked to be zero already */ 19300 return 0; 19301 verbose(env, "Syscall programs can only be sleepable\n"); 19302 return -EINVAL; 19303 } 19304 19305 if (prog->sleepable && !can_be_sleepable(prog)) { 19306 verbose(env, "Program of this type cannot be sleepable\n"); 19307 return -EINVAL; 19308 } 19309 19310 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 19311 return check_struct_ops_btf_id(env); 19312 19313 if (prog->type != BPF_PROG_TYPE_TRACING && 19314 prog->type != BPF_PROG_TYPE_LSM && 19315 prog->type != BPF_PROG_TYPE_EXT) 19316 return 0; 19317 19318 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 19319 if (ret) 19320 return ret; 19321 19322 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 19323 /* to make freplace equivalent to their targets, they need to 19324 * inherit env->ops and expected_attach_type for the rest of the 19325 * verification 19326 */ 19327 env->ops = bpf_verifier_ops[tgt_prog->type]; 19328 prog->expected_attach_type = tgt_prog->expected_attach_type; 19329 } 19330 19331 /* store info about the attachment target that will be used later */ 19332 prog->aux->attach_func_proto = tgt_info.tgt_type; 19333 prog->aux->attach_func_name = tgt_info.tgt_name; 19334 prog->aux->mod = tgt_info.tgt_mod; 19335 19336 if (tgt_prog) { 19337 prog->aux->saved_dst_prog_type = tgt_prog->type; 19338 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 19339 } 19340 19341 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 19342 prog->aux->attach_btf_trace = true; 19343 return 0; 19344 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 19345 return bpf_iter_prog_supported(prog); 19346 } 19347 19348 if (prog->type == BPF_PROG_TYPE_LSM) { 19349 ret = bpf_lsm_verify_prog(&env->log, prog); 19350 if (ret < 0) 19351 return ret; 19352 } else if (prog->type == BPF_PROG_TYPE_TRACING && 19353 btf_id_set_contains(&btf_id_deny, btf_id)) { 19354 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 19355 tgt_info.tgt_name); 19356 return -EINVAL; 19357 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 19358 prog->expected_attach_type == BPF_TRACE_FSESSION || 19359 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI || 19360 prog->expected_attach_type == BPF_MODIFY_RETURN) && 19361 btf_id_set_contains(&noreturn_deny, btf_id)) { 19362 verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n", 19363 tgt_info.tgt_name); 19364 return -EINVAL; 19365 } 19366 19367 /* 19368 * We don't get trampoline for tracing_multi programs at this point, 19369 * it's done when tracing_multi link is created. 19370 */ 19371 if (prog->type == BPF_PROG_TYPE_TRACING && 19372 is_tracing_multi(prog->expected_attach_type)) 19373 return 0; 19374 19375 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 19376 tr = bpf_trampoline_get(key, &tgt_info); 19377 if (!tr) 19378 return -ENOMEM; 19379 19380 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 19381 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 19382 19383 prog->aux->dst_trampoline = tr; 19384 return 0; 19385 } 19386 19387 int bpf_check_attach_btf_id_multi(struct btf *btf, struct bpf_prog *prog, u32 btf_id, 19388 struct bpf_attach_target_info *tgt_info) 19389 { 19390 const struct btf_type *t; 19391 unsigned long addr; 19392 const char *tname; 19393 int err; 19394 19395 if (!btf_id || !btf) 19396 return -EINVAL; 19397 19398 /* Check noreturn attachment. */ 19399 if ((prog->expected_attach_type == BPF_TRACE_FEXIT_MULTI || 19400 prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI) && 19401 btf_id_set_contains(&noreturn_deny, btf_id)) 19402 return -EINVAL; 19403 /* Check denied attachment. */ 19404 if (btf_id_set_contains(&btf_id_deny, btf_id)) 19405 return -EINVAL; 19406 19407 /* Check and get function target data. */ 19408 t = btf_type_by_id(btf, btf_id); 19409 if (!t) 19410 return -EINVAL; 19411 tname = btf_name_by_offset(btf, t->name_off); 19412 if (!tname) 19413 return -EINVAL; 19414 if (!btf_type_is_func(t)) 19415 return -EINVAL; 19416 t = btf_type_by_id(btf, t->type); 19417 if (!btf_type_is_func_proto(t)) 19418 return -EINVAL; 19419 err = btf_distill_func_proto(NULL, btf, t, tname, &tgt_info->fmodel); 19420 if (err < 0) 19421 return err; 19422 if (btf_is_module(btf)) { 19423 /* The bpf program already holds reference to module. */ 19424 if (WARN_ON_ONCE(!prog->aux->mod)) 19425 return -EINVAL; 19426 addr = find_kallsyms_symbol_value(prog->aux->mod, tname); 19427 } else { 19428 addr = kallsyms_lookup_name(tname); 19429 } 19430 if (!addr || !ftrace_location(addr)) 19431 return -ENOENT; 19432 19433 /* Check sleepable program attachment. */ 19434 if (prog->sleepable) { 19435 err = btf_id_allow_sleepable(btf_id, addr, prog, btf); 19436 if (err) 19437 return err; 19438 } 19439 tgt_info->tgt_addr = addr; 19440 return 0; 19441 } 19442 19443 struct btf *bpf_get_btf_vmlinux(void) 19444 { 19445 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 19446 mutex_lock(&bpf_verifier_lock); 19447 if (!btf_vmlinux) 19448 btf_vmlinux = btf_parse_vmlinux(); 19449 mutex_unlock(&bpf_verifier_lock); 19450 } 19451 return btf_vmlinux; 19452 } 19453 19454 /* 19455 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 19456 * this case expect that every file descriptor in the array is either a map or 19457 * a BTF. Everything else is considered to be trash. 19458 */ 19459 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) 19460 { 19461 struct bpf_map *map; 19462 struct btf *btf; 19463 CLASS(fd, f)(fd); 19464 int err; 19465 19466 map = __bpf_map_get(f); 19467 if (!IS_ERR(map)) { 19468 err = __add_used_map(env, map); 19469 if (err < 0) 19470 return err; 19471 return 0; 19472 } 19473 19474 btf = __btf_get_by_fd(f); 19475 if (!IS_ERR(btf)) { 19476 btf_get(btf); 19477 return __add_used_btf(env, btf); 19478 } 19479 19480 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 19481 return PTR_ERR(map); 19482 } 19483 19484 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr) 19485 { 19486 size_t size = sizeof(int); 19487 int ret; 19488 int fd; 19489 u32 i; 19490 19491 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 19492 19493 /* 19494 * The only difference between old (no fd_array_cnt is given) and new 19495 * APIs is that in the latter case the fd_array is expected to be 19496 * continuous and is scanned for map fds right away 19497 */ 19498 if (!attr->fd_array_cnt) 19499 return 0; 19500 19501 /* Check for integer overflow */ 19502 if (attr->fd_array_cnt >= (U32_MAX / size)) { 19503 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt); 19504 return -EINVAL; 19505 } 19506 19507 for (i = 0; i < attr->fd_array_cnt; i++) { 19508 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size)) 19509 return -EFAULT; 19510 19511 ret = add_fd_from_fd_array(env, fd); 19512 if (ret) 19513 return ret; 19514 } 19515 19516 return 0; 19517 } 19518 19519 /* replace a generic kfunc with a specialized version if necessary */ 19520 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx) 19521 { 19522 struct bpf_prog *prog = env->prog; 19523 bool seen_direct_write; 19524 void *xdp_kfunc; 19525 bool is_rdonly; 19526 u32 func_id = desc->func_id; 19527 u16 offset = desc->offset; 19528 unsigned long addr = desc->addr; 19529 19530 if (offset) /* return if module BTF is used */ 19531 return 0; 19532 19533 if (bpf_dev_bound_kfunc_id(func_id)) { 19534 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19535 if (xdp_kfunc) 19536 addr = (unsigned long)xdp_kfunc; 19537 /* fallback to default kfunc when not supported by netdev */ 19538 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19539 seen_direct_write = env->seen_direct_write; 19540 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19541 19542 if (is_rdonly) 19543 addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19544 19545 /* restore env->seen_direct_write to its original value, since 19546 * may_access_direct_pkt_data mutates it 19547 */ 19548 env->seen_direct_write = seen_direct_write; 19549 } else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) { 19550 if (bpf_lsm_has_d_inode_locked(prog)) 19551 addr = (unsigned long)bpf_set_dentry_xattr_locked; 19552 } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) { 19553 if (bpf_lsm_has_d_inode_locked(prog)) 19554 addr = (unsigned long)bpf_remove_dentry_xattr_locked; 19555 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 19556 if (!env->insn_aux_data[insn_idx].non_sleepable) 19557 addr = (unsigned long)bpf_dynptr_from_file_sleepable; 19558 } else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) { 19559 if (env->insn_aux_data[insn_idx].non_sleepable) 19560 addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable; 19561 } else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) { 19562 if (env->insn_aux_data[insn_idx].non_sleepable) 19563 addr = (unsigned long)bpf_arena_free_pages_non_sleepable; 19564 } 19565 desc->addr = addr; 19566 return 0; 19567 } 19568 19569 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19570 u16 struct_meta_reg, 19571 u16 node_offset_reg, 19572 struct bpf_insn *insn, 19573 struct bpf_insn *insn_buf, 19574 int *cnt) 19575 { 19576 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19577 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19578 19579 insn_buf[0] = addr[0]; 19580 insn_buf[1] = addr[1]; 19581 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19582 insn_buf[3] = *insn; 19583 *cnt = 4; 19584 } 19585 19586 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19587 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19588 { 19589 struct bpf_kfunc_desc *desc; 19590 int err; 19591 19592 if (!insn->imm) { 19593 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19594 return -EINVAL; 19595 } 19596 19597 *cnt = 0; 19598 19599 /* insn->imm has the btf func_id. Replace it with an offset relative to 19600 * __bpf_call_base, unless the JIT needs to call functions that are 19601 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19602 */ 19603 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19604 if (!desc) { 19605 verifier_bug(env, "kernel function descriptor not found for func_id %u", 19606 insn->imm); 19607 return -EFAULT; 19608 } 19609 19610 err = specialize_kfunc(env, desc, insn_idx); 19611 if (err) 19612 return err; 19613 19614 if (!bpf_jit_supports_far_kfunc_call()) 19615 insn->imm = BPF_CALL_IMM(desc->addr); 19616 19617 if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) { 19618 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19619 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19620 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19621 19622 if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) { 19623 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19624 insn_idx); 19625 return -EFAULT; 19626 } 19627 19628 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19629 insn_buf[1] = addr[0]; 19630 insn_buf[2] = addr[1]; 19631 insn_buf[3] = *insn; 19632 *cnt = 4; 19633 } else if (is_bpf_obj_drop_kfunc(desc->func_id) || 19634 is_bpf_percpu_obj_drop_kfunc(desc->func_id) || 19635 is_bpf_refcount_acquire_kfunc(desc->func_id)) { 19636 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19637 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19638 19639 if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) { 19640 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19641 insn_idx); 19642 return -EFAULT; 19643 } 19644 19645 if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) { 19646 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19647 insn_idx); 19648 return -EFAULT; 19649 } 19650 19651 insn_buf[0] = addr[0]; 19652 insn_buf[1] = addr[1]; 19653 insn_buf[2] = *insn; 19654 *cnt = 3; 19655 } else if (is_bpf_list_push_kfunc(desc->func_id) || 19656 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19657 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19658 int struct_meta_reg = BPF_REG_3; 19659 int node_offset_reg = BPF_REG_4; 19660 19661 /* list_add/rbtree_add have an extra arg (prev/less), 19662 * so args-to-fixup are in diff regs. 19663 */ 19664 if (desc->func_id == special_kfunc_list[KF_bpf_list_add] || 19665 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19666 struct_meta_reg = BPF_REG_4; 19667 node_offset_reg = BPF_REG_5; 19668 } 19669 19670 if (!kptr_struct_meta) { 19671 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19672 insn_idx); 19673 return -EFAULT; 19674 } 19675 19676 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19677 node_offset_reg, insn, insn_buf, cnt); 19678 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19679 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19680 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19681 *cnt = 1; 19682 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] && 19683 (env->prog->expected_attach_type == BPF_TRACE_FSESSION || 19684 env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19685 19686 /* 19687 * inline the bpf_session_is_return() for fsession: 19688 * bool bpf_session_is_return(void *ctx) 19689 * { 19690 * return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1; 19691 * } 19692 */ 19693 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19694 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT); 19695 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1); 19696 *cnt = 3; 19697 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] && 19698 (env->prog->expected_attach_type == BPF_TRACE_FSESSION || 19699 env->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)) { 19700 /* 19701 * inline bpf_session_cookie() for fsession: 19702 * __u64 *bpf_session_cookie(void *ctx) 19703 * { 19704 * u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF; 19705 * return &((u64 *)ctx)[-off]; 19706 * } 19707 */ 19708 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19709 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT); 19710 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF); 19711 insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19712 insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1); 19713 insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0); 19714 *cnt = 6; 19715 } 19716 19717 if (env->insn_aux_data[insn_idx].arg_prog) { 19718 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 19719 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 19720 int idx = *cnt; 19721 19722 insn_buf[idx++] = ld_addrs[0]; 19723 insn_buf[idx++] = ld_addrs[1]; 19724 insn_buf[idx++] = *insn; 19725 *cnt = idx; 19726 } 19727 return 0; 19728 } 19729 19730 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, 19731 struct bpf_log_attr *attr_log) 19732 { 19733 u64 start_time = ktime_get_ns(); 19734 struct bpf_verifier_env *env; 19735 int i, len, ret = -EINVAL, err; 19736 bool is_priv; 19737 19738 BTF_TYPE_EMIT(enum bpf_features); 19739 19740 /* no program is valid */ 19741 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 19742 return -EINVAL; 19743 19744 /* 'struct bpf_verifier_env' can be global, but since it's not small, 19745 * allocate/free it every time bpf_check() is called 19746 */ 19747 env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT); 19748 if (!env) 19749 return -ENOMEM; 19750 19751 env->bt.env = env; 19752 19753 len = (*prog)->len; 19754 env->insn_aux_data = 19755 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 19756 ret = -ENOMEM; 19757 if (!env->insn_aux_data) 19758 goto err_free_env; 19759 for (i = 0; i < len; i++) 19760 env->insn_aux_data[i].orig_idx = i; 19761 env->succ = bpf_iarray_realloc(NULL, 2); 19762 if (!env->succ) 19763 goto err_free_env; 19764 env->prog = *prog; 19765 env->ops = bpf_verifier_ops[env->prog->type]; 19766 19767 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 19768 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 19769 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 19770 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 19771 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 19772 19773 bpf_get_btf_vmlinux(); 19774 19775 /* grab the mutex to protect few globals used by verifier */ 19776 if (!is_priv) 19777 mutex_lock(&bpf_verifier_lock); 19778 19779 /* user could have requested verbose verifier output 19780 * and supplied buffer to store the verification trace 19781 */ 19782 ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size); 19783 if (ret) 19784 goto err_unlock; 19785 19786 ret = process_fd_array(env, attr, uattr); 19787 if (ret) 19788 goto skip_full_check; 19789 19790 mark_verifier_state_clean(env); 19791 19792 if (IS_ERR(btf_vmlinux)) { 19793 /* Either gcc or pahole or kernel are broken. */ 19794 verbose(env, "in-kernel BTF is malformed\n"); 19795 ret = PTR_ERR(btf_vmlinux); 19796 goto skip_full_check; 19797 } 19798 19799 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 19800 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 19801 env->strict_alignment = true; 19802 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 19803 env->strict_alignment = false; 19804 19805 if (is_priv) 19806 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 19807 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 19808 19809 env->explored_states = kvzalloc_objs(struct list_head, 19810 state_htab_size(env), 19811 GFP_KERNEL_ACCOUNT); 19812 ret = -ENOMEM; 19813 if (!env->explored_states) 19814 goto skip_full_check; 19815 19816 for (i = 0; i < state_htab_size(env); i++) 19817 INIT_LIST_HEAD(&env->explored_states[i]); 19818 INIT_LIST_HEAD(&env->free_list); 19819 19820 ret = bpf_check_btf_info_early(env, attr, uattr); 19821 if (ret < 0) 19822 goto skip_full_check; 19823 19824 ret = add_subprog_and_kfunc(env); 19825 if (ret < 0) 19826 goto skip_full_check; 19827 19828 ret = check_subprogs(env); 19829 if (ret < 0) 19830 goto skip_full_check; 19831 19832 ret = bpf_check_btf_info(env, attr, uattr); 19833 if (ret < 0) 19834 goto skip_full_check; 19835 19836 ret = check_and_resolve_insns(env); 19837 if (ret < 0) 19838 goto skip_full_check; 19839 19840 if (bpf_prog_is_offloaded(env->prog->aux)) { 19841 ret = bpf_prog_offload_verifier_prep(env->prog); 19842 if (ret) 19843 goto skip_full_check; 19844 } 19845 19846 ret = bpf_check_cfg(env); 19847 if (ret < 0) 19848 goto skip_full_check; 19849 19850 ret = bpf_compute_postorder(env); 19851 if (ret < 0) 19852 goto skip_full_check; 19853 19854 ret = bpf_stack_liveness_init(env); 19855 if (ret) 19856 goto skip_full_check; 19857 19858 ret = check_attach_btf_id(env); 19859 if (ret) 19860 goto skip_full_check; 19861 19862 ret = bpf_compute_const_regs(env); 19863 if (ret < 0) 19864 goto skip_full_check; 19865 19866 ret = bpf_prune_dead_branches(env); 19867 if (ret < 0) 19868 goto skip_full_check; 19869 19870 ret = sort_subprogs_topo(env); 19871 if (ret < 0) 19872 goto skip_full_check; 19873 19874 ret = bpf_compute_scc(env); 19875 if (ret < 0) 19876 goto skip_full_check; 19877 19878 ret = bpf_compute_live_registers(env); 19879 if (ret < 0) 19880 goto skip_full_check; 19881 19882 ret = mark_fastcall_patterns(env); 19883 if (ret < 0) 19884 goto skip_full_check; 19885 19886 ret = do_check_main(env); 19887 ret = ret ?: do_check_subprogs(env); 19888 19889 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 19890 ret = bpf_prog_offload_finalize(env); 19891 19892 skip_full_check: 19893 kvfree(env->explored_states); 19894 19895 /* might decrease stack depth, keep it before passes that 19896 * allocate additional slots. 19897 */ 19898 if (ret == 0) 19899 ret = bpf_remove_fastcall_spills_fills(env); 19900 19901 if (ret == 0) 19902 ret = check_max_stack_depth(env); 19903 19904 /* instruction rewrites happen after this point */ 19905 if (ret == 0) 19906 ret = bpf_optimize_bpf_loop(env); 19907 19908 if (is_priv) { 19909 if (ret == 0) 19910 bpf_opt_hard_wire_dead_code_branches(env); 19911 if (ret == 0) 19912 ret = bpf_opt_remove_dead_code(env); 19913 if (ret == 0) 19914 ret = bpf_opt_remove_nops(env); 19915 } else { 19916 if (ret == 0) 19917 sanitize_dead_code(env); 19918 } 19919 19920 if (ret == 0) 19921 /* program is valid, convert *(u32*)(ctx + off) accesses */ 19922 ret = bpf_convert_ctx_accesses(env); 19923 19924 if (ret == 0) 19925 ret = bpf_do_misc_fixups(env); 19926 19927 /* do 32-bit optimization after insn patching has done so those patched 19928 * insns could be handled correctly. 19929 */ 19930 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 19931 ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr); 19932 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 19933 : false; 19934 } 19935 19936 if (ret == 0) 19937 ret = bpf_fixup_call_args(env); 19938 19939 env->verification_time = ktime_get_ns() - start_time; 19940 print_verification_stats(env); 19941 env->prog->aux->verified_insns = env->insn_processed; 19942 19943 /* preserve original error even if log finalization is successful */ 19944 err = bpf_log_attr_finalize(attr_log, &env->log); 19945 if (err) 19946 ret = err; 19947 19948 if (ret) 19949 goto err_release_maps; 19950 19951 if (env->used_map_cnt) { 19952 /* if program passed verifier, update used_maps in bpf_prog_info */ 19953 env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0], 19954 env->used_map_cnt, 19955 GFP_KERNEL_ACCOUNT); 19956 19957 if (!env->prog->aux->used_maps) { 19958 ret = -ENOMEM; 19959 goto err_release_maps; 19960 } 19961 19962 memcpy(env->prog->aux->used_maps, env->used_maps, 19963 sizeof(env->used_maps[0]) * env->used_map_cnt); 19964 env->prog->aux->used_map_cnt = env->used_map_cnt; 19965 } 19966 if (env->used_btf_cnt) { 19967 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 19968 env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0], 19969 env->used_btf_cnt, 19970 GFP_KERNEL_ACCOUNT); 19971 if (!env->prog->aux->used_btfs) { 19972 ret = -ENOMEM; 19973 goto err_release_maps; 19974 } 19975 19976 memcpy(env->prog->aux->used_btfs, env->used_btfs, 19977 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 19978 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 19979 } 19980 if (env->used_map_cnt || env->used_btf_cnt) { 19981 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 19982 * bpf_ld_imm64 instructions 19983 */ 19984 convert_pseudo_ld_imm64(env); 19985 } 19986 19987 adjust_btf_func(env); 19988 19989 /* extension progs temporarily inherit the attach_type of their targets 19990 for verification purposes, so set it back to zero before returning 19991 */ 19992 if (env->prog->type == BPF_PROG_TYPE_EXT) 19993 env->prog->expected_attach_type = 0; 19994 19995 env->prog = __bpf_prog_select_runtime(env, env->prog, &ret); 19996 19997 err_release_maps: 19998 if (ret) 19999 release_insn_arrays(env); 20000 if (!env->prog->aux->used_maps) 20001 /* if we didn't copy map pointers into bpf_prog_info, release 20002 * them now. Otherwise free_used_maps() will release them. 20003 */ 20004 release_maps(env); 20005 if (!env->prog->aux->used_btfs) 20006 release_btfs(env); 20007 20008 *prog = env->prog; 20009 20010 module_put(env->attach_btf_mod); 20011 err_unlock: 20012 if (!is_priv) 20013 mutex_unlock(&bpf_verifier_lock); 20014 bpf_clear_insn_aux_data(env, 0, env->prog->len); 20015 err_free_env: 20016 bpf_stack_liveness_free(env); 20017 kvfree(env->cfg.insn_postorder); 20018 kvfree(env->scc_info); 20019 kvfree(env->succ); 20020 kvfree(env->gotox_tmp_buf); 20021 vfree(env->insn_aux_data); 20022 kvfree(env); 20023 return ret; 20024 } 20025