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 int ref_set_non_owning(struct bpf_verifier_env *env, 209 struct bpf_reg_state *reg); 210 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg); 211 static inline bool in_sleepable_context(struct bpf_verifier_env *env); 212 static const char *non_sleepable_context_description(struct bpf_verifier_env *env); 213 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 214 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 215 216 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 217 struct bpf_map *map, 218 bool unpriv, bool poison) 219 { 220 unpriv |= bpf_map_ptr_unpriv(aux); 221 aux->map_ptr_state.unpriv = unpriv; 222 aux->map_ptr_state.poison = poison; 223 aux->map_ptr_state.map_ptr = map; 224 } 225 226 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 227 { 228 bool poisoned = bpf_map_key_poisoned(aux); 229 230 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 231 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 232 } 233 234 static void update_ref_obj(struct ref_obj_desc *ref_obj, struct bpf_reg_state *reg) 235 { 236 ref_obj->id = reg->id; 237 ref_obj->parent_id = reg->parent_id; 238 ref_obj->cnt++; 239 } 240 241 static int validate_ref_obj(struct bpf_verifier_env *env, struct ref_obj_desc *ref_obj) 242 { 243 if (ref_obj->cnt > 1) { 244 verifier_bug(env, "function expects only one referenced object but got %d\n", 245 ref_obj->cnt); 246 return -EFAULT; 247 } 248 249 return 0; 250 } 251 252 struct bpf_call_arg_meta { 253 struct bpf_map_desc map; 254 struct bpf_dynptr_desc dynptr; 255 struct ref_obj_desc ref_obj; 256 bool raw_mode; 257 bool pkt_access; 258 u8 release_regno; 259 int regno; 260 int access_size; 261 int mem_size; 262 u64 msize_max_value; 263 int func_id; 264 struct btf *btf; 265 u32 btf_id; 266 struct btf *ret_btf; 267 u32 ret_btf_id; 268 u32 subprogno; 269 struct btf_field *kptr_field; 270 s64 const_map_key; 271 }; 272 273 struct bpf_kfunc_meta { 274 struct btf *btf; 275 const struct btf_type *proto; 276 const char *name; 277 const u32 *flags; 278 s32 id; 279 }; 280 281 struct btf *btf_vmlinux; 282 283 typedef struct argno { 284 int argno; 285 } argno_t; 286 287 static argno_t argno_from_reg(u32 regno) 288 { 289 return (argno_t){ .argno = regno }; 290 } 291 292 static argno_t argno_from_arg(u32 arg) 293 { 294 return (argno_t){ .argno = -arg }; 295 } 296 297 static int reg_from_argno(argno_t a) 298 { 299 if (a.argno >= 0) 300 return a.argno; 301 if (a.argno >= -MAX_BPF_FUNC_REG_ARGS) 302 return -a.argno; 303 return -1; 304 } 305 306 static int arg_from_argno(argno_t a) 307 { 308 if (a.argno < 0) 309 return -a.argno; 310 return -1; 311 } 312 313 static int arg_idx_from_argno(argno_t a) 314 { 315 return arg_from_argno(a) - 1; 316 } 317 318 static const char *btf_type_name(const struct btf *btf, u32 id) 319 { 320 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 321 } 322 323 static DEFINE_MUTEX(bpf_verifier_lock); 324 static DEFINE_MUTEX(bpf_percpu_ma_lock); 325 326 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 327 { 328 struct bpf_verifier_env *env = private_data; 329 va_list args; 330 331 if (!bpf_verifier_log_needed(&env->log)) 332 return; 333 334 va_start(args, fmt); 335 bpf_verifier_vlog(&env->log, fmt, args); 336 va_end(args); 337 } 338 339 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 340 struct bpf_reg_state *reg, 341 struct bpf_retval_range range, const char *ctx, 342 const char *reg_name) 343 { 344 bool unknown = true; 345 346 verbose(env, "%s the register %s has", ctx, reg_name); 347 if (reg_smin(reg) > S64_MIN) { 348 verbose(env, " smin=%lld", reg_smin(reg)); 349 unknown = false; 350 } 351 if (reg_smax(reg) < S64_MAX) { 352 verbose(env, " smax=%lld", reg_smax(reg)); 353 unknown = false; 354 } 355 if (unknown) 356 verbose(env, " unknown scalar value"); 357 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 358 } 359 360 static bool reg_not_null(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 361 { 362 enum bpf_reg_type type; 363 364 type = reg->type; 365 if (type_may_be_null(type)) 366 return false; 367 368 type = base_type(type); 369 return type == PTR_TO_SOCKET || 370 type == PTR_TO_TCP_SOCK || 371 type == PTR_TO_MAP_VALUE || 372 type == PTR_TO_MAP_KEY || 373 type == PTR_TO_SOCK_COMMON || 374 (type == PTR_TO_BTF_ID && is_trusted_reg(env, reg)) || 375 (type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) || 376 type == CONST_PTR_TO_MAP; 377 } 378 379 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 380 { 381 struct btf_record *rec = NULL; 382 struct btf_struct_meta *meta; 383 384 if (reg->type == PTR_TO_MAP_VALUE) { 385 rec = reg->map_ptr->record; 386 } else if (type_is_ptr_alloc_obj(reg->type)) { 387 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 388 if (meta) 389 rec = meta->record; 390 } 391 return rec; 392 } 393 394 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog) 395 { 396 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 397 398 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 399 } 400 401 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog) 402 { 403 const struct btf_type *type, *func, *func_proto; 404 const struct btf *btf = env->prog->aux->btf; 405 u32 btf_id; 406 407 btf_id = env->prog->aux->func_info[subprog].type_id; 408 409 func = btf_type_by_id(btf, btf_id); 410 if (verifier_bug_if(!func, env, "btf_id %u not found", btf_id)) 411 return false; 412 413 func_proto = btf_type_by_id(btf, func->type); 414 if (!func_proto) 415 return false; 416 417 type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 418 if (!type) 419 return false; 420 421 return btf_type_is_void(type); 422 } 423 424 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 425 { 426 struct bpf_func_info *info; 427 428 if (!env->prog->aux->func_info) 429 return ""; 430 431 info = &env->prog->aux->func_info[subprog]; 432 return btf_type_name(env->prog->aux->btf, info->type_id); 433 } 434 435 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 436 { 437 struct bpf_subprog_info *info = subprog_info(env, subprog); 438 439 info->is_cb = true; 440 info->is_async_cb = true; 441 info->is_exception_cb = true; 442 } 443 444 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 445 { 446 return subprog_info(env, subprog)->is_exception_cb; 447 } 448 449 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 450 { 451 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK); 452 } 453 454 static bool type_is_rdonly_mem(u32 type) 455 { 456 return type & MEM_RDONLY; 457 } 458 459 static bool is_acquire_function(enum bpf_func_id func_id, 460 const struct bpf_map *map) 461 { 462 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 463 464 if (func_id == BPF_FUNC_sk_lookup_tcp || 465 func_id == BPF_FUNC_sk_lookup_udp || 466 func_id == BPF_FUNC_skc_lookup_tcp || 467 func_id == BPF_FUNC_ringbuf_reserve || 468 func_id == BPF_FUNC_kptr_xchg) 469 return true; 470 471 if (func_id == BPF_FUNC_map_lookup_elem && 472 (map_type == BPF_MAP_TYPE_SOCKMAP || 473 map_type == BPF_MAP_TYPE_SOCKHASH)) 474 return true; 475 476 return false; 477 } 478 479 static bool is_ptr_cast_function(enum bpf_func_id func_id) 480 { 481 return func_id == BPF_FUNC_tcp_sock || 482 func_id == BPF_FUNC_sk_fullsock || 483 func_id == BPF_FUNC_skc_to_tcp_sock || 484 func_id == BPF_FUNC_skc_to_tcp6_sock || 485 func_id == BPF_FUNC_skc_to_udp6_sock || 486 func_id == BPF_FUNC_skc_to_mptcp_sock || 487 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 488 func_id == BPF_FUNC_skc_to_tcp_request_sock; 489 } 490 491 static bool is_sync_callback_calling_kfunc(u32 btf_id); 492 static bool is_async_callback_calling_kfunc(u32 btf_id); 493 static bool is_callback_calling_kfunc(u32 btf_id); 494 495 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id); 496 static bool is_task_work_add_kfunc(u32 func_id); 497 498 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 499 { 500 return func_id == BPF_FUNC_for_each_map_elem || 501 func_id == BPF_FUNC_find_vma || 502 func_id == BPF_FUNC_loop || 503 func_id == BPF_FUNC_user_ringbuf_drain; 504 } 505 506 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 507 { 508 return func_id == BPF_FUNC_timer_set_callback; 509 } 510 511 static bool is_callback_calling_function(enum bpf_func_id func_id) 512 { 513 return is_sync_callback_calling_function(func_id) || 514 is_async_callback_calling_function(func_id); 515 } 516 517 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn) 518 { 519 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 520 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 521 } 522 523 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn) 524 { 525 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 526 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 527 } 528 529 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn) 530 { 531 /* bpf_timer callbacks are never sleepable. */ 532 if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback) 533 return false; 534 535 /* bpf_wq and bpf_task_work callbacks are always sleepable. */ 536 if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 537 (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm))) 538 return true; 539 540 verifier_bug(env, "unhandled async callback in is_async_cb_sleepable"); 541 return false; 542 } 543 544 bool bpf_is_may_goto_insn(struct bpf_insn *insn) 545 { 546 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 547 } 548 549 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 550 { 551 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 552 553 /* We need to check that slots between [spi - nr_slots + 1, spi] are 554 * within [0, allocated_stack). 555 * 556 * Please note that the spi grows downwards. For example, a dynptr 557 * takes the size of two stack slots; the first slot will be at 558 * spi and the second slot will be at spi - 1. 559 */ 560 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 561 } 562 563 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 564 const char *obj_kind, int nr_slots) 565 { 566 int off, spi; 567 568 if (!tnum_is_const(reg->var_off)) { 569 verbose(env, "%s has to be at a constant offset\n", obj_kind); 570 return -EINVAL; 571 } 572 573 off = reg->var_off.value; 574 if (off % BPF_REG_SIZE) { 575 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 576 return -EINVAL; 577 } 578 579 spi = bpf_get_spi(off); 580 if (spi + 1 < nr_slots) { 581 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 582 return -EINVAL; 583 } 584 585 if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots)) 586 return -ERANGE; 587 return spi; 588 } 589 590 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 591 { 592 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 593 } 594 595 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 596 { 597 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 598 } 599 600 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 601 { 602 return stack_slot_obj_get_spi(env, reg, "irq_flag", 1); 603 } 604 605 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 606 { 607 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 608 case DYNPTR_TYPE_LOCAL: 609 return BPF_DYNPTR_TYPE_LOCAL; 610 case DYNPTR_TYPE_RINGBUF: 611 return BPF_DYNPTR_TYPE_RINGBUF; 612 case DYNPTR_TYPE_SKB: 613 return BPF_DYNPTR_TYPE_SKB; 614 case DYNPTR_TYPE_XDP: 615 return BPF_DYNPTR_TYPE_XDP; 616 case DYNPTR_TYPE_SKB_META: 617 return BPF_DYNPTR_TYPE_SKB_META; 618 case DYNPTR_TYPE_FILE: 619 return BPF_DYNPTR_TYPE_FILE; 620 default: 621 return BPF_DYNPTR_TYPE_INVALID; 622 } 623 } 624 625 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 626 { 627 switch (type) { 628 case BPF_DYNPTR_TYPE_LOCAL: 629 return DYNPTR_TYPE_LOCAL; 630 case BPF_DYNPTR_TYPE_RINGBUF: 631 return DYNPTR_TYPE_RINGBUF; 632 case BPF_DYNPTR_TYPE_SKB: 633 return DYNPTR_TYPE_SKB; 634 case BPF_DYNPTR_TYPE_XDP: 635 return DYNPTR_TYPE_XDP; 636 case BPF_DYNPTR_TYPE_SKB_META: 637 return DYNPTR_TYPE_SKB_META; 638 case BPF_DYNPTR_TYPE_FILE: 639 return DYNPTR_TYPE_FILE; 640 default: 641 return 0; 642 } 643 } 644 645 static bool dynptr_type_referenced(enum bpf_dynptr_type type) 646 { 647 return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE; 648 } 649 650 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 651 enum bpf_dynptr_type type, 652 bool first_slot, int id, int parent_id); 653 654 655 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 656 struct bpf_reg_state *sreg1, 657 struct bpf_reg_state *sreg2, 658 enum bpf_dynptr_type type, int parent_id) 659 { 660 int id = ++env->id_gen; 661 662 __mark_dynptr_reg(sreg1, type, true, id, parent_id); 663 __mark_dynptr_reg(sreg2, type, false, id, parent_id); 664 } 665 666 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 667 struct bpf_reg_state *reg, 668 enum bpf_dynptr_type type) 669 { 670 __mark_dynptr_reg(reg, type, true, ++env->id_gen, 0); 671 } 672 673 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 674 struct bpf_func_state *state, int spi); 675 676 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 677 enum bpf_arg_type arg_type, int insn_idx, 678 struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr) 679 { 680 struct bpf_func_state *state = bpf_func(env, reg); 681 int spi, i, err, parent_id = 0; 682 enum bpf_dynptr_type type; 683 684 spi = dynptr_get_spi(env, reg); 685 if (spi < 0) 686 return spi; 687 688 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 689 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 690 * to ensure that for the following example: 691 * [d1][d1][d2][d2] 692 * spi 3 2 1 0 693 * So marking spi = 2 should lead to destruction of both d1 and d2. In 694 * case they do belong to same dynptr, second call won't see slot_type 695 * as STACK_DYNPTR and will simply skip destruction. 696 */ 697 err = destroy_if_dynptr_stack_slot(env, state, spi); 698 if (err) 699 return err; 700 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 701 if (err) 702 return err; 703 704 for (i = 0; i < BPF_REG_SIZE; i++) { 705 state->stack[spi].slot_type[i] = STACK_DYNPTR; 706 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 707 } 708 709 type = arg_to_dynptr_type(arg_type); 710 if (type == BPF_DYNPTR_TYPE_INVALID) 711 return -EINVAL; 712 713 if (dynptr->type == BPF_DYNPTR_TYPE_INVALID) { /* dynptr constructors */ 714 err = validate_ref_obj(env, ref_obj); 715 if (err) 716 return err; 717 718 /* Track parent's id if the parent is a referenced object */ 719 parent_id = ref_obj->id; 720 721 if (dynptr_type_referenced(type)) { 722 int id; 723 724 /* 725 * Create an intermediate reference that tracks the referenced 726 * object for the referenced dynptr. Freeing a referenced dynptr 727 * through helpers/kfuncs will invalidate all clones. 728 */ 729 id = acquire_reference(env, insn_idx, parent_id); 730 if (id < 0) 731 return id; 732 733 parent_id = id; 734 } 735 } else { /* bpf_dynptr_clone() */ 736 parent_id = dynptr->parent_id; 737 } 738 739 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 740 &state->stack[spi - 1].spilled_ptr, type, parent_id); 741 742 return 0; 743 } 744 745 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_stack_state *stack) 746 { 747 int i; 748 749 for (i = 0; i < BPF_REG_SIZE; i++) { 750 stack[0].slot_type[i] = STACK_INVALID; 751 stack[1].slot_type[i] = STACK_INVALID; 752 } 753 754 bpf_mark_reg_not_init(env, &stack[0].spilled_ptr); 755 bpf_mark_reg_not_init(env, &stack[1].spilled_ptr); 756 } 757 758 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 759 { 760 struct bpf_func_state *state = bpf_func(env, reg); 761 int spi; 762 763 spi = dynptr_get_spi(env, reg); 764 if (spi < 0) 765 return spi; 766 767 /* 768 * For referenced dynptr, release the parent ref which cascades to 769 * all clones and derived slices. For non-referenced dynptr, only 770 * the dynptr and slices derived from it will be invalidated. 771 */ 772 reg = &state->stack[spi].spilled_ptr; 773 return release_reference(env, dynptr_type_referenced(reg->dynptr.type) 774 ? reg->parent_id 775 : reg->id); 776 } 777 778 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 779 struct bpf_reg_state *reg); 780 781 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 782 { 783 if (!env->allow_ptr_leaks) 784 bpf_mark_reg_not_init(env, reg); 785 else 786 __mark_reg_unknown(env, reg); 787 } 788 789 static int dynptr_ref_cnt(struct bpf_verifier_env *env, int v_parent_id) 790 { 791 struct bpf_stack_state *stack; 792 struct bpf_func_state *state; 793 struct bpf_reg_state *reg; 794 int ref_cnt = 0; 795 796 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, 1 << STACK_DYNPTR, ({ 797 if (!stack || stack->slot_type[0] != STACK_DYNPTR) 798 continue; 799 if (!stack->spilled_ptr.dynptr.first_slot) 800 continue; 801 if (stack->spilled_ptr.parent_id == v_parent_id) 802 ref_cnt++; 803 })); 804 805 return ref_cnt; 806 } 807 808 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 809 struct bpf_func_state *state, int spi) 810 { 811 int err = 0; 812 813 /* We always ensure that STACK_DYNPTR is never set partially, 814 * hence just checking for slot_type[0] is enough. This is 815 * different for STACK_SPILL, where it may be only set for 816 * 1 byte, so code has to use is_spilled_reg. 817 */ 818 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 819 return 0; 820 821 /* Reposition spi to first slot */ 822 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 823 spi = spi + 1; 824 825 /* 826 * A referenced dynptr can be overwritten only if there is at 827 * least one other dynptr sharing the same virtual ref parent, 828 * ensuring the reference can still be properly released. 829 */ 830 if (dynptr_type_referenced(state->stack[spi].spilled_ptr.dynptr.type) && 831 dynptr_ref_cnt(env, state->stack[spi].spilled_ptr.parent_id) <= 1) { 832 verbose(env, "cannot overwrite referenced dynptr\n"); 833 return -EINVAL; 834 } 835 836 /* Invalidate the dynptr and any derived slices */ 837 err = release_reference(env, state->stack[spi].spilled_ptr.id); 838 if (!err) { 839 mark_stack_slot_scratched(env, spi); 840 mark_stack_slot_scratched(env, spi - 1); 841 } 842 843 return err; 844 } 845 846 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 847 { 848 int spi; 849 850 if (reg->type == CONST_PTR_TO_DYNPTR) 851 return false; 852 853 spi = dynptr_get_spi(env, reg); 854 855 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 856 * error because this just means the stack state hasn't been updated yet. 857 * We will do check_mem_access to check and update stack bounds later. 858 */ 859 if (spi < 0 && spi != -ERANGE) 860 return false; 861 862 /* We don't need to check if the stack slots are marked by previous 863 * dynptr initializations because we allow overwriting existing unreferenced 864 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 865 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 866 * touching are completely destructed before we reinitialize them for a new 867 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 868 * instead of delaying it until the end where the user will get "Unreleased 869 * reference" error. 870 */ 871 return true; 872 } 873 874 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 875 { 876 struct bpf_func_state *state = bpf_func(env, reg); 877 int i, spi; 878 879 /* This already represents first slot of initialized bpf_dynptr. 880 * 881 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 882 * check_func_arg_reg_off's logic, so we don't need to check its 883 * offset and alignment. 884 */ 885 if (reg->type == CONST_PTR_TO_DYNPTR) 886 return true; 887 888 spi = dynptr_get_spi(env, reg); 889 if (spi < 0) 890 return false; 891 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 892 return false; 893 894 for (i = 0; i < BPF_REG_SIZE; i++) { 895 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 896 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 897 return false; 898 } 899 900 return true; 901 } 902 903 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 904 enum bpf_arg_type arg_type) 905 { 906 struct bpf_func_state *state = bpf_func(env, reg); 907 enum bpf_dynptr_type dynptr_type; 908 int spi; 909 910 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 911 if (arg_type == ARG_PTR_TO_DYNPTR) 912 return true; 913 914 dynptr_type = arg_to_dynptr_type(arg_type); 915 if (reg->type == CONST_PTR_TO_DYNPTR) { 916 return reg->dynptr.type == dynptr_type; 917 } else { 918 spi = dynptr_get_spi(env, reg); 919 if (spi < 0) 920 return false; 921 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 922 } 923 } 924 925 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 926 927 static bool in_rcu_cs(struct bpf_verifier_env *env); 928 929 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 930 931 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 932 struct bpf_kfunc_call_arg_meta *meta, 933 struct bpf_reg_state *reg, int insn_idx, 934 struct btf *btf, u32 btf_id, int nr_slots) 935 { 936 struct bpf_func_state *state = bpf_func(env, reg); 937 int spi, i, j, id; 938 939 spi = iter_get_spi(env, reg, nr_slots); 940 if (spi < 0) 941 return spi; 942 943 id = acquire_reference(env, insn_idx, 0); 944 if (id < 0) 945 return id; 946 947 for (i = 0; i < nr_slots; i++) { 948 struct bpf_stack_state *slot = &state->stack[spi - i]; 949 struct bpf_reg_state *st = &slot->spilled_ptr; 950 951 __mark_reg_known_zero(st); 952 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 953 if (is_kfunc_rcu_protected(meta)) { 954 if (in_rcu_cs(env)) 955 st->type |= MEM_RCU; 956 else 957 st->type |= PTR_UNTRUSTED; 958 } 959 st->id = i == 0 ? id : 0; 960 st->iter.btf = btf; 961 st->iter.btf_id = btf_id; 962 st->iter.state = BPF_ITER_STATE_ACTIVE; 963 st->iter.depth = 0; 964 965 for (j = 0; j < BPF_REG_SIZE; j++) 966 slot->slot_type[j] = STACK_ITER; 967 968 mark_stack_slot_scratched(env, spi - i); 969 } 970 971 return 0; 972 } 973 974 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 975 struct bpf_reg_state *reg, int nr_slots) 976 { 977 struct bpf_func_state *state = bpf_func(env, reg); 978 int spi, i, j; 979 980 spi = iter_get_spi(env, reg, nr_slots); 981 if (spi < 0) 982 return spi; 983 984 for (i = 0; i < nr_slots; i++) { 985 struct bpf_stack_state *slot = &state->stack[spi - i]; 986 struct bpf_reg_state *st = &slot->spilled_ptr; 987 988 if (i == 0) 989 WARN_ON_ONCE(release_reference(env, st->id)); 990 991 bpf_mark_reg_not_init(env, st); 992 993 for (j = 0; j < BPF_REG_SIZE; j++) 994 slot->slot_type[j] = STACK_INVALID; 995 996 mark_stack_slot_scratched(env, spi - i); 997 } 998 999 return 0; 1000 } 1001 1002 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1003 struct bpf_reg_state *reg, int nr_slots) 1004 { 1005 struct bpf_func_state *state = bpf_func(env, reg); 1006 int spi, i, j; 1007 1008 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1009 * will do check_mem_access to check and update stack bounds later, so 1010 * return true for that case. 1011 */ 1012 spi = iter_get_spi(env, reg, nr_slots); 1013 if (spi == -ERANGE) 1014 return true; 1015 if (spi < 0) 1016 return false; 1017 1018 for (i = 0; i < nr_slots; i++) { 1019 struct bpf_stack_state *slot = &state->stack[spi - i]; 1020 1021 for (j = 0; j < BPF_REG_SIZE; j++) 1022 if (slot->slot_type[j] == STACK_ITER) 1023 return false; 1024 } 1025 1026 return true; 1027 } 1028 1029 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1030 struct btf *btf, u32 btf_id, int nr_slots) 1031 { 1032 struct bpf_func_state *state = bpf_func(env, reg); 1033 int spi, i, j; 1034 1035 spi = iter_get_spi(env, reg, nr_slots); 1036 if (spi < 0) 1037 return -EINVAL; 1038 1039 for (i = 0; i < nr_slots; i++) { 1040 struct bpf_stack_state *slot = &state->stack[spi - i]; 1041 struct bpf_reg_state *st = &slot->spilled_ptr; 1042 1043 if (st->type & PTR_UNTRUSTED) 1044 return -EPROTO; 1045 /* only main (first) slot has id set */ 1046 if (i == 0 && !st->id) 1047 return -EINVAL; 1048 if (i != 0 && st->id) 1049 return -EINVAL; 1050 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1051 return -EINVAL; 1052 1053 for (j = 0; j < BPF_REG_SIZE; j++) 1054 if (slot->slot_type[j] != STACK_ITER) 1055 return -EINVAL; 1056 } 1057 1058 return 0; 1059 } 1060 1061 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx); 1062 static int release_irq_state(struct bpf_verifier_state *state, int id); 1063 1064 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env, 1065 struct bpf_kfunc_call_arg_meta *meta, 1066 struct bpf_reg_state *reg, int insn_idx, 1067 int kfunc_class) 1068 { 1069 struct bpf_func_state *state = bpf_func(env, reg); 1070 struct bpf_stack_state *slot; 1071 struct bpf_reg_state *st; 1072 int spi, i, id; 1073 1074 spi = irq_flag_get_spi(env, reg); 1075 if (spi < 0) 1076 return spi; 1077 1078 id = acquire_irq_state(env, insn_idx); 1079 if (id < 0) 1080 return id; 1081 1082 slot = &state->stack[spi]; 1083 st = &slot->spilled_ptr; 1084 1085 __mark_reg_known_zero(st); 1086 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1087 st->id = id; 1088 st->irq.kfunc_class = kfunc_class; 1089 1090 for (i = 0; i < BPF_REG_SIZE; i++) 1091 slot->slot_type[i] = STACK_IRQ_FLAG; 1092 1093 mark_stack_slot_scratched(env, spi); 1094 return 0; 1095 } 1096 1097 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1098 int kfunc_class) 1099 { 1100 struct bpf_func_state *state = bpf_func(env, reg); 1101 struct bpf_stack_state *slot; 1102 struct bpf_reg_state *st; 1103 int spi, i, err; 1104 1105 spi = irq_flag_get_spi(env, reg); 1106 if (spi < 0) 1107 return spi; 1108 1109 slot = &state->stack[spi]; 1110 st = &slot->spilled_ptr; 1111 1112 if (st->irq.kfunc_class != kfunc_class) { 1113 const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1114 const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1115 1116 verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n", 1117 flag_kfunc, used_kfunc); 1118 return -EINVAL; 1119 } 1120 1121 err = release_irq_state(env->cur_state, st->id); 1122 WARN_ON_ONCE(err && err != -EACCES); 1123 if (err) { 1124 int insn_idx = 0; 1125 1126 for (int i = 0; i < env->cur_state->acquired_refs; i++) { 1127 if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) { 1128 insn_idx = env->cur_state->refs[i].insn_idx; 1129 break; 1130 } 1131 } 1132 1133 verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n", 1134 env->cur_state->active_irq_id, insn_idx); 1135 return err; 1136 } 1137 1138 bpf_mark_reg_not_init(env, st); 1139 1140 for (i = 0; i < BPF_REG_SIZE; i++) 1141 slot->slot_type[i] = STACK_INVALID; 1142 1143 mark_stack_slot_scratched(env, spi); 1144 return 0; 1145 } 1146 1147 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1148 { 1149 struct bpf_func_state *state = bpf_func(env, reg); 1150 struct bpf_stack_state *slot; 1151 int spi, i; 1152 1153 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1154 * will do check_mem_access to check and update stack bounds later, so 1155 * return true for that case. 1156 */ 1157 spi = irq_flag_get_spi(env, reg); 1158 if (spi == -ERANGE) 1159 return true; 1160 if (spi < 0) 1161 return false; 1162 1163 slot = &state->stack[spi]; 1164 1165 for (i = 0; i < BPF_REG_SIZE; i++) 1166 if (slot->slot_type[i] == STACK_IRQ_FLAG) 1167 return false; 1168 return true; 1169 } 1170 1171 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1172 { 1173 struct bpf_func_state *state = bpf_func(env, reg); 1174 struct bpf_stack_state *slot; 1175 struct bpf_reg_state *st; 1176 int spi, i; 1177 1178 spi = irq_flag_get_spi(env, reg); 1179 if (spi < 0) 1180 return -EINVAL; 1181 1182 slot = &state->stack[spi]; 1183 st = &slot->spilled_ptr; 1184 1185 if (!st->id) 1186 return -EINVAL; 1187 1188 for (i = 0; i < BPF_REG_SIZE; i++) 1189 if (slot->slot_type[i] != STACK_IRQ_FLAG) 1190 return -EINVAL; 1191 return 0; 1192 } 1193 1194 /* Check if given stack slot is "special": 1195 * - spilled register state (STACK_SPILL); 1196 * - dynptr state (STACK_DYNPTR); 1197 * - iter state (STACK_ITER). 1198 * - irq flag state (STACK_IRQ_FLAG) 1199 */ 1200 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1201 { 1202 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1203 1204 switch (type) { 1205 case STACK_SPILL: 1206 case STACK_DYNPTR: 1207 case STACK_ITER: 1208 case STACK_IRQ_FLAG: 1209 return true; 1210 case STACK_INVALID: 1211 case STACK_POISON: 1212 case STACK_MISC: 1213 case STACK_ZERO: 1214 return false; 1215 default: 1216 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1217 return true; 1218 } 1219 } 1220 1221 /* The reg state of a pointer or a bounded scalar was saved when 1222 * it was spilled to the stack. 1223 */ 1224 1225 /* 1226 * Mark stack slot as STACK_MISC, unless it is already: 1227 * - STACK_INVALID, in which case they are equivalent. 1228 * - STACK_ZERO, in which case we preserve more precise STACK_ZERO. 1229 * - STACK_POISON, which truly forbids access to the slot. 1230 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged 1231 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is 1232 * unnecessary as both are considered equivalent when loading data and pruning, 1233 * in case of unprivileged mode it will be incorrect to allow reads of invalid 1234 * slots. 1235 */ 1236 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1237 { 1238 if (*stype == STACK_ZERO) 1239 return; 1240 if (*stype == STACK_INVALID || *stype == STACK_POISON) 1241 return; 1242 *stype = STACK_MISC; 1243 } 1244 1245 static void scrub_spilled_slot(u8 *stype) 1246 { 1247 if (*stype != STACK_INVALID && *stype != STACK_POISON) 1248 *stype = STACK_MISC; 1249 } 1250 1251 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1252 * small to hold src. This is different from krealloc since we don't want to preserve 1253 * the contents of dst. 1254 * 1255 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1256 * not be allocated. 1257 */ 1258 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1259 { 1260 size_t alloc_bytes; 1261 void *orig = dst; 1262 size_t bytes; 1263 1264 if (ZERO_OR_NULL_PTR(src)) 1265 goto out; 1266 1267 if (unlikely(check_mul_overflow(n, size, &bytes))) 1268 return NULL; 1269 1270 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1271 dst = krealloc(orig, alloc_bytes, flags); 1272 if (!dst) { 1273 kfree(orig); 1274 return NULL; 1275 } 1276 1277 memcpy(dst, src, bytes); 1278 out: 1279 return dst ? dst : ZERO_SIZE_PTR; 1280 } 1281 1282 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1283 * small to hold new_n items. new items are zeroed out if the array grows. 1284 * 1285 * Contrary to krealloc_array, does not free arr if new_n is zero. 1286 */ 1287 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1288 { 1289 size_t alloc_size; 1290 void *new_arr; 1291 1292 if (!new_n || old_n == new_n) 1293 goto out; 1294 1295 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1296 new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT); 1297 if (!new_arr) { 1298 kfree(arr); 1299 return NULL; 1300 } 1301 arr = new_arr; 1302 1303 if (new_n > old_n) 1304 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1305 1306 out: 1307 return arr ? arr : ZERO_SIZE_PTR; 1308 } 1309 1310 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) 1311 { 1312 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1313 sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT); 1314 if (!dst->refs) 1315 return -ENOMEM; 1316 1317 dst->acquired_refs = src->acquired_refs; 1318 dst->active_locks = src->active_locks; 1319 dst->active_preempt_locks = src->active_preempt_locks; 1320 dst->active_rcu_locks = src->active_rcu_locks; 1321 dst->active_irq_id = src->active_irq_id; 1322 dst->active_lock_id = src->active_lock_id; 1323 dst->active_lock_ptr = src->active_lock_ptr; 1324 return 0; 1325 } 1326 1327 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1328 { 1329 size_t n = src->allocated_stack / BPF_REG_SIZE; 1330 1331 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1332 GFP_KERNEL_ACCOUNT); 1333 if (!dst->stack) 1334 return -ENOMEM; 1335 1336 dst->allocated_stack = src->allocated_stack; 1337 1338 /* copy stack args state */ 1339 n = src->out_stack_arg_cnt; 1340 if (n) { 1341 dst->stack_arg_regs = copy_array(dst->stack_arg_regs, src->stack_arg_regs, n, 1342 sizeof(struct bpf_reg_state), 1343 GFP_KERNEL_ACCOUNT); 1344 if (!dst->stack_arg_regs) 1345 return -ENOMEM; 1346 } 1347 1348 dst->out_stack_arg_cnt = src->out_stack_arg_cnt; 1349 return 0; 1350 } 1351 1352 static int resize_reference_state(struct bpf_verifier_state *state, size_t n) 1353 { 1354 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1355 sizeof(struct bpf_reference_state)); 1356 if (!state->refs) 1357 return -ENOMEM; 1358 1359 state->acquired_refs = n; 1360 return 0; 1361 } 1362 1363 /* Possibly update state->allocated_stack to be at least size bytes. Also 1364 * possibly update the function's high-water mark in its bpf_subprog_info. 1365 */ 1366 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1367 { 1368 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1369 1370 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1371 size = round_up(size, BPF_REG_SIZE); 1372 n = size / BPF_REG_SIZE; 1373 1374 if (old_n >= n) 1375 return 0; 1376 1377 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1378 if (!state->stack) 1379 return -ENOMEM; 1380 1381 state->allocated_stack = size; 1382 1383 /* update known max for given subprogram */ 1384 if (env->subprog_info[state->subprogno].stack_depth < size) 1385 env->subprog_info[state->subprogno].stack_depth = size; 1386 1387 return 0; 1388 } 1389 1390 static int grow_stack_arg_slots(struct bpf_verifier_env *env, 1391 struct bpf_func_state *state, int cnt) 1392 { 1393 size_t old_n = state->out_stack_arg_cnt; 1394 1395 if (old_n >= cnt) 1396 return 0; 1397 1398 state->stack_arg_regs = realloc_array(state->stack_arg_regs, old_n, cnt, 1399 sizeof(struct bpf_reg_state)); 1400 if (!state->stack_arg_regs) 1401 return -ENOMEM; 1402 1403 state->out_stack_arg_cnt = cnt; 1404 return 0; 1405 } 1406 1407 /* Acquire a pointer id from the env and update the state->refs to include 1408 * this new pointer reference. 1409 * On success, returns a valid pointer id to associate with the register 1410 * On failure, returns a negative errno. 1411 */ 1412 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1413 { 1414 struct bpf_verifier_state *state = env->cur_state; 1415 int new_ofs = state->acquired_refs; 1416 int err; 1417 1418 err = resize_reference_state(state, state->acquired_refs + 1); 1419 if (err) 1420 return NULL; 1421 state->refs[new_ofs].insn_idx = insn_idx; 1422 1423 return &state->refs[new_ofs]; 1424 } 1425 1426 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id) 1427 { 1428 struct bpf_reference_state *s; 1429 1430 s = acquire_reference_state(env, insn_idx); 1431 if (!s) 1432 return -ENOMEM; 1433 s->type = REF_TYPE_PTR; 1434 s->id = ++env->id_gen; 1435 s->parent_id = parent_id; 1436 return s->id; 1437 } 1438 1439 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type, 1440 int id, void *ptr) 1441 { 1442 struct bpf_verifier_state *state = env->cur_state; 1443 struct bpf_reference_state *s; 1444 1445 s = acquire_reference_state(env, insn_idx); 1446 if (!s) 1447 return -ENOMEM; 1448 s->type = type; 1449 s->id = id; 1450 s->ptr = ptr; 1451 1452 state->active_locks++; 1453 state->active_lock_id = id; 1454 state->active_lock_ptr = ptr; 1455 return 0; 1456 } 1457 1458 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx) 1459 { 1460 struct bpf_verifier_state *state = env->cur_state; 1461 struct bpf_reference_state *s; 1462 1463 s = acquire_reference_state(env, insn_idx); 1464 if (!s) 1465 return -ENOMEM; 1466 s->type = REF_TYPE_IRQ; 1467 s->id = ++env->id_gen; 1468 1469 state->active_irq_id = s->id; 1470 return s->id; 1471 } 1472 1473 static void release_reference_state(struct bpf_verifier_state *state, int idx) 1474 { 1475 int last_idx; 1476 size_t rem; 1477 1478 /* IRQ state requires the relative ordering of elements remaining the 1479 * same, since it relies on the refs array to behave as a stack, so that 1480 * it can detect out-of-order IRQ restore. Hence use memmove to shift 1481 * the array instead of swapping the final element into the deleted idx. 1482 */ 1483 last_idx = state->acquired_refs - 1; 1484 rem = state->acquired_refs - idx - 1; 1485 if (last_idx && idx != last_idx) 1486 memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem); 1487 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1488 state->acquired_refs--; 1489 return; 1490 } 1491 1492 static bool find_reference_state(struct bpf_verifier_state *state, int id) 1493 { 1494 int i; 1495 1496 for (i = 0; i < state->acquired_refs; i++) { 1497 if (state->refs[i].type != REF_TYPE_PTR) 1498 continue; 1499 if (state->refs[i].id == id) 1500 return true; 1501 } 1502 1503 return false; 1504 } 1505 1506 static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 1507 { 1508 return find_reference_state(env->cur_state, reg->id); 1509 } 1510 1511 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr) 1512 { 1513 void *prev_ptr = NULL; 1514 u32 prev_id = 0; 1515 int i; 1516 1517 for (i = 0; i < state->acquired_refs; i++) { 1518 if (state->refs[i].type == type && state->refs[i].id == id && 1519 state->refs[i].ptr == ptr) { 1520 release_reference_state(state, i); 1521 state->active_locks--; 1522 /* Reassign active lock (id, ptr). */ 1523 state->active_lock_id = prev_id; 1524 state->active_lock_ptr = prev_ptr; 1525 return 0; 1526 } 1527 if (state->refs[i].type & REF_TYPE_LOCK_MASK) { 1528 prev_id = state->refs[i].id; 1529 prev_ptr = state->refs[i].ptr; 1530 } 1531 } 1532 return -EINVAL; 1533 } 1534 1535 static int release_irq_state(struct bpf_verifier_state *state, int id) 1536 { 1537 u32 prev_id = 0; 1538 int i; 1539 1540 if (id != state->active_irq_id) 1541 return -EACCES; 1542 1543 for (i = 0; i < state->acquired_refs; i++) { 1544 if (state->refs[i].type != REF_TYPE_IRQ) 1545 continue; 1546 if (state->refs[i].id == id) { 1547 release_reference_state(state, i); 1548 state->active_irq_id = prev_id; 1549 return 0; 1550 } else { 1551 prev_id = state->refs[i].id; 1552 } 1553 } 1554 return -EINVAL; 1555 } 1556 1557 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type, 1558 int id, void *ptr) 1559 { 1560 int i; 1561 1562 for (i = 0; i < state->acquired_refs; i++) { 1563 struct bpf_reference_state *s = &state->refs[i]; 1564 1565 if (!(s->type & type)) 1566 continue; 1567 1568 if (s->id == id && s->ptr == ptr) 1569 return s; 1570 } 1571 return NULL; 1572 } 1573 1574 static void free_func_state(struct bpf_func_state *state) 1575 { 1576 if (!state) 1577 return; 1578 kfree(state->stack_arg_regs); 1579 kfree(state->stack); 1580 kfree(state); 1581 } 1582 1583 void bpf_clear_jmp_history(struct bpf_verifier_state *state) 1584 { 1585 kfree(state->jmp_history); 1586 state->jmp_history = NULL; 1587 state->jmp_history_cnt = 0; 1588 } 1589 1590 void bpf_free_verifier_state(struct bpf_verifier_state *state, 1591 bool free_self) 1592 { 1593 int i; 1594 1595 for (i = 0; i <= state->curframe; i++) { 1596 free_func_state(state->frame[i]); 1597 state->frame[i] = NULL; 1598 } 1599 kfree(state->refs); 1600 bpf_clear_jmp_history(state); 1601 if (free_self) 1602 kfree(state); 1603 } 1604 1605 /* copy verifier state from src to dst growing dst stack space 1606 * when necessary to accommodate larger src stack 1607 */ 1608 static int copy_func_state(struct bpf_func_state *dst, 1609 const struct bpf_func_state *src) 1610 { 1611 memcpy(dst, src, offsetof(struct bpf_func_state, stack)); 1612 return copy_stack_state(dst, src); 1613 } 1614 1615 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state, 1616 const struct bpf_verifier_state *src) 1617 { 1618 struct bpf_func_state *dst; 1619 int i, err; 1620 1621 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1622 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1623 GFP_KERNEL_ACCOUNT); 1624 if (!dst_state->jmp_history) 1625 return -ENOMEM; 1626 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1627 1628 /* if dst has more stack frames then src frame, free them, this is also 1629 * necessary in case of exceptional exits using bpf_throw. 1630 */ 1631 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1632 free_func_state(dst_state->frame[i]); 1633 dst_state->frame[i] = NULL; 1634 } 1635 err = copy_reference_state(dst_state, src); 1636 if (err) 1637 return err; 1638 dst_state->speculative = src->speculative; 1639 dst_state->in_sleepable = src->in_sleepable; 1640 dst_state->curframe = src->curframe; 1641 dst_state->branches = src->branches; 1642 dst_state->parent = src->parent; 1643 dst_state->first_insn_idx = src->first_insn_idx; 1644 dst_state->last_insn_idx = src->last_insn_idx; 1645 dst_state->dfs_depth = src->dfs_depth; 1646 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1647 dst_state->may_goto_depth = src->may_goto_depth; 1648 dst_state->equal_state = src->equal_state; 1649 for (i = 0; i <= src->curframe; i++) { 1650 dst = dst_state->frame[i]; 1651 if (!dst) { 1652 dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT); 1653 if (!dst) 1654 return -ENOMEM; 1655 dst_state->frame[i] = dst; 1656 } 1657 err = copy_func_state(dst, src->frame[i]); 1658 if (err) 1659 return err; 1660 } 1661 return 0; 1662 } 1663 1664 static u32 state_htab_size(struct bpf_verifier_env *env) 1665 { 1666 return env->prog->len; 1667 } 1668 1669 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx) 1670 { 1671 struct bpf_verifier_state *cur = env->cur_state; 1672 struct bpf_func_state *state = cur->frame[cur->curframe]; 1673 1674 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1675 } 1676 1677 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1678 { 1679 int fr; 1680 1681 if (a->curframe != b->curframe) 1682 return false; 1683 1684 for (fr = a->curframe; fr >= 0; fr--) 1685 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1686 return false; 1687 1688 return true; 1689 } 1690 1691 1692 void bpf_free_backedges(struct bpf_scc_visit *visit) 1693 { 1694 struct bpf_scc_backedge *backedge, *next; 1695 1696 for (backedge = visit->backedges; backedge; backedge = next) { 1697 bpf_free_verifier_state(&backedge->state, false); 1698 next = backedge->next; 1699 kfree(backedge); 1700 } 1701 visit->backedges = NULL; 1702 } 1703 1704 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1705 int *insn_idx, bool pop_log) 1706 { 1707 struct bpf_verifier_state *cur = env->cur_state; 1708 struct bpf_verifier_stack_elem *elem, *head = env->head; 1709 int err; 1710 1711 if (env->head == NULL) 1712 return -ENOENT; 1713 1714 if (cur) { 1715 err = bpf_copy_verifier_state(cur, &head->st); 1716 if (err) 1717 return err; 1718 } 1719 if (pop_log) 1720 bpf_vlog_reset(&env->log, head->log_pos); 1721 if (insn_idx) 1722 *insn_idx = head->insn_idx; 1723 if (prev_insn_idx) 1724 *prev_insn_idx = head->prev_insn_idx; 1725 elem = head->next; 1726 bpf_free_verifier_state(&head->st, false); 1727 kfree(head); 1728 env->head = elem; 1729 env->stack_size--; 1730 return 0; 1731 } 1732 1733 static bool error_recoverable_with_nospec(int err) 1734 { 1735 /* Should only return true for non-fatal errors that are allowed to 1736 * occur during speculative verification. For these we can insert a 1737 * nospec and the program might still be accepted. Do not include 1738 * something like ENOMEM because it is likely to re-occur for the next 1739 * architectural path once it has been recovered-from in all speculative 1740 * paths. 1741 */ 1742 return err == -EPERM || err == -EACCES || err == -EINVAL; 1743 } 1744 1745 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1746 int insn_idx, int prev_insn_idx, 1747 bool speculative) 1748 { 1749 struct bpf_verifier_state *cur = env->cur_state; 1750 struct bpf_verifier_stack_elem *elem; 1751 int err; 1752 1753 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 1754 if (!elem) 1755 return ERR_PTR(-ENOMEM); 1756 1757 elem->insn_idx = insn_idx; 1758 elem->prev_insn_idx = prev_insn_idx; 1759 elem->next = env->head; 1760 elem->log_pos = env->log.end_pos; 1761 env->head = elem; 1762 env->stack_size++; 1763 err = bpf_copy_verifier_state(&elem->st, cur); 1764 if (err) 1765 return ERR_PTR(-ENOMEM); 1766 elem->st.speculative |= speculative; 1767 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1768 verbose(env, "The sequence of %d jumps is too complex.\n", 1769 env->stack_size); 1770 return ERR_PTR(-E2BIG); 1771 } 1772 if (elem->st.parent) { 1773 ++elem->st.parent->branches; 1774 /* WARN_ON(branches > 2) technically makes sense here, 1775 * but 1776 * 1. speculative states will bump 'branches' for non-branch 1777 * instructions 1778 * 2. is_state_visited() heuristics may decide not to create 1779 * a new state for a sequence of branches and all such current 1780 * and cloned states will be pointing to a single parent state 1781 * which might have large 'branches' count. 1782 */ 1783 } 1784 return &elem->st; 1785 } 1786 1787 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno) 1788 { 1789 char *buf = env->tmp_arg_name; 1790 int len = sizeof(env->tmp_arg_name); 1791 int arg, regno = reg_from_argno(argno); 1792 1793 if (regno >= 0) { 1794 snprintf(buf, len, "R%d", regno); 1795 } else { 1796 arg = arg_from_argno(argno); 1797 snprintf(buf, len, "*(R11-%u)", (arg - MAX_BPF_FUNC_REG_ARGS) * BPF_REG_SIZE); 1798 } 1799 1800 return buf; 1801 } 1802 1803 static const int caller_saved[CALLER_SAVED_REGS] = { 1804 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1805 }; 1806 1807 /* This helper doesn't clear reg->id */ 1808 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1809 { 1810 reg->var_off = tnum_const(imm); 1811 reg->r64 = cnum64_from_urange(imm, imm); 1812 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 1813 } 1814 1815 /* Mark the unknown part of a register (variable offset or scalar value) as 1816 * known to have the value @imm. 1817 */ 1818 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1819 { 1820 /* Clear off and union(map_ptr, range) */ 1821 memset(((u8 *)reg) + sizeof(reg->type), 0, 1822 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1823 reg->id = 0; 1824 reg->parent_id = 0; 1825 ___mark_reg_known(reg, imm); 1826 } 1827 1828 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1829 { 1830 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1831 reg->r32 = cnum32_from_urange((u32)imm, (u32)imm); 1832 } 1833 1834 /* Mark the 'variable offset' part of a register as zero. This should be 1835 * used only on registers holding a pointer type. 1836 */ 1837 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1838 { 1839 __mark_reg_known(reg, 0); 1840 } 1841 1842 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1843 { 1844 __mark_reg_known(reg, 0); 1845 reg->type = SCALAR_VALUE; 1846 /* all scalars are assumed imprecise initially (unless unprivileged, 1847 * in which case everything is forced to be precise) 1848 */ 1849 reg->precise = !env->bpf_capable; 1850 } 1851 1852 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1853 struct bpf_reg_state *regs, u32 regno) 1854 { 1855 __mark_reg_known_zero(regs + regno); 1856 } 1857 1858 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1859 bool first_slot, int id, int parent_id) 1860 { 1861 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1862 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1863 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1864 */ 1865 __mark_reg_known_zero(reg); 1866 reg->type = CONST_PTR_TO_DYNPTR; 1867 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1868 reg->id = id; 1869 reg->parent_id = parent_id; 1870 reg->dynptr.type = type; 1871 reg->dynptr.first_slot = first_slot; 1872 } 1873 1874 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1875 { 1876 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1877 const struct bpf_map *map = reg->map_ptr; 1878 1879 if (map->inner_map_meta) { 1880 reg->type = CONST_PTR_TO_MAP; 1881 reg->map_ptr = map->inner_map_meta; 1882 /* transfer reg's id which is unique for every map_lookup_elem 1883 * as UID of the inner map. 1884 */ 1885 if (btf_record_has_field(map->inner_map_meta->record, 1886 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) { 1887 reg->map_uid = reg->id; 1888 } 1889 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1890 reg->type = PTR_TO_XDP_SOCK; 1891 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1892 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1893 reg->type = PTR_TO_SOCKET; 1894 } else { 1895 reg->type = PTR_TO_MAP_VALUE; 1896 } 1897 return; 1898 } 1899 1900 reg->type &= ~PTR_MAYBE_NULL; 1901 } 1902 1903 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1904 struct btf_field_graph_root *ds_head) 1905 { 1906 __mark_reg_known(®s[regno], ds_head->node_offset); 1907 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1908 regs[regno].btf = ds_head->btf; 1909 regs[regno].btf_id = ds_head->value_btf_id; 1910 } 1911 1912 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1913 { 1914 return type_is_pkt_pointer(reg->type); 1915 } 1916 1917 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1918 { 1919 return reg_is_pkt_pointer(reg) || 1920 reg->type == PTR_TO_PACKET_END; 1921 } 1922 1923 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1924 { 1925 return base_type(reg->type) == PTR_TO_MEM && 1926 (reg->type & 1927 (DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META)); 1928 } 1929 1930 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1931 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1932 enum bpf_reg_type which) 1933 { 1934 /* The register can already have a range from prior markings. 1935 * This is fine as long as it hasn't been advanced from its 1936 * origin. 1937 */ 1938 return reg->type == which && 1939 reg->id == 0 && 1940 tnum_equals_const(reg->var_off, 0); 1941 } 1942 1943 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1944 { 1945 reg->r32 = CNUM32_UNBOUNDED; 1946 } 1947 1948 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1949 { 1950 reg->r64 = CNUM64_UNBOUNDED; 1951 } 1952 1953 /* Reset the min/max bounds of a register */ 1954 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1955 { 1956 __mark_reg64_unbounded(reg); 1957 __mark_reg32_unbounded(reg); 1958 } 1959 1960 static void reset_reg64_and_tnum(struct bpf_reg_state *reg) 1961 { 1962 __mark_reg64_unbounded(reg); 1963 reg->var_off = tnum_unknown; 1964 } 1965 1966 static void reset_reg32_and_tnum(struct bpf_reg_state *reg) 1967 { 1968 __mark_reg32_unbounded(reg); 1969 reg->var_off = tnum_unknown; 1970 } 1971 1972 static struct cnum32 cnum32_from_tnum(struct tnum tnum) 1973 { 1974 tnum = tnum_subreg(tnum); 1975 if ((tnum.mask & S32_MIN) || (tnum.value & S32_MIN)) 1976 /* min signed is max(sign bit) | min(other bits) */ 1977 /* max signed is min(sign bit) | max(other bits) */ 1978 return cnum32_from_srange(tnum.value | (tnum.mask & S32_MIN), 1979 tnum.value | (tnum.mask & S32_MAX)); 1980 else 1981 return cnum32_from_urange(tnum.value, (tnum.value | tnum.mask)); 1982 } 1983 1984 static struct cnum64 cnum64_from_tnum(struct tnum tnum) 1985 { 1986 if ((tnum.mask & S64_MIN) || (tnum.value & S64_MIN)) 1987 /* min signed is max(sign bit) | min(other bits) */ 1988 /* max signed is min(sign bit) | max(other bits) */ 1989 return cnum64_from_srange(tnum.value | (tnum.mask & S64_MIN), 1990 tnum.value | (tnum.mask & S64_MAX)); 1991 else 1992 return cnum64_from_urange(tnum.value, (tnum.value | tnum.mask)); 1993 } 1994 1995 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1996 { 1997 cnum32_intersect_with(®->r32, cnum32_from_tnum(reg->var_off)); 1998 } 1999 2000 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2001 { 2002 u64 tnum_next, tmax; 2003 bool umin_in_tnum; 2004 2005 cnum64_intersect_with(®->r64, cnum64_from_tnum(reg->var_off)); 2006 2007 /* Check if u64 and tnum overlap in a single value */ 2008 tnum_next = tnum_step(reg->var_off, reg_umin(reg)); 2009 umin_in_tnum = (reg_umin(reg) & ~reg->var_off.mask) == reg->var_off.value; 2010 tmax = reg->var_off.value | reg->var_off.mask; 2011 if (umin_in_tnum && tnum_next > reg_umax(reg)) { 2012 /* The u64 range and the tnum only overlap in umin. 2013 * u64: ---[xxxxxx]----- 2014 * tnum: --xx----------x- 2015 */ 2016 ___mark_reg_known(reg, reg_umin(reg)); 2017 } else if (!umin_in_tnum && tnum_next == tmax) { 2018 /* The u64 range and the tnum only overlap in the maximum value 2019 * represented by the tnum, called tmax. 2020 * u64: ---[xxxxxx]----- 2021 * tnum: xx-----x-------- 2022 */ 2023 ___mark_reg_known(reg, tmax); 2024 } else if (!umin_in_tnum && tnum_next <= reg_umax(reg) && 2025 tnum_step(reg->var_off, tnum_next) > reg_umax(reg)) { 2026 /* The u64 range and the tnum only overlap in between umin 2027 * (excluded) and umax. 2028 * u64: ---[xxxxxx]----- 2029 * tnum: xx----x-------x- 2030 */ 2031 ___mark_reg_known(reg, tnum_next); 2032 } 2033 } 2034 2035 static void __update_reg_bounds(struct bpf_reg_state *reg) 2036 { 2037 __update_reg32_bounds(reg); 2038 __update_reg64_bounds(reg); 2039 } 2040 2041 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg) 2042 { 2043 cnum32_intersect_with(®->r32, cnum32_from_cnum64(reg->r64)); 2044 } 2045 2046 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg) 2047 { 2048 reg->r64 = cnum64_cnum32_intersect(reg->r64, reg->r32); 2049 } 2050 2051 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2052 { 2053 deduce_bounds_32_from_64(reg); 2054 deduce_bounds_64_from_32(reg); 2055 } 2056 2057 /* Attempts to improve var_off based on unsigned min/max information */ 2058 static void __reg_bound_offset(struct bpf_reg_state *reg) 2059 { 2060 struct tnum var64_off = tnum_intersect(reg->var_off, 2061 tnum_range(reg_umin(reg), 2062 reg_umax(reg))); 2063 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2064 tnum_range(reg_u32_min(reg), 2065 reg_u32_max(reg))); 2066 2067 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2068 } 2069 2070 static bool range_bounds_violation(struct bpf_reg_state *reg); 2071 2072 static void reg_bounds_sync(struct bpf_reg_state *reg) 2073 { 2074 /* If the input reg_state is invalid, we can exit early */ 2075 if (range_bounds_violation(reg)) 2076 return; 2077 /* We might have learned new bounds from the var_off. */ 2078 __update_reg_bounds(reg); 2079 /* We might have learned something about the sign bit. */ 2080 __reg_deduce_bounds(reg); 2081 __reg_deduce_bounds(reg); 2082 /* We might have learned some bits from the bounds. */ 2083 __reg_bound_offset(reg); 2084 /* Intersecting with the old var_off might have improved our bounds 2085 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2086 * then new var_off is (0; 0x7f...fc) which improves our umax. 2087 */ 2088 __update_reg_bounds(reg); 2089 } 2090 2091 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg) 2092 { 2093 if (!tnum_is_const(reg->var_off)) 2094 return false; 2095 2096 return !cnum64_is_const(reg->r64) || reg->r64.base != reg->var_off.value; 2097 } 2098 2099 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg) 2100 { 2101 if (!tnum_subreg_is_const(reg->var_off)) 2102 return false; 2103 2104 return !cnum32_is_const(reg->r32) || reg->r32.base != tnum_subreg(reg->var_off).value; 2105 } 2106 2107 static bool range_bounds_violation(struct bpf_reg_state *reg) 2108 { 2109 return cnum32_is_empty(reg->r32) || cnum64_is_empty(reg->r64); 2110 } 2111 2112 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2113 struct bpf_reg_state *reg, const char *ctx) 2114 { 2115 const char *msg; 2116 2117 if (range_bounds_violation(reg)) { 2118 msg = "range bounds violation"; 2119 goto out; 2120 } 2121 2122 if (const_tnum_range_mismatch(reg)) { 2123 msg = "const tnum out of sync with range bounds"; 2124 goto out; 2125 } 2126 2127 if (const_tnum_range_mismatch_32(reg)) { 2128 msg = "const subreg tnum out of sync with range bounds"; 2129 goto out; 2130 } 2131 2132 return 0; 2133 out: 2134 verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s r64={.base=%#llx, .size=%#llx} " 2135 "r32={.base=%#x, .size=%#x} var_off=(%#llx, %#llx)", 2136 ctx, msg, 2137 reg->r64.base, reg->r64.size, 2138 reg->r32.base, reg->r32.size, 2139 reg->var_off.value, reg->var_off.mask); 2140 if (env->test_reg_invariants) 2141 return -EFAULT; 2142 __mark_reg_unbounded(reg); 2143 return 0; 2144 } 2145 2146 /* Mark a register as having a completely unknown (scalar) value. */ 2147 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2148 { 2149 s32 subreg_def = reg->subreg_def; 2150 2151 memset(reg, 0, sizeof(*reg)); 2152 reg->type = SCALAR_VALUE; 2153 reg->var_off = tnum_unknown; 2154 reg->subreg_def = subreg_def; 2155 __mark_reg_unbounded(reg); 2156 } 2157 2158 /* Mark a register as having a completely unknown (scalar) value, 2159 * initialize .precise as true when not bpf capable. 2160 */ 2161 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2162 struct bpf_reg_state *reg) 2163 { 2164 bpf_mark_reg_unknown_imprecise(reg); 2165 reg->precise = !env->bpf_capable; 2166 } 2167 2168 static void mark_reg_unknown(struct bpf_verifier_env *env, 2169 struct bpf_reg_state *regs, u32 regno) 2170 { 2171 __mark_reg_unknown(env, regs + regno); 2172 } 2173 2174 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2175 struct bpf_reg_state *regs, 2176 u32 regno, 2177 s32 s32_min, 2178 s32 s32_max) 2179 { 2180 struct bpf_reg_state *reg = regs + regno; 2181 2182 reg_set_srange32(reg, 2183 max_t(s32, reg_s32_min(reg), s32_min), 2184 min_t(s32, reg_s32_max(reg), s32_max)); 2185 reg_set_srange64(reg, 2186 max_t(s64, reg_smin(reg), s32_min), 2187 min_t(s64, reg_smax(reg), s32_max)); 2188 2189 reg_bounds_sync(reg); 2190 2191 return reg_bounds_sanity_check(env, reg, "s32_range"); 2192 } 2193 2194 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env, 2195 struct bpf_reg_state *reg) 2196 { 2197 __mark_reg_unknown(env, reg); 2198 reg->type = NOT_INIT; 2199 } 2200 2201 static int mark_btf_ld_reg(struct bpf_verifier_env *env, 2202 struct bpf_reg_state *regs, u32 regno, 2203 enum bpf_reg_type reg_type, 2204 struct btf *btf, u32 btf_id, 2205 enum bpf_type_flag flag) 2206 { 2207 switch (reg_type) { 2208 case SCALAR_VALUE: 2209 mark_reg_unknown(env, regs, regno); 2210 return 0; 2211 case PTR_TO_BTF_ID: 2212 mark_reg_known_zero(env, regs, regno); 2213 regs[regno].type = PTR_TO_BTF_ID | flag; 2214 regs[regno].btf = btf; 2215 regs[regno].btf_id = btf_id; 2216 if (type_may_be_null(flag)) 2217 regs[regno].id = ++env->id_gen; 2218 return 0; 2219 case PTR_TO_MEM: 2220 mark_reg_known_zero(env, regs, regno); 2221 regs[regno].type = PTR_TO_MEM | flag; 2222 regs[regno].mem_size = 0; 2223 return 0; 2224 default: 2225 verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__); 2226 return -EFAULT; 2227 } 2228 } 2229 2230 #define DEF_NOT_SUBREG (0) 2231 static void init_reg_state(struct bpf_verifier_env *env, 2232 struct bpf_func_state *state) 2233 { 2234 struct bpf_reg_state *regs = state->regs; 2235 int i; 2236 2237 for (i = 0; i < MAX_BPF_REG; i++) { 2238 bpf_mark_reg_not_init(env, ®s[i]); 2239 regs[i].subreg_def = DEF_NOT_SUBREG; 2240 } 2241 2242 /* frame pointer */ 2243 regs[BPF_REG_FP].type = PTR_TO_STACK; 2244 mark_reg_known_zero(env, regs, BPF_REG_FP); 2245 regs[BPF_REG_FP].frameno = state->frameno; 2246 } 2247 2248 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2249 { 2250 /* 2251 * return_32bit is set to false by default and set explicitly 2252 * by the caller when necessary. 2253 */ 2254 return (struct bpf_retval_range){ minval, maxval, false }; 2255 } 2256 2257 static void init_func_state(struct bpf_verifier_env *env, 2258 struct bpf_func_state *state, 2259 int callsite, int frameno, int subprogno) 2260 { 2261 state->callsite = callsite; 2262 state->frameno = frameno; 2263 state->subprogno = subprogno; 2264 state->callback_ret_range = retval_range(0, 0); 2265 init_reg_state(env, state); 2266 mark_verifier_state_scratched(env); 2267 } 2268 2269 /* Similar to push_stack(), but for async callbacks */ 2270 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2271 int insn_idx, int prev_insn_idx, 2272 int subprog, bool is_sleepable) 2273 { 2274 struct bpf_verifier_stack_elem *elem; 2275 struct bpf_func_state *frame; 2276 2277 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 2278 if (!elem) 2279 return ERR_PTR(-ENOMEM); 2280 2281 elem->insn_idx = insn_idx; 2282 elem->prev_insn_idx = prev_insn_idx; 2283 elem->next = env->head; 2284 elem->log_pos = env->log.end_pos; 2285 env->head = elem; 2286 env->stack_size++; 2287 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2288 verbose(env, 2289 "The sequence of %d jumps is too complex for async cb.\n", 2290 env->stack_size); 2291 return ERR_PTR(-E2BIG); 2292 } 2293 /* Unlike push_stack() do not bpf_copy_verifier_state(). 2294 * The caller state doesn't matter. 2295 * This is async callback. It starts in a fresh stack. 2296 * Initialize it similar to do_check_common(). 2297 */ 2298 elem->st.branches = 1; 2299 elem->st.in_sleepable = is_sleepable; 2300 frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT); 2301 if (!frame) 2302 return ERR_PTR(-ENOMEM); 2303 init_func_state(env, frame, 2304 BPF_MAIN_FUNC /* callsite */, 2305 0 /* frameno within this callchain */, 2306 subprog /* subprog number within this prog */); 2307 elem->st.frame[0] = frame; 2308 return &elem->st; 2309 } 2310 2311 2312 static int cmp_subprogs(const void *a, const void *b) 2313 { 2314 return ((struct bpf_subprog_info *)a)->start - 2315 ((struct bpf_subprog_info *)b)->start; 2316 } 2317 2318 /* Find subprogram that contains instruction at 'off' */ 2319 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off) 2320 { 2321 struct bpf_subprog_info *vals = env->subprog_info; 2322 int l, r, m; 2323 2324 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0) 2325 return NULL; 2326 2327 l = 0; 2328 r = env->subprog_cnt - 1; 2329 while (l < r) { 2330 m = l + (r - l + 1) / 2; 2331 if (vals[m].start <= off) 2332 l = m; 2333 else 2334 r = m - 1; 2335 } 2336 return &vals[l]; 2337 } 2338 2339 /* Find subprogram that starts exactly at 'off' */ 2340 int bpf_find_subprog(struct bpf_verifier_env *env, int off) 2341 { 2342 struct bpf_subprog_info *p; 2343 2344 p = bpf_find_containing_subprog(env, off); 2345 if (!p || p->start != off) 2346 return -ENOENT; 2347 return p - env->subprog_info; 2348 } 2349 2350 static int add_subprog(struct bpf_verifier_env *env, int off) 2351 { 2352 int insn_cnt = env->prog->len; 2353 int ret; 2354 2355 if (off >= insn_cnt || off < 0) { 2356 verbose(env, "call to invalid destination\n"); 2357 return -EINVAL; 2358 } 2359 ret = bpf_find_subprog(env, off); 2360 if (ret >= 0) 2361 return ret; 2362 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2363 verbose(env, "too many subprograms\n"); 2364 return -E2BIG; 2365 } 2366 /* determine subprog starts. The end is one before the next starts */ 2367 env->subprog_info[env->subprog_cnt++].start = off; 2368 sort(env->subprog_info, env->subprog_cnt, 2369 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2370 return env->subprog_cnt - 1; 2371 } 2372 2373 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2374 { 2375 struct bpf_prog_aux *aux = env->prog->aux; 2376 struct btf *btf = aux->btf; 2377 const struct btf_type *t; 2378 u32 main_btf_id, id; 2379 const char *name; 2380 int ret, i; 2381 2382 /* Non-zero func_info_cnt implies valid btf */ 2383 if (!aux->func_info_cnt) 2384 return 0; 2385 main_btf_id = aux->func_info[0].type_id; 2386 2387 t = btf_type_by_id(btf, main_btf_id); 2388 if (!t) { 2389 verbose(env, "invalid btf id for main subprog in func_info\n"); 2390 return -EINVAL; 2391 } 2392 2393 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2394 if (IS_ERR(name)) { 2395 ret = PTR_ERR(name); 2396 /* If there is no tag present, there is no exception callback */ 2397 if (ret == -ENOENT) 2398 ret = 0; 2399 else if (ret == -EEXIST) 2400 verbose(env, "multiple exception callback tags for main subprog\n"); 2401 return ret; 2402 } 2403 2404 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2405 if (ret < 0) { 2406 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2407 return ret; 2408 } 2409 id = ret; 2410 t = btf_type_by_id(btf, id); 2411 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2412 verbose(env, "exception callback '%s' must have global linkage\n", name); 2413 return -EINVAL; 2414 } 2415 ret = 0; 2416 for (i = 0; i < aux->func_info_cnt; i++) { 2417 if (aux->func_info[i].type_id != id) 2418 continue; 2419 ret = aux->func_info[i].insn_off; 2420 /* Further func_info and subprog checks will also happen 2421 * later, so assume this is the right insn_off for now. 2422 */ 2423 if (!ret) { 2424 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2425 ret = -EINVAL; 2426 } 2427 } 2428 if (!ret) { 2429 verbose(env, "exception callback type id not found in func_info\n"); 2430 ret = -EINVAL; 2431 } 2432 return ret; 2433 } 2434 2435 #define MAX_KFUNC_BTFS 256 2436 2437 struct bpf_kfunc_btf { 2438 struct btf *btf; 2439 struct module *module; 2440 u16 offset; 2441 }; 2442 2443 struct bpf_kfunc_btf_tab { 2444 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2445 u32 nr_descs; 2446 }; 2447 2448 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2449 { 2450 const struct bpf_kfunc_desc *d0 = a; 2451 const struct bpf_kfunc_desc *d1 = b; 2452 2453 /* func_id is not greater than BTF_MAX_TYPE */ 2454 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2455 } 2456 2457 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2458 { 2459 const struct bpf_kfunc_btf *d0 = a; 2460 const struct bpf_kfunc_btf *d1 = b; 2461 2462 return d0->offset - d1->offset; 2463 } 2464 2465 static struct bpf_kfunc_desc * 2466 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2467 { 2468 struct bpf_kfunc_desc desc = { 2469 .func_id = func_id, 2470 .offset = offset, 2471 }; 2472 struct bpf_kfunc_desc_tab *tab; 2473 2474 tab = prog->aux->kfunc_tab; 2475 return bsearch(&desc, tab->descs, tab->nr_descs, 2476 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2477 } 2478 2479 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2480 u16 btf_fd_idx, u8 **func_addr) 2481 { 2482 const struct bpf_kfunc_desc *desc; 2483 2484 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2485 if (!desc) 2486 return -EFAULT; 2487 2488 *func_addr = (u8 *)desc->addr; 2489 return 0; 2490 } 2491 2492 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2493 s16 offset) 2494 { 2495 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2496 struct bpf_kfunc_btf_tab *tab; 2497 struct bpf_kfunc_btf *b; 2498 struct module *mod; 2499 struct btf *btf; 2500 int btf_fd; 2501 2502 tab = env->prog->aux->kfunc_btf_tab; 2503 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2504 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2505 if (!b) { 2506 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2507 verbose(env, "too many different module BTFs\n"); 2508 return ERR_PTR(-E2BIG); 2509 } 2510 2511 if (bpfptr_is_null(env->fd_array)) { 2512 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2513 return ERR_PTR(-EPROTO); 2514 } 2515 2516 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2517 offset * sizeof(btf_fd), 2518 sizeof(btf_fd))) 2519 return ERR_PTR(-EFAULT); 2520 2521 btf = btf_get_by_fd(btf_fd); 2522 if (IS_ERR(btf)) { 2523 verbose(env, "invalid module BTF fd specified\n"); 2524 return btf; 2525 } 2526 2527 if (!btf_is_module(btf)) { 2528 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2529 btf_put(btf); 2530 return ERR_PTR(-EINVAL); 2531 } 2532 2533 mod = btf_try_get_module(btf); 2534 if (!mod) { 2535 btf_put(btf); 2536 return ERR_PTR(-ENXIO); 2537 } 2538 2539 b = &tab->descs[tab->nr_descs++]; 2540 b->btf = btf; 2541 b->module = mod; 2542 b->offset = offset; 2543 2544 /* sort() reorders entries by value, so b may no longer point 2545 * to the right entry after this 2546 */ 2547 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2548 kfunc_btf_cmp_by_off, NULL); 2549 } else { 2550 btf = b->btf; 2551 } 2552 2553 return btf; 2554 } 2555 2556 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2557 { 2558 if (!tab) 2559 return; 2560 2561 while (tab->nr_descs--) { 2562 module_put(tab->descs[tab->nr_descs].module); 2563 btf_put(tab->descs[tab->nr_descs].btf); 2564 } 2565 kfree(tab); 2566 } 2567 2568 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2569 { 2570 if (offset) { 2571 if (offset < 0) { 2572 /* In the future, this can be allowed to increase limit 2573 * of fd index into fd_array, interpreted as u16. 2574 */ 2575 verbose(env, "negative offset disallowed for kernel module function call\n"); 2576 return ERR_PTR(-EINVAL); 2577 } 2578 2579 return __find_kfunc_desc_btf(env, offset); 2580 } 2581 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2582 } 2583 2584 #define KF_IMPL_SUFFIX "_impl" 2585 2586 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_env *env, 2587 struct btf *btf, 2588 const char *func_name) 2589 { 2590 char *buf = env->tmp_str_buf; 2591 const struct btf_type *func; 2592 s32 impl_id; 2593 int len; 2594 2595 len = snprintf(buf, TMP_STR_BUF_LEN, "%s%s", func_name, KF_IMPL_SUFFIX); 2596 if (len < 0 || len >= TMP_STR_BUF_LEN) { 2597 verbose(env, "function name %s%s is too long\n", func_name, KF_IMPL_SUFFIX); 2598 return NULL; 2599 } 2600 2601 impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC); 2602 if (impl_id <= 0) { 2603 verbose(env, "cannot find function %s in BTF\n", buf); 2604 return NULL; 2605 } 2606 2607 func = btf_type_by_id(btf, impl_id); 2608 2609 return btf_type_by_id(btf, func->type); 2610 } 2611 2612 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 2613 s32 func_id, 2614 s16 offset, 2615 struct bpf_kfunc_meta *kfunc) 2616 { 2617 const struct btf_type *func, *func_proto; 2618 const char *func_name; 2619 u32 *kfunc_flags; 2620 struct btf *btf; 2621 2622 if (func_id <= 0) { 2623 verbose(env, "invalid kernel function btf_id %d\n", func_id); 2624 return -EINVAL; 2625 } 2626 2627 btf = find_kfunc_desc_btf(env, offset); 2628 if (IS_ERR(btf)) { 2629 verbose(env, "failed to find BTF for kernel function\n"); 2630 return PTR_ERR(btf); 2631 } 2632 2633 /* 2634 * Note that kfunc_flags may be NULL at this point, which 2635 * means that we couldn't find func_id in any relevant 2636 * kfunc_id_set. This most likely indicates an invalid kfunc 2637 * call. However we don't fail with an error here, 2638 * and let the caller decide what to do with NULL kfunc->flags. 2639 */ 2640 kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog); 2641 2642 func = btf_type_by_id(btf, func_id); 2643 if (!func || !btf_type_is_func(func)) { 2644 verbose(env, "kernel btf_id %d is not a function\n", func_id); 2645 return -EINVAL; 2646 } 2647 2648 func_name = btf_name_by_offset(btf, func->name_off); 2649 2650 /* 2651 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag 2652 * can be found through the counterpart _impl kfunc. 2653 */ 2654 if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS)) 2655 func_proto = find_kfunc_impl_proto(env, btf, func_name); 2656 else 2657 func_proto = btf_type_by_id(btf, func->type); 2658 2659 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2660 verbose(env, "kernel function btf_id %d does not have a valid func_proto\n", 2661 func_id); 2662 return -EINVAL; 2663 } 2664 2665 memset(kfunc, 0, sizeof(*kfunc)); 2666 kfunc->btf = btf; 2667 kfunc->id = func_id; 2668 kfunc->name = func_name; 2669 kfunc->proto = func_proto; 2670 kfunc->flags = kfunc_flags; 2671 2672 return 0; 2673 } 2674 2675 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset) 2676 { 2677 struct bpf_kfunc_btf_tab *btf_tab; 2678 struct btf_func_model func_model; 2679 struct bpf_kfunc_desc_tab *tab; 2680 struct bpf_prog_aux *prog_aux; 2681 struct bpf_kfunc_meta kfunc; 2682 struct bpf_kfunc_desc *desc; 2683 unsigned long addr; 2684 int err; 2685 2686 prog_aux = env->prog->aux; 2687 tab = prog_aux->kfunc_tab; 2688 btf_tab = prog_aux->kfunc_btf_tab; 2689 if (!tab) { 2690 if (!btf_vmlinux) { 2691 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2692 return -ENOTSUPP; 2693 } 2694 2695 if (!env->prog->jit_requested) { 2696 verbose(env, "JIT is required for calling kernel function\n"); 2697 return -ENOTSUPP; 2698 } 2699 2700 if (!bpf_jit_supports_kfunc_call()) { 2701 verbose(env, "JIT does not support calling kernel function\n"); 2702 return -ENOTSUPP; 2703 } 2704 2705 if (!env->prog->gpl_compatible) { 2706 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2707 return -EINVAL; 2708 } 2709 2710 tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT); 2711 if (!tab) 2712 return -ENOMEM; 2713 prog_aux->kfunc_tab = tab; 2714 } 2715 2716 /* func_id == 0 is always invalid, but instead of returning an error, be 2717 * conservative and wait until the code elimination pass before returning 2718 * error, so that invalid calls that get pruned out can be in BPF programs 2719 * loaded from userspace. It is also required that offset be untouched 2720 * for such calls. 2721 */ 2722 if (!func_id && !offset) 2723 return 0; 2724 2725 if (!btf_tab && offset) { 2726 btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT); 2727 if (!btf_tab) 2728 return -ENOMEM; 2729 prog_aux->kfunc_btf_tab = btf_tab; 2730 } 2731 2732 if (find_kfunc_desc(env->prog, func_id, offset)) 2733 return 0; 2734 2735 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2736 verbose(env, "too many different kernel function calls\n"); 2737 return -E2BIG; 2738 } 2739 2740 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 2741 if (err) 2742 return err; 2743 2744 addr = kallsyms_lookup_name(kfunc.name); 2745 if (!addr) { 2746 verbose(env, "cannot find address for kernel function %s\n", kfunc.name); 2747 return -EINVAL; 2748 } 2749 2750 if (bpf_dev_bound_kfunc_id(func_id)) { 2751 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2752 if (err) 2753 return err; 2754 } 2755 2756 err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model); 2757 if (err) 2758 return err; 2759 2760 desc = &tab->descs[tab->nr_descs++]; 2761 desc->func_id = func_id; 2762 desc->offset = offset; 2763 desc->addr = addr; 2764 desc->func_model = func_model; 2765 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2766 kfunc_desc_cmp_by_id_off, NULL); 2767 return 0; 2768 } 2769 2770 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2771 { 2772 return !!prog->aux->kfunc_tab; 2773 } 2774 2775 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2776 { 2777 struct bpf_subprog_info *subprog = env->subprog_info; 2778 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2779 struct bpf_insn *insn = env->prog->insnsi; 2780 2781 /* Add entry function. */ 2782 ret = add_subprog(env, 0); 2783 if (ret) 2784 return ret; 2785 2786 for (i = 0; i < insn_cnt; i++, insn++) { 2787 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2788 !bpf_pseudo_kfunc_call(insn)) 2789 continue; 2790 2791 if (!env->bpf_capable) { 2792 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2793 return -EPERM; 2794 } 2795 2796 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2797 ret = add_subprog(env, i + insn->imm + 1); 2798 else 2799 ret = bpf_add_kfunc_call(env, insn->imm, insn->off); 2800 2801 if (ret < 0) 2802 return ret; 2803 } 2804 2805 ret = bpf_find_exception_callback_insn_off(env); 2806 if (ret < 0) 2807 return ret; 2808 ex_cb_insn = ret; 2809 2810 /* If ex_cb_insn > 0, this means that the main program has a subprog 2811 * marked using BTF decl tag to serve as the exception callback. 2812 */ 2813 if (ex_cb_insn) { 2814 ret = add_subprog(env, ex_cb_insn); 2815 if (ret < 0) 2816 return ret; 2817 for (i = 1; i < env->subprog_cnt; i++) { 2818 if (env->subprog_info[i].start != ex_cb_insn) 2819 continue; 2820 env->exception_callback_subprog = i; 2821 bpf_mark_subprog_exc_cb(env, i); 2822 break; 2823 } 2824 } 2825 2826 /* Add a fake 'exit' subprog which could simplify subprog iteration 2827 * logic. 'subprog_cnt' should not be increased. 2828 */ 2829 subprog[env->subprog_cnt].start = insn_cnt; 2830 2831 if (env->log.level & BPF_LOG_LEVEL2) 2832 for (i = 0; i < env->subprog_cnt; i++) 2833 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2834 2835 return 0; 2836 } 2837 2838 static int check_subprogs(struct bpf_verifier_env *env) 2839 { 2840 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2841 struct bpf_subprog_info *subprog = env->subprog_info; 2842 struct bpf_insn *insn = env->prog->insnsi; 2843 int insn_cnt = env->prog->len; 2844 2845 /* now check that all jumps are within the same subprog */ 2846 subprog_start = subprog[cur_subprog].start; 2847 subprog_end = subprog[cur_subprog + 1].start; 2848 for (i = 0; i < insn_cnt; i++) { 2849 u8 code = insn[i].code; 2850 2851 if (code == (BPF_JMP | BPF_CALL) && 2852 insn[i].src_reg == 0 && 2853 insn[i].imm == BPF_FUNC_tail_call) { 2854 subprog[cur_subprog].has_tail_call = true; 2855 subprog[cur_subprog].tail_call_reachable = true; 2856 } 2857 if (BPF_CLASS(code) == BPF_LD && 2858 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2859 subprog[cur_subprog].has_ld_abs = true; 2860 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2861 goto next; 2862 if (BPF_OP(code) == BPF_CALL) 2863 goto next; 2864 if (BPF_OP(code) == BPF_EXIT) { 2865 subprog[cur_subprog].exit_idx = i; 2866 goto next; 2867 } 2868 off = i + bpf_jmp_offset(&insn[i]) + 1; 2869 if (off < subprog_start || off >= subprog_end) { 2870 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2871 return -EINVAL; 2872 } 2873 next: 2874 if (i == subprog_end - 1) { 2875 /* to avoid fall-through from one subprog into another 2876 * the last insn of the subprog should be either exit 2877 * or unconditional jump back or bpf_throw call 2878 */ 2879 if (code != (BPF_JMP | BPF_EXIT) && 2880 code != (BPF_JMP32 | BPF_JA) && 2881 code != (BPF_JMP | BPF_JA)) { 2882 verbose(env, "last insn is not an exit or jmp\n"); 2883 return -EINVAL; 2884 } 2885 subprog_start = subprog_end; 2886 cur_subprog++; 2887 if (cur_subprog < env->subprog_cnt) 2888 subprog_end = subprog[cur_subprog + 1].start; 2889 } 2890 } 2891 return 0; 2892 } 2893 2894 /* 2895 * Sort subprogs in topological order so that leaf subprogs come first and 2896 * their callers come later. This is a DFS post-order traversal of the call 2897 * graph. Scan only reachable instructions (those in the computed postorder) of 2898 * the current subprog to discover callees (direct subprogs and sync 2899 * callbacks). 2900 */ 2901 static int sort_subprogs_topo(struct bpf_verifier_env *env) 2902 { 2903 struct bpf_subprog_info *si = env->subprog_info; 2904 int *insn_postorder = env->cfg.insn_postorder; 2905 struct bpf_insn *insn = env->prog->insnsi; 2906 int cnt = env->subprog_cnt; 2907 int *dfs_stack = NULL; 2908 int top = 0, order = 0; 2909 int i, ret = 0; 2910 u8 *color = NULL; 2911 2912 color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT); 2913 dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT); 2914 if (!color || !dfs_stack) { 2915 ret = -ENOMEM; 2916 goto out; 2917 } 2918 2919 /* 2920 * DFS post-order traversal. 2921 * Color values: 0 = unvisited, 1 = on stack, 2 = done. 2922 */ 2923 for (i = 0; i < cnt; i++) { 2924 if (color[i]) 2925 continue; 2926 color[i] = 1; 2927 dfs_stack[top++] = i; 2928 2929 while (top > 0) { 2930 int cur = dfs_stack[top - 1]; 2931 int po_start = si[cur].postorder_start; 2932 int po_end = si[cur + 1].postorder_start; 2933 bool pushed = false; 2934 int j; 2935 2936 for (j = po_start; j < po_end; j++) { 2937 int idx = insn_postorder[j]; 2938 int callee; 2939 2940 if (!bpf_pseudo_call(&insn[idx]) && !bpf_pseudo_func(&insn[idx])) 2941 continue; 2942 callee = bpf_find_subprog(env, idx + insn[idx].imm + 1); 2943 if (callee < 0) { 2944 ret = -EFAULT; 2945 goto out; 2946 } 2947 if (color[callee] == 2) 2948 continue; 2949 if (color[callee] == 1) { 2950 if (bpf_pseudo_func(&insn[idx])) 2951 continue; 2952 verbose(env, "recursive call from %s() to %s()\n", 2953 subprog_name(env, cur), 2954 subprog_name(env, callee)); 2955 ret = -EINVAL; 2956 goto out; 2957 } 2958 color[callee] = 1; 2959 dfs_stack[top++] = callee; 2960 pushed = true; 2961 break; 2962 } 2963 2964 if (!pushed) { 2965 color[cur] = 2; 2966 env->subprog_topo_order[order++] = cur; 2967 top--; 2968 } 2969 } 2970 } 2971 2972 if (env->log.level & BPF_LOG_LEVEL2) 2973 for (i = 0; i < cnt; i++) 2974 verbose(env, "topo_order[%d] = %s\n", 2975 i, subprog_name(env, env->subprog_topo_order[i])); 2976 out: 2977 kvfree(dfs_stack); 2978 kvfree(color); 2979 return ret; 2980 } 2981 2982 static void mark_stack_slots_scratched(struct bpf_verifier_env *env, 2983 int spi, int nr_slots) 2984 { 2985 int i; 2986 2987 for (i = 0; i < nr_slots; i++) 2988 mark_stack_slot_scratched(env, spi - i); 2989 } 2990 2991 /* This function is supposed to be used by the following 32-bit optimization 2992 * code only. It returns TRUE if the source or destination register operates 2993 * on 64-bit, otherwise return FALSE. 2994 */ 2995 bool bpf_is_reg64(struct bpf_insn *insn, 2996 u32 regno, struct bpf_reg_state *reg, enum bpf_reg_arg_type t) 2997 { 2998 u8 code, class, op; 2999 3000 code = insn->code; 3001 class = BPF_CLASS(code); 3002 op = BPF_OP(code); 3003 if (class == BPF_JMP) { 3004 /* BPF_EXIT for "main" will reach here. Return TRUE 3005 * conservatively. 3006 */ 3007 if (op == BPF_EXIT) 3008 return true; 3009 if (op == BPF_CALL) { 3010 /* BPF to BPF call will reach here because of marking 3011 * caller saved clobber with DST_OP_NO_MARK for which we 3012 * don't care the register def because they are anyway 3013 * marked as NOT_INIT already. 3014 */ 3015 if (insn->src_reg == BPF_PSEUDO_CALL) 3016 return false; 3017 /* Helper call will reach here because of arg type 3018 * check, conservatively return TRUE. 3019 */ 3020 if (t == SRC_OP) 3021 return true; 3022 3023 return false; 3024 } 3025 } 3026 3027 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3028 return false; 3029 3030 if (class == BPF_ALU64 || class == BPF_JMP || 3031 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3032 return true; 3033 3034 if (class == BPF_ALU || class == BPF_JMP32) 3035 return false; 3036 3037 if (class == BPF_LDX) { 3038 if (t != SRC_OP) 3039 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3040 /* LDX source must be ptr. */ 3041 return true; 3042 } 3043 3044 if (class == BPF_STX) { 3045 /* BPF_STX (including atomic variants) has one or more source 3046 * operands, one of which is a ptr. Check whether the caller is 3047 * asking about it. 3048 */ 3049 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3050 return true; 3051 return BPF_SIZE(code) == BPF_DW; 3052 } 3053 3054 if (class == BPF_LD) { 3055 u8 mode = BPF_MODE(code); 3056 3057 /* LD_IMM64 */ 3058 if (mode == BPF_IMM) 3059 return true; 3060 3061 /* Both LD_IND and LD_ABS return 32-bit data. */ 3062 if (t != SRC_OP) 3063 return false; 3064 3065 /* Implicit ctx ptr. */ 3066 if (regno == BPF_REG_6) 3067 return true; 3068 3069 /* Explicit source could be any width. */ 3070 return true; 3071 } 3072 3073 if (class == BPF_ST) 3074 /* The only source register for BPF_ST is a ptr. */ 3075 return true; 3076 3077 /* Conservatively return true at default. */ 3078 return true; 3079 } 3080 3081 static void mark_insn_zext(struct bpf_verifier_env *env, 3082 struct bpf_reg_state *reg) 3083 { 3084 s32 def_idx = reg->subreg_def; 3085 3086 if (def_idx == DEF_NOT_SUBREG) 3087 return; 3088 3089 env->insn_aux_data[def_idx - 1].zext_dst = true; 3090 /* The dst will be zero extended, so won't be sub-register anymore. */ 3091 reg->subreg_def = DEF_NOT_SUBREG; 3092 } 3093 3094 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3095 enum bpf_reg_arg_type t) 3096 { 3097 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3098 struct bpf_reg_state *reg; 3099 bool rw64; 3100 3101 mark_reg_scratched(env, regno); 3102 3103 reg = ®s[regno]; 3104 rw64 = bpf_is_reg64(insn, regno, reg, t); 3105 if (t == SRC_OP) { 3106 /* check whether register used as source operand can be read */ 3107 if (reg->type == NOT_INIT) { 3108 verbose(env, "R%d !read_ok\n", regno); 3109 return -EACCES; 3110 } 3111 /* We don't need to worry about FP liveness because it's read-only */ 3112 if (regno == BPF_REG_FP) 3113 return 0; 3114 3115 if (rw64) 3116 mark_insn_zext(env, reg); 3117 3118 return 0; 3119 } else { 3120 /* check whether register used as dest operand can be written to */ 3121 if (regno == BPF_REG_FP) { 3122 verbose(env, "frame pointer is read only\n"); 3123 return -EACCES; 3124 } 3125 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3126 if (t == DST_OP) 3127 mark_reg_unknown(env, regs, regno); 3128 } 3129 return 0; 3130 } 3131 3132 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3133 enum bpf_reg_arg_type t) 3134 { 3135 struct bpf_verifier_state *vstate = env->cur_state; 3136 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3137 3138 return __check_reg_arg(env, state->regs, regno, t); 3139 } 3140 3141 static void mark_indirect_target(struct bpf_verifier_env *env, int idx) 3142 { 3143 env->insn_aux_data[idx].indirect_target = true; 3144 } 3145 3146 #define LR_FRAMENO_BITS 3 3147 #define LR_SPI_BITS 6 3148 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3149 #define LR_SIZE_BITS 4 3150 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3151 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3152 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3153 #define LR_SPI_OFF LR_FRAMENO_BITS 3154 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3155 #define LINKED_REGS_MAX 6 3156 3157 struct linked_reg { 3158 u8 frameno; 3159 union { 3160 u8 spi; 3161 u8 regno; 3162 }; 3163 bool is_reg; 3164 }; 3165 3166 struct linked_regs { 3167 int cnt; 3168 struct linked_reg entries[LINKED_REGS_MAX]; 3169 }; 3170 3171 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3172 { 3173 if (s->cnt < LINKED_REGS_MAX) 3174 return &s->entries[s->cnt++]; 3175 3176 return NULL; 3177 } 3178 3179 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track 3180 * number of elements currently in stack. 3181 * Pack one history entry for linked registers as 10 bits in the following format: 3182 * - 3-bits frameno 3183 * - 6-bits spi_or_reg 3184 * - 1-bit is_reg 3185 */ 3186 static u64 linked_regs_pack(struct linked_regs *s) 3187 { 3188 u64 val = 0; 3189 int i; 3190 3191 for (i = 0; i < s->cnt; ++i) { 3192 struct linked_reg *e = &s->entries[i]; 3193 u64 tmp = 0; 3194 3195 tmp |= e->frameno; 3196 tmp |= e->spi << LR_SPI_OFF; 3197 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3198 3199 val <<= LR_ENTRY_BITS; 3200 val |= tmp; 3201 } 3202 val <<= LR_SIZE_BITS; 3203 val |= s->cnt; 3204 return val; 3205 } 3206 3207 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3208 { 3209 int i; 3210 3211 s->cnt = val & LR_SIZE_MASK; 3212 val >>= LR_SIZE_BITS; 3213 3214 for (i = 0; i < s->cnt; ++i) { 3215 struct linked_reg *e = &s->entries[i]; 3216 3217 e->frameno = val & LR_FRAMENO_MASK; 3218 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3219 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3220 val >>= LR_ENTRY_BITS; 3221 } 3222 } 3223 3224 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3225 { 3226 const struct btf_type *func; 3227 struct btf *desc_btf; 3228 3229 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3230 return NULL; 3231 3232 desc_btf = find_kfunc_desc_btf(data, insn->off); 3233 if (IS_ERR(desc_btf)) 3234 return "<error>"; 3235 3236 func = btf_type_by_id(desc_btf, insn->imm); 3237 return btf_name_by_offset(desc_btf, func->name_off); 3238 } 3239 3240 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn) 3241 { 3242 const struct bpf_insn_cbs cbs = { 3243 .cb_call = disasm_kfunc_name, 3244 .cb_print = verbose, 3245 .private_data = env, 3246 }; 3247 3248 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3249 } 3250 3251 /* If any register R in hist->linked_regs is marked as precise in bt, 3252 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 3253 */ 3254 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 3255 { 3256 struct linked_regs linked_regs; 3257 bool some_precise = false; 3258 int i; 3259 3260 if (!hist || hist->linked_regs == 0) 3261 return; 3262 3263 linked_regs_unpack(hist->linked_regs, &linked_regs); 3264 for (i = 0; i < linked_regs.cnt; ++i) { 3265 struct linked_reg *e = &linked_regs.entries[i]; 3266 3267 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 3268 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 3269 some_precise = true; 3270 break; 3271 } 3272 } 3273 3274 if (!some_precise) 3275 return; 3276 3277 for (i = 0; i < linked_regs.cnt; ++i) { 3278 struct linked_reg *e = &linked_regs.entries[i]; 3279 3280 if (e->is_reg) 3281 bpf_bt_set_frame_reg(bt, e->frameno, e->regno); 3282 else 3283 bpf_bt_set_frame_slot(bt, e->frameno, e->spi); 3284 } 3285 } 3286 3287 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3288 { 3289 return bpf_mark_chain_precision(env, env->cur_state, regno, NULL); 3290 } 3291 3292 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 3293 * desired reg and stack masks across all relevant frames 3294 */ 3295 static int mark_chain_precision_batch(struct bpf_verifier_env *env, 3296 struct bpf_verifier_state *starting_state) 3297 { 3298 return bpf_mark_chain_precision(env, starting_state, -1, NULL); 3299 } 3300 3301 static bool is_spillable_regtype(enum bpf_reg_type type) 3302 { 3303 switch (base_type(type)) { 3304 case PTR_TO_MAP_VALUE: 3305 case PTR_TO_STACK: 3306 case PTR_TO_CTX: 3307 case PTR_TO_PACKET: 3308 case PTR_TO_PACKET_META: 3309 case PTR_TO_PACKET_END: 3310 case PTR_TO_FLOW_KEYS: 3311 case CONST_PTR_TO_MAP: 3312 case PTR_TO_SOCKET: 3313 case PTR_TO_SOCK_COMMON: 3314 case PTR_TO_TCP_SOCK: 3315 case PTR_TO_XDP_SOCK: 3316 case PTR_TO_BTF_ID: 3317 case PTR_TO_BUF: 3318 case PTR_TO_MEM: 3319 case PTR_TO_FUNC: 3320 case PTR_TO_MAP_KEY: 3321 case PTR_TO_ARENA: 3322 return true; 3323 default: 3324 return false; 3325 } 3326 } 3327 3328 3329 /* check if register is a constant scalar value */ 3330 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 3331 { 3332 return reg->type == SCALAR_VALUE && 3333 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 3334 } 3335 3336 /* assuming is_reg_const() is true, return constant value of a register */ 3337 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 3338 { 3339 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 3340 } 3341 3342 static bool __is_pointer_value(bool allow_ptr_leaks, 3343 const struct bpf_reg_state *reg) 3344 { 3345 if (allow_ptr_leaks) 3346 return false; 3347 3348 return reg->type != SCALAR_VALUE; 3349 } 3350 3351 static void clear_scalar_id(struct bpf_reg_state *reg) 3352 { 3353 reg->id = 0; 3354 reg->delta = 0; 3355 } 3356 3357 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 3358 struct bpf_reg_state *src_reg) 3359 { 3360 if (src_reg->type != SCALAR_VALUE) 3361 return; 3362 /* 3363 * The verifier is processing rX = rY insn and 3364 * rY->id has special linked register already. 3365 * Cleared it, since multiple rX += const are not supported. 3366 */ 3367 if (src_reg->id & BPF_ADD_CONST) 3368 clear_scalar_id(src_reg); 3369 /* 3370 * Ensure that src_reg has a valid ID that will be copied to 3371 * dst_reg and then will be used by sync_linked_regs() to 3372 * propagate min/max range. 3373 */ 3374 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 3375 src_reg->id = ++env->id_gen; 3376 } 3377 3378 static void save_register_state(struct bpf_verifier_env *env, 3379 struct bpf_func_state *state, 3380 int spi, struct bpf_reg_state *reg, 3381 int size) 3382 { 3383 int i; 3384 3385 state->stack[spi].spilled_ptr = *reg; 3386 3387 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3388 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 3389 3390 /* size < 8 bytes spill */ 3391 for (; i; i--) 3392 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 3393 } 3394 3395 static bool is_bpf_st_mem(struct bpf_insn *insn) 3396 { 3397 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 3398 } 3399 3400 static int get_reg_width(struct bpf_reg_state *reg) 3401 { 3402 return fls64(reg_umax(reg)); 3403 } 3404 3405 /* See comment for mark_fastcall_pattern_for_call() */ 3406 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 3407 struct bpf_func_state *state, int insn_idx, int off) 3408 { 3409 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 3410 struct bpf_insn_aux_data *aux = env->insn_aux_data; 3411 int i; 3412 3413 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 3414 return; 3415 /* access to the region [max_stack_depth .. fastcall_stack_off) 3416 * from something that is not a part of the fastcall pattern, 3417 * disable fastcall rewrites for current subprogram by setting 3418 * fastcall_stack_off to a value smaller than any possible offset. 3419 */ 3420 subprog->fastcall_stack_off = S16_MIN; 3421 /* reset fastcall aux flags within subprogram, 3422 * happens at most once per subprogram 3423 */ 3424 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 3425 aux[i].fastcall_spills_num = 0; 3426 aux[i].fastcall_pattern = 0; 3427 } 3428 } 3429 3430 static void scrub_special_slot(struct bpf_func_state *state, int spi) 3431 { 3432 int i; 3433 3434 /* regular write of data into stack destroys any spilled ptr */ 3435 state->stack[spi].spilled_ptr.type = NOT_INIT; 3436 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 3437 if (is_stack_slot_special(&state->stack[spi])) 3438 for (i = 0; i < BPF_REG_SIZE; i++) 3439 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 3440 } 3441 3442 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3443 * stack boundary and alignment are checked in check_mem_access() 3444 */ 3445 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3446 /* stack frame we're writing to */ 3447 struct bpf_func_state *state, 3448 int off, int size, int value_regno, 3449 int insn_idx) 3450 { 3451 struct bpf_func_state *cur; /* state of the current function */ 3452 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3453 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3454 struct bpf_reg_state *reg = NULL; 3455 int insn_flags = INSN_F_STACK_ACCESS; 3456 int hist_spi = spi, hist_frame = state->frameno; 3457 3458 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 3459 * so it's aligned access and [off, off + size) are within stack limits 3460 */ 3461 if (!env->allow_ptr_leaks && 3462 bpf_is_spilled_reg(&state->stack[spi]) && 3463 !bpf_is_spilled_scalar_reg(&state->stack[spi]) && 3464 size != BPF_REG_SIZE) { 3465 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3466 return -EACCES; 3467 } 3468 3469 cur = env->cur_state->frame[env->cur_state->curframe]; 3470 if (value_regno >= 0) 3471 reg = &cur->regs[value_regno]; 3472 if (!env->bypass_spec_v4) { 3473 bool sanitize = reg && is_spillable_regtype(reg->type); 3474 3475 for (i = 0; i < size; i++) { 3476 u8 type = state->stack[spi].slot_type[i]; 3477 3478 if (type != STACK_MISC && type != STACK_ZERO) { 3479 sanitize = true; 3480 break; 3481 } 3482 } 3483 3484 if (sanitize) 3485 env->insn_aux_data[insn_idx].nospec_result = true; 3486 } 3487 3488 err = destroy_if_dynptr_stack_slot(env, state, spi); 3489 if (err) 3490 return err; 3491 3492 check_fastcall_stack_contract(env, state, insn_idx, off); 3493 mark_stack_slot_scratched(env, spi); 3494 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 3495 bool reg_value_fits; 3496 3497 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 3498 /* Make sure that reg had an ID to build a relation on spill. */ 3499 if (reg_value_fits) 3500 assign_scalar_id_before_mov(env, reg); 3501 save_register_state(env, state, spi, reg, size); 3502 /* Break the relation on a narrowing spill. */ 3503 if (!reg_value_fits) 3504 state->stack[spi].spilled_ptr.id = 0; 3505 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 3506 env->bpf_capable) { 3507 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 3508 3509 memset(tmp_reg, 0, sizeof(*tmp_reg)); 3510 __mark_reg_known(tmp_reg, insn->imm); 3511 tmp_reg->type = SCALAR_VALUE; 3512 save_register_state(env, state, spi, tmp_reg, size); 3513 } else if (reg && is_spillable_regtype(reg->type)) { 3514 /* register containing pointer is being spilled into stack */ 3515 if (size != BPF_REG_SIZE) { 3516 verbose_linfo(env, insn_idx, "; "); 3517 verbose(env, "invalid size of register spill\n"); 3518 return -EACCES; 3519 } 3520 if (state != cur && reg->type == PTR_TO_STACK) { 3521 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 3522 return -EINVAL; 3523 } 3524 save_register_state(env, state, spi, reg, size); 3525 } else { 3526 u8 type = STACK_MISC; 3527 3528 scrub_special_slot(state, spi); 3529 3530 /* when we zero initialize stack slots mark them as such */ 3531 if ((reg && bpf_register_is_null(reg)) || 3532 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 3533 /* STACK_ZERO case happened because register spill 3534 * wasn't properly aligned at the stack slot boundary, 3535 * so it's not a register spill anymore; force 3536 * originating register to be precise to make 3537 * STACK_ZERO correct for subsequent states 3538 */ 3539 err = mark_chain_precision(env, value_regno); 3540 if (err) 3541 return err; 3542 type = STACK_ZERO; 3543 } 3544 3545 /* Mark slots affected by this stack write. */ 3546 for (i = 0; i < size; i++) 3547 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 3548 insn_flags = 0; /* not a register spill */ 3549 } 3550 3551 if (insn_flags) 3552 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3553 hist_spi, hist_frame, 0); 3554 return 0; 3555 } 3556 3557 /* Write the stack: 'stack[ptr_reg + off] = value_regno'. 'ptr_reg' is 3558 * known to contain a variable offset. 3559 * This function checks whether the write is permitted and conservatively 3560 * tracks the effects of the write, considering that each stack slot in the 3561 * dynamic range is potentially written to. 3562 * 3563 * 'value_regno' can be -1, meaning that an unknown value is being written to 3564 * the stack. 3565 * 3566 * Spilled pointers in range are not marked as written because we don't know 3567 * what's going to be actually written. This means that read propagation for 3568 * future reads cannot be terminated by this write. 3569 * 3570 * For privileged programs, uninitialized stack slots are considered 3571 * initialized by this write (even though we don't know exactly what offsets 3572 * are going to be written to). The idea is that we don't want the verifier to 3573 * reject future reads that access slots written to through variable offsets. 3574 */ 3575 static int check_stack_write_var_off(struct bpf_verifier_env *env, 3576 /* func where register points to */ 3577 struct bpf_func_state *state, 3578 struct bpf_reg_state *ptr_reg, int off, int size, 3579 int value_regno, int insn_idx) 3580 { 3581 struct bpf_func_state *cur; /* state of the current function */ 3582 int min_off, max_off; 3583 int i, err; 3584 struct bpf_reg_state *value_reg = NULL; 3585 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3586 bool writing_zero = false; 3587 /* set if the fact that we're writing a zero is used to let any 3588 * stack slots remain STACK_ZERO 3589 */ 3590 bool zero_used = false; 3591 3592 cur = env->cur_state->frame[env->cur_state->curframe]; 3593 min_off = reg_smin(ptr_reg) + off; 3594 max_off = reg_smax(ptr_reg) + off + size; 3595 if (value_regno >= 0) 3596 value_reg = &cur->regs[value_regno]; 3597 if ((value_reg && bpf_register_is_null(value_reg)) || 3598 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 3599 writing_zero = true; 3600 3601 for (i = min_off; i < max_off; i++) { 3602 int spi; 3603 3604 spi = bpf_get_spi(i); 3605 err = destroy_if_dynptr_stack_slot(env, state, spi); 3606 if (err) 3607 return err; 3608 } 3609 3610 check_fastcall_stack_contract(env, state, insn_idx, min_off); 3611 /* Variable offset writes destroy any spilled pointers in range. */ 3612 for (i = min_off; i < max_off; i++) { 3613 u8 new_type, *stype; 3614 int slot, spi; 3615 3616 slot = -i - 1; 3617 spi = slot / BPF_REG_SIZE; 3618 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 3619 mark_stack_slot_scratched(env, spi); 3620 3621 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 3622 /* Reject the write if range we may write to has not 3623 * been initialized beforehand. If we didn't reject 3624 * here, the ptr status would be erased below (even 3625 * though not all slots are actually overwritten), 3626 * possibly opening the door to leaks. 3627 * 3628 * We do however catch STACK_INVALID case below, and 3629 * only allow reading possibly uninitialized memory 3630 * later for CAP_PERFMON, as the write may not happen to 3631 * that slot. 3632 */ 3633 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 3634 insn_idx, i); 3635 return -EINVAL; 3636 } 3637 3638 /* If writing_zero and the spi slot contains a spill of value 0, 3639 * maintain the spill type. 3640 */ 3641 if (writing_zero && *stype == STACK_SPILL && 3642 bpf_is_spilled_scalar_reg(&state->stack[spi])) { 3643 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 3644 3645 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 3646 zero_used = true; 3647 continue; 3648 } 3649 } 3650 3651 /* 3652 * Scrub slots if variable-offset stack write goes over spilled pointers. 3653 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT 3654 * and valid program is rejected by check_stack_read_fixed_off() 3655 * with obscure "invalid size of register fill" message. 3656 */ 3657 scrub_special_slot(state, spi); 3658 3659 /* Update the slot type. */ 3660 new_type = STACK_MISC; 3661 if (writing_zero && *stype == STACK_ZERO) { 3662 new_type = STACK_ZERO; 3663 zero_used = true; 3664 } 3665 /* If the slot is STACK_INVALID, we check whether it's OK to 3666 * pretend that it will be initialized by this write. The slot 3667 * might not actually be written to, and so if we mark it as 3668 * initialized future reads might leak uninitialized memory. 3669 * For privileged programs, we will accept such reads to slots 3670 * that may or may not be written because, if we're reject 3671 * them, the error would be too confusing. 3672 * Conservatively, treat STACK_POISON in a similar way. 3673 */ 3674 if ((*stype == STACK_INVALID || *stype == STACK_POISON) && 3675 !env->allow_uninit_stack) { 3676 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 3677 insn_idx, i); 3678 return -EINVAL; 3679 } 3680 *stype = new_type; 3681 } 3682 if (zero_used) { 3683 /* backtracking doesn't work for STACK_ZERO yet. */ 3684 err = mark_chain_precision(env, value_regno); 3685 if (err) 3686 return err; 3687 } 3688 return 0; 3689 } 3690 3691 /* When register 'dst_regno' is assigned some values from stack[min_off, 3692 * max_off), we set the register's type according to the types of the 3693 * respective stack slots. If all the stack values are known to be zeros, then 3694 * so is the destination reg. Otherwise, the register is considered to be 3695 * SCALAR. This function does not deal with register filling; the caller must 3696 * ensure that all spilled registers in the stack range have been marked as 3697 * read. 3698 */ 3699 static void mark_reg_stack_read(struct bpf_verifier_env *env, 3700 /* func where src register points to */ 3701 struct bpf_func_state *ptr_state, 3702 int min_off, int max_off, int dst_regno) 3703 { 3704 struct bpf_verifier_state *vstate = env->cur_state; 3705 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3706 int i, slot, spi; 3707 u8 *stype; 3708 int zeros = 0; 3709 3710 for (i = min_off; i < max_off; i++) { 3711 slot = -i - 1; 3712 spi = slot / BPF_REG_SIZE; 3713 mark_stack_slot_scratched(env, spi); 3714 stype = ptr_state->stack[spi].slot_type; 3715 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 3716 break; 3717 zeros++; 3718 } 3719 if (zeros == max_off - min_off) { 3720 /* Any access_size read into register is zero extended, 3721 * so the whole register == const_zero. 3722 */ 3723 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3724 } else { 3725 /* have read misc data from the stack */ 3726 mark_reg_unknown(env, state->regs, dst_regno); 3727 } 3728 } 3729 3730 /* Read the stack at 'off' and put the results into the register indicated by 3731 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 3732 * spilled reg. 3733 * 3734 * 'dst_regno' can be -1, meaning that the read value is not going to a 3735 * register. 3736 * 3737 * The access is assumed to be within the current stack bounds. 3738 */ 3739 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 3740 /* func where src register points to */ 3741 struct bpf_func_state *reg_state, 3742 int off, int size, int dst_regno) 3743 { 3744 struct bpf_verifier_state *vstate = env->cur_state; 3745 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3746 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 3747 struct bpf_reg_state *reg; 3748 u8 *stype, type; 3749 int insn_flags = INSN_F_STACK_ACCESS; 3750 int hist_spi = spi, hist_frame = reg_state->frameno; 3751 3752 stype = reg_state->stack[spi].slot_type; 3753 reg = ®_state->stack[spi].spilled_ptr; 3754 3755 mark_stack_slot_scratched(env, spi); 3756 check_fastcall_stack_contract(env, state, env->insn_idx, off); 3757 3758 if (bpf_is_spilled_reg(®_state->stack[spi])) { 3759 u8 spill_size = 1; 3760 3761 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 3762 spill_size++; 3763 3764 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 3765 if (reg->type != SCALAR_VALUE) { 3766 verbose_linfo(env, env->insn_idx, "; "); 3767 verbose(env, "invalid size of register fill\n"); 3768 return -EACCES; 3769 } 3770 3771 if (dst_regno < 0) 3772 return 0; 3773 3774 if (size <= spill_size && 3775 bpf_stack_narrow_access_ok(off, size, spill_size)) { 3776 /* The earlier check_reg_arg() has decided the 3777 * subreg_def for this insn. Save it first. 3778 */ 3779 s32 subreg_def = state->regs[dst_regno].subreg_def; 3780 3781 if (env->bpf_capable && size == 4 && spill_size == 4 && 3782 get_reg_width(reg) <= 32) 3783 /* Ensure stack slot has an ID to build a relation 3784 * with the destination register on fill. 3785 */ 3786 assign_scalar_id_before_mov(env, reg); 3787 state->regs[dst_regno] = *reg; 3788 state->regs[dst_regno].subreg_def = subreg_def; 3789 3790 /* Break the relation on a narrowing fill. 3791 * coerce_reg_to_size will adjust the boundaries. 3792 */ 3793 if (get_reg_width(reg) > size * BITS_PER_BYTE) 3794 clear_scalar_id(&state->regs[dst_regno]); 3795 } else { 3796 int spill_cnt = 0, zero_cnt = 0; 3797 3798 for (i = 0; i < size; i++) { 3799 type = stype[(slot - i) % BPF_REG_SIZE]; 3800 if (type == STACK_SPILL) { 3801 spill_cnt++; 3802 continue; 3803 } 3804 if (type == STACK_MISC) 3805 continue; 3806 if (type == STACK_ZERO) { 3807 zero_cnt++; 3808 continue; 3809 } 3810 if (type == STACK_INVALID && env->allow_uninit_stack) 3811 continue; 3812 if (type == STACK_POISON) { 3813 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3814 off, i, size); 3815 } else { 3816 verbose(env, "invalid read from stack off %d+%d size %d\n", 3817 off, i, size); 3818 } 3819 return -EACCES; 3820 } 3821 3822 if (spill_cnt == size && 3823 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 3824 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3825 /* this IS register fill, so keep insn_flags */ 3826 } else if (zero_cnt == size) { 3827 /* similarly to mark_reg_stack_read(), preserve zeroes */ 3828 __mark_reg_const_zero(env, &state->regs[dst_regno]); 3829 insn_flags = 0; /* not restoring original register state */ 3830 } else { 3831 mark_reg_unknown(env, state->regs, dst_regno); 3832 insn_flags = 0; /* not restoring original register state */ 3833 } 3834 } 3835 } else if (dst_regno >= 0) { 3836 /* restore register state from stack */ 3837 if (env->bpf_capable) 3838 /* Ensure stack slot has an ID to build a relation 3839 * with the destination register on fill. 3840 */ 3841 assign_scalar_id_before_mov(env, reg); 3842 state->regs[dst_regno] = *reg; 3843 /* mark reg as written since spilled pointer state likely 3844 * has its liveness marks cleared by is_state_visited() 3845 * which resets stack/reg liveness for state transitions 3846 */ 3847 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 3848 /* If dst_regno==-1, the caller is asking us whether 3849 * it is acceptable to use this value as a SCALAR_VALUE 3850 * (e.g. for XADD). 3851 * We must not allow unprivileged callers to do that 3852 * with spilled pointers. 3853 */ 3854 verbose(env, "leaking pointer from stack off %d\n", 3855 off); 3856 return -EACCES; 3857 } 3858 } else { 3859 for (i = 0; i < size; i++) { 3860 type = stype[(slot - i) % BPF_REG_SIZE]; 3861 if (type == STACK_MISC) 3862 continue; 3863 if (type == STACK_ZERO) 3864 continue; 3865 if (type == STACK_INVALID && env->allow_uninit_stack) 3866 continue; 3867 if (type == STACK_POISON) { 3868 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 3869 off, i, size); 3870 } else { 3871 verbose(env, "invalid read from stack off %d+%d size %d\n", 3872 off, i, size); 3873 } 3874 return -EACCES; 3875 } 3876 if (dst_regno >= 0) 3877 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3878 insn_flags = 0; /* we are not restoring spilled register */ 3879 } 3880 if (insn_flags) 3881 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 3882 hist_spi, hist_frame, 0); 3883 return 0; 3884 } 3885 3886 enum bpf_access_src { 3887 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3888 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3889 }; 3890 3891 static int check_stack_range_initialized(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3892 argno_t argno, int off, int access_size, 3893 bool zero_size_allowed, 3894 enum bpf_access_type type, 3895 struct bpf_call_arg_meta *meta); 3896 3897 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3898 { 3899 return cur_regs(env) + regno; 3900 } 3901 3902 /* Read the stack at 'reg + off' and put the result into the register 3903 * 'dst_regno'. 3904 * 'off' includes the pointer register's fixed offset(i.e. 'reg->off'), 3905 * but not its variable offset. 3906 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3907 * 3908 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3909 * filling registers (i.e. reads of spilled register cannot be detected when 3910 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3911 * SCALAR_VALUE. That's why we assert that the 'reg' has a variable 3912 * offset; for a fixed offset check_stack_read_fixed_off should be used 3913 * instead. 3914 */ 3915 static int check_stack_read_var_off(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3916 argno_t ptr_argno, int off, int size, int dst_regno) 3917 { 3918 struct bpf_func_state *ptr_state = bpf_func(env, reg); 3919 int err; 3920 int min_off, max_off; 3921 3922 /* Note that we pass a NULL meta, so raw access will not be permitted. 3923 */ 3924 err = check_stack_range_initialized(env, reg, ptr_argno, off, size, 3925 false, BPF_READ, NULL); 3926 if (err) 3927 return err; 3928 3929 min_off = reg_smin(reg) + off; 3930 max_off = reg_smax(reg) + off; 3931 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 3932 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 3933 return 0; 3934 } 3935 3936 /* check_stack_read dispatches to check_stack_read_fixed_off or 3937 * check_stack_read_var_off. 3938 * 3939 * The caller must ensure that the offset falls within the allocated stack 3940 * bounds. 3941 * 3942 * 'dst_regno' is a register which will receive the value from the stack. It 3943 * can be -1, meaning that the read value is not going to a register. 3944 */ 3945 static int check_stack_read(struct bpf_verifier_env *env, 3946 struct bpf_reg_state *reg, argno_t ptr_argno, int off, int size, 3947 int dst_regno) 3948 { 3949 struct bpf_func_state *state = bpf_func(env, reg); 3950 int err; 3951 /* Some accesses are only permitted with a static offset. */ 3952 bool var_off = !tnum_is_const(reg->var_off); 3953 3954 /* The offset is required to be static when reads don't go to a 3955 * register, in order to not leak pointers (see 3956 * check_stack_read_fixed_off). 3957 */ 3958 if (dst_regno < 0 && var_off) { 3959 char tn_buf[48]; 3960 3961 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3962 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 3963 tn_buf, off, size); 3964 return -EACCES; 3965 } 3966 /* Variable offset is prohibited for unprivileged mode for simplicity 3967 * since it requires corresponding support in Spectre masking for stack 3968 * ALU. See also retrieve_ptr_limit(). The check in 3969 * check_stack_access_for_ptr_arithmetic() called by 3970 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 3971 * with variable offsets, therefore no check is required here. Further, 3972 * just checking it here would be insufficient as speculative stack 3973 * writes could still lead to unsafe speculative behaviour. 3974 */ 3975 if (!var_off) { 3976 off += reg->var_off.value; 3977 err = check_stack_read_fixed_off(env, state, off, size, 3978 dst_regno); 3979 } else { 3980 /* Variable offset stack reads need more conservative handling 3981 * than fixed offset ones. Note that dst_regno >= 0 on this 3982 * branch. 3983 */ 3984 err = check_stack_read_var_off(env, reg, ptr_argno, off, size, 3985 dst_regno); 3986 } 3987 return err; 3988 } 3989 3990 3991 /* check_stack_write dispatches to check_stack_write_fixed_off or 3992 * check_stack_write_var_off. 3993 * 3994 * 'reg' is the register used as a pointer into the stack. 3995 * 'value_regno' is the register whose value we're writing to the stack. It can 3996 * be -1, meaning that we're not writing from a register. 3997 * 3998 * The caller must ensure that the offset falls within the maximum stack size. 3999 */ 4000 static int check_stack_write(struct bpf_verifier_env *env, 4001 struct bpf_reg_state *reg, int off, int size, 4002 int value_regno, int insn_idx) 4003 { 4004 struct bpf_func_state *state = bpf_func(env, reg); 4005 int err; 4006 4007 if (tnum_is_const(reg->var_off)) { 4008 off += reg->var_off.value; 4009 err = check_stack_write_fixed_off(env, state, off, size, 4010 value_regno, insn_idx); 4011 } else { 4012 /* Variable offset stack reads need more conservative handling 4013 * than fixed offset ones. 4014 */ 4015 err = check_stack_write_var_off(env, state, 4016 reg, off, size, 4017 value_regno, insn_idx); 4018 } 4019 return err; 4020 } 4021 4022 /* 4023 * Write a value to the outgoing stack arg area. 4024 * off is a negative offset from r11 (e.g. -8 for arg6, -16 for arg7). 4025 */ 4026 static int check_stack_arg_write(struct bpf_verifier_env *env, struct bpf_func_state *state, 4027 int off, struct bpf_reg_state *value_reg) 4028 { 4029 int max_stack_arg_regs = MAX_BPF_FUNC_ARGS - MAX_BPF_FUNC_REG_ARGS; 4030 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4031 int spi = -off / BPF_REG_SIZE - 1; 4032 struct bpf_reg_state *arg; 4033 int err; 4034 4035 if (spi >= max_stack_arg_regs) { 4036 verbose(env, "stack arg write offset %d exceeds max %d stack args\n", 4037 off, max_stack_arg_regs); 4038 return -EINVAL; 4039 } 4040 4041 err = grow_stack_arg_slots(env, state, spi + 1); 4042 if (err) 4043 return err; 4044 4045 /* Track the max outgoing stack arg slot count. */ 4046 if (spi + 1 > subprog->max_out_stack_arg_cnt) 4047 subprog->max_out_stack_arg_cnt = spi + 1; 4048 4049 if (value_reg) { 4050 state->stack_arg_regs[spi] = *value_reg; 4051 } else { 4052 /* BPF_ST: store immediate, treat as scalar */ 4053 arg = &state->stack_arg_regs[spi]; 4054 arg->type = SCALAR_VALUE; 4055 __mark_reg_known(arg, env->prog->insnsi[env->insn_idx].imm); 4056 } 4057 state->no_stack_arg_load = true; 4058 return bpf_push_jmp_history(env, env->cur_state, 4059 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4060 } 4061 4062 /* 4063 * Read a value from the incoming stack arg area. 4064 * off is a positive offset from r11 (e.g. +8 for arg6, +16 for arg7). 4065 */ 4066 static int check_stack_arg_read(struct bpf_verifier_env *env, struct bpf_func_state *state, 4067 int off, int dst_regno) 4068 { 4069 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 4070 struct bpf_verifier_state *vstate = env->cur_state; 4071 int spi = off / BPF_REG_SIZE - 1; 4072 struct bpf_func_state *caller, *cur; 4073 struct bpf_reg_state *arg; 4074 4075 if (state->no_stack_arg_load) { 4076 verbose(env, "r11 load must be before any r11 store or call insn\n"); 4077 return -EINVAL; 4078 } 4079 4080 if (spi + 1 > bpf_in_stack_arg_cnt(subprog)) { 4081 verbose(env, "invalid read from stack arg off %d depth %d\n", 4082 off, bpf_in_stack_arg_cnt(subprog) * BPF_REG_SIZE); 4083 return -EACCES; 4084 } 4085 4086 caller = vstate->frame[vstate->curframe - 1]; 4087 arg = &caller->stack_arg_regs[spi]; 4088 cur = vstate->frame[vstate->curframe]; 4089 cur->regs[dst_regno] = *arg; 4090 return bpf_push_jmp_history(env, env->cur_state, 4091 INSN_F_STACK_ARG_ACCESS, spi, 0, 0); 4092 } 4093 4094 static int mark_stack_arg_precision(struct bpf_verifier_env *env, int arg_idx) 4095 { 4096 struct bpf_func_state *caller = cur_func(env); 4097 int spi = arg_idx - MAX_BPF_FUNC_REG_ARGS; 4098 4099 bt_set_frame_stack_arg_slot(&env->bt, caller->frameno, spi); 4100 return mark_chain_precision_batch(env, env->cur_state); 4101 } 4102 4103 static int check_outgoing_stack_args(struct bpf_verifier_env *env, struct bpf_func_state *caller, 4104 int nargs) 4105 { 4106 int i, spi; 4107 4108 for (i = MAX_BPF_FUNC_REG_ARGS; i < nargs; i++) { 4109 spi = i - MAX_BPF_FUNC_REG_ARGS; 4110 if (spi >= caller->out_stack_arg_cnt || 4111 caller->stack_arg_regs[spi].type == NOT_INIT) { 4112 verbose(env, "callee expects %d args, stack arg%d is not initialized\n", 4113 nargs, spi + 1); 4114 return -EFAULT; 4115 } 4116 } 4117 4118 return 0; 4119 } 4120 4121 static struct bpf_reg_state *get_func_arg_reg(struct bpf_func_state *caller, 4122 struct bpf_reg_state *regs, int arg) 4123 { 4124 if (arg < MAX_BPF_FUNC_REG_ARGS) 4125 return ®s[arg + 1]; 4126 4127 return &caller->stack_arg_regs[arg - MAX_BPF_FUNC_REG_ARGS]; 4128 } 4129 4130 static int check_map_access_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4131 int off, int size, enum bpf_access_type type) 4132 { 4133 struct bpf_map *map = reg->map_ptr; 4134 u32 cap = bpf_map_flags_to_cap(map); 4135 4136 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4137 verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n", 4138 map->value_size, reg_smin(reg) + off, size); 4139 return -EACCES; 4140 } 4141 4142 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4143 verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n", 4144 map->value_size, reg_smin(reg) + off, size); 4145 return -EACCES; 4146 } 4147 4148 return 0; 4149 } 4150 4151 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4152 static int __check_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4153 int off, int size, u32 mem_size, 4154 bool zero_size_allowed) 4155 { 4156 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4157 4158 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4159 return 0; 4160 4161 switch (reg->type) { 4162 case PTR_TO_MAP_KEY: 4163 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4164 mem_size, off, size); 4165 break; 4166 case PTR_TO_MAP_VALUE: 4167 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4168 mem_size, off, size); 4169 break; 4170 case PTR_TO_PACKET: 4171 case PTR_TO_PACKET_META: 4172 case PTR_TO_PACKET_END: 4173 verbose(env, "invalid access to packet, off=%d size=%d, %s(id=%d,off=%d,r=%d)\n", 4174 off, size, reg_arg_name(env, argno), reg->id, off, mem_size); 4175 break; 4176 case PTR_TO_CTX: 4177 verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n", 4178 mem_size, off, size); 4179 break; 4180 case PTR_TO_MEM: 4181 default: 4182 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4183 mem_size, off, size); 4184 } 4185 4186 return -EACCES; 4187 } 4188 4189 /* check read/write into a memory region with possible variable offset */ 4190 static int check_mem_region_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4191 int off, int size, u32 mem_size, 4192 bool zero_size_allowed) 4193 { 4194 int err; 4195 4196 /* We may have adjusted the register pointing to memory region, so we 4197 * need to try adding each of min_value and max_value to off 4198 * to make sure our theoretical access will be safe. 4199 * 4200 * The minimum value is only important with signed 4201 * comparisons where we can't assume the floor of a 4202 * value is 0. If we are using signed variables for our 4203 * index'es we need to make sure that whatever we use 4204 * will have a set floor within our range. 4205 */ 4206 if (reg_smin(reg) < 0 && 4207 (reg_smin(reg) == S64_MIN || 4208 (off + reg_smin(reg) != (s64)(s32)(off + reg_smin(reg))) || 4209 reg_smin(reg) + off < 0)) { 4210 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4211 reg_arg_name(env, argno)); 4212 return -EACCES; 4213 } 4214 err = __check_mem_access(env, reg, argno, reg_smin(reg) + off, size, 4215 mem_size, zero_size_allowed); 4216 if (err) { 4217 verbose(env, "%s min value is outside of the allowed memory range\n", 4218 reg_arg_name(env, argno)); 4219 return err; 4220 } 4221 4222 /* If we haven't set a max value then we need to bail since we can't be 4223 * sure we won't do bad things. 4224 * If reg_umax(reg) + off could overflow, treat that as unbounded too. 4225 */ 4226 if (reg_umax(reg) >= BPF_MAX_VAR_OFF) { 4227 verbose(env, "%s unbounded memory access, make sure to bounds check any such access\n", 4228 reg_arg_name(env, argno)); 4229 return -EACCES; 4230 } 4231 err = __check_mem_access(env, reg, argno, reg_umax(reg) + off, size, 4232 mem_size, zero_size_allowed); 4233 if (err) { 4234 verbose(env, "%s max value is outside of the allowed memory range\n", 4235 reg_arg_name(env, argno)); 4236 return err; 4237 } 4238 4239 return 0; 4240 } 4241 4242 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4243 const struct bpf_reg_state *reg, argno_t argno, 4244 bool fixed_off_ok) 4245 { 4246 /* Access to this pointer-typed register or passing it to a helper 4247 * is only allowed in its original, unmodified form. 4248 */ 4249 4250 if (!tnum_is_const(reg->var_off)) { 4251 char tn_buf[48]; 4252 4253 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4254 verbose(env, "variable %s access var_off=%s disallowed\n", 4255 reg_type_str(env, reg->type), tn_buf); 4256 return -EACCES; 4257 } 4258 4259 if (reg_smin(reg) < 0) { 4260 verbose(env, "negative offset %s ptr %s off=%lld disallowed\n", 4261 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4262 return -EACCES; 4263 } 4264 4265 if (!fixed_off_ok && reg->var_off.value != 0) { 4266 verbose(env, "dereference of modified %s ptr %s off=%lld disallowed\n", 4267 reg_type_str(env, reg->type), reg_arg_name(env, argno), reg->var_off.value); 4268 return -EACCES; 4269 } 4270 4271 return 0; 4272 } 4273 4274 static int check_ptr_off_reg(struct bpf_verifier_env *env, 4275 const struct bpf_reg_state *reg, int regno) 4276 { 4277 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 4278 } 4279 4280 static int map_kptr_match_type(struct bpf_verifier_env *env, 4281 struct btf_field *kptr_field, 4282 struct bpf_reg_state *reg, u32 regno) 4283 { 4284 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4285 int perm_flags; 4286 const char *reg_name = ""; 4287 4288 if (base_type(reg->type) != PTR_TO_BTF_ID) 4289 goto bad_type; 4290 4291 if (btf_is_kernel(reg->btf)) { 4292 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 4293 4294 /* Only unreferenced case accepts untrusted pointers */ 4295 if (kptr_field->type == BPF_KPTR_UNREF) 4296 perm_flags |= PTR_UNTRUSTED; 4297 } else { 4298 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 4299 if (kptr_field->type == BPF_KPTR_PERCPU) 4300 perm_flags |= MEM_PERCPU; 4301 } 4302 4303 if (type_flag(reg->type) & ~perm_flags) 4304 goto bad_type; 4305 4306 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4307 reg_name = btf_type_name(reg->btf, reg->btf_id); 4308 4309 /* For ref_ptr case, release function check should ensure we get one 4310 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4311 * normal store of unreferenced kptr, we must ensure var_off is zero. 4312 * Since ref_ptr cannot be accessed directly by BPF insns, check for 4313 * reg->id is not needed here. 4314 */ 4315 if (__check_ptr_off_reg(env, reg, argno_from_reg(regno), true)) 4316 return -EACCES; 4317 4318 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 4319 * we also need to take into account the reg->var_off. 4320 * 4321 * We want to support cases like: 4322 * 4323 * struct foo { 4324 * struct bar br; 4325 * struct baz bz; 4326 * }; 4327 * 4328 * struct foo *v; 4329 * v = func(); // PTR_TO_BTF_ID 4330 * val->foo = v; // reg->var_off is zero, btf and btf_id match type 4331 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with 4332 * // first member type of struct after comparison fails 4333 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked 4334 * // to match type 4335 * 4336 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off 4337 * is zero. We must also ensure that btf_struct_ids_match does not walk 4338 * the struct to match type against first member of struct, i.e. reject 4339 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4340 * strict mode to true for type match. 4341 */ 4342 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value, 4343 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4344 kptr_field->type != BPF_KPTR_UNREF)) 4345 goto bad_type; 4346 return 0; 4347 bad_type: 4348 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4349 reg_type_str(env, reg->type), reg_name); 4350 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4351 if (kptr_field->type == BPF_KPTR_UNREF) 4352 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4353 targ_name); 4354 else 4355 verbose(env, "\n"); 4356 return -EINVAL; 4357 } 4358 4359 static bool in_sleepable(struct bpf_verifier_env *env) 4360 { 4361 return env->cur_state->in_sleepable; 4362 } 4363 4364 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 4365 * can dereference RCU protected pointers and result is PTR_TRUSTED. 4366 */ 4367 static bool in_rcu_cs(struct bpf_verifier_env *env) 4368 { 4369 return env->cur_state->active_rcu_locks || 4370 env->cur_state->active_locks || 4371 !in_sleepable(env); 4372 } 4373 4374 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 4375 BTF_SET_START(rcu_protected_types) 4376 #ifdef CONFIG_NET 4377 BTF_ID(struct, prog_test_ref_kfunc) 4378 #endif 4379 #ifdef CONFIG_CGROUPS 4380 BTF_ID(struct, cgroup) 4381 #endif 4382 #ifdef CONFIG_BPF_JIT 4383 BTF_ID(struct, bpf_cpumask) 4384 #endif 4385 BTF_ID(struct, task_struct) 4386 #ifdef CONFIG_CRYPTO 4387 BTF_ID(struct, bpf_crypto_ctx) 4388 #endif 4389 BTF_SET_END(rcu_protected_types) 4390 4391 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 4392 { 4393 if (!btf_is_kernel(btf)) 4394 return true; 4395 return btf_id_set_contains(&rcu_protected_types, btf_id); 4396 } 4397 4398 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 4399 { 4400 struct btf_struct_meta *meta; 4401 4402 if (btf_is_kernel(kptr_field->kptr.btf)) 4403 return NULL; 4404 4405 meta = btf_find_struct_meta(kptr_field->kptr.btf, 4406 kptr_field->kptr.btf_id); 4407 4408 return meta ? meta->record : NULL; 4409 } 4410 4411 static bool rcu_safe_kptr(const struct btf_field *field) 4412 { 4413 const struct btf_field_kptr *kptr = &field->kptr; 4414 4415 return field->type == BPF_KPTR_PERCPU || 4416 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 4417 } 4418 4419 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 4420 { 4421 struct btf_record *rec; 4422 u32 ret; 4423 4424 ret = PTR_MAYBE_NULL; 4425 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 4426 ret |= MEM_RCU; 4427 if (kptr_field->type == BPF_KPTR_PERCPU) 4428 ret |= MEM_PERCPU; 4429 else if (!btf_is_kernel(kptr_field->kptr.btf)) 4430 ret |= MEM_ALLOC; 4431 4432 rec = kptr_pointee_btf_record(kptr_field); 4433 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 4434 ret |= NON_OWN_REF; 4435 } else { 4436 ret |= PTR_UNTRUSTED; 4437 } 4438 4439 return ret; 4440 } 4441 4442 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 4443 struct btf_field *field) 4444 { 4445 struct bpf_reg_state *reg; 4446 const struct btf_type *t; 4447 4448 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 4449 mark_reg_known_zero(env, cur_regs(env), regno); 4450 reg = reg_state(env, regno); 4451 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 4452 reg->mem_size = t->size; 4453 reg->id = ++env->id_gen; 4454 4455 return 0; 4456 } 4457 4458 static int check_map_kptr_access(struct bpf_verifier_env *env, 4459 int value_regno, int insn_idx, 4460 struct btf_field *kptr_field) 4461 { 4462 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4463 int class = BPF_CLASS(insn->code); 4464 struct bpf_reg_state *val_reg; 4465 int ret; 4466 4467 /* Things we already checked for in check_map_access and caller: 4468 * - Reject cases where variable offset may touch kptr 4469 * - size of access (must be BPF_DW) 4470 * - tnum_is_const(reg->var_off) 4471 * - kptr_field->offset == off + reg->var_off.value 4472 */ 4473 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4474 if (BPF_MODE(insn->code) != BPF_MEM) { 4475 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4476 return -EACCES; 4477 } 4478 4479 /* We only allow loading referenced kptr, since it will be marked as 4480 * untrusted, similar to unreferenced kptr. 4481 */ 4482 if (class != BPF_LDX && 4483 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 4484 verbose(env, "store to referenced kptr disallowed\n"); 4485 return -EACCES; 4486 } 4487 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 4488 verbose(env, "store to uptr disallowed\n"); 4489 return -EACCES; 4490 } 4491 4492 if (class == BPF_LDX) { 4493 if (kptr_field->type == BPF_UPTR) 4494 return mark_uptr_ld_reg(env, value_regno, kptr_field); 4495 4496 /* We can simply mark the value_regno receiving the pointer 4497 * value from map as PTR_TO_BTF_ID, with the correct type. 4498 */ 4499 ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, 4500 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4501 btf_ld_kptr_type(env, kptr_field)); 4502 if (ret < 0) 4503 return ret; 4504 } else if (class == BPF_STX) { 4505 val_reg = reg_state(env, value_regno); 4506 if (!bpf_register_is_null(val_reg) && 4507 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4508 return -EACCES; 4509 } else if (class == BPF_ST) { 4510 if (insn->imm) { 4511 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4512 kptr_field->offset); 4513 return -EACCES; 4514 } 4515 } else { 4516 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4517 return -EACCES; 4518 } 4519 return 0; 4520 } 4521 4522 /* 4523 * Return the size of the memory region accessible from a pointer to map value. 4524 * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible. 4525 */ 4526 static u32 map_mem_size(const struct bpf_map *map) 4527 { 4528 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) 4529 return map->max_entries * sizeof(long); 4530 4531 return map->value_size; 4532 } 4533 4534 /* check read/write into a map element with possible variable offset */ 4535 static int check_map_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 4536 int off, int size, bool zero_size_allowed, 4537 enum bpf_access_src src) 4538 { 4539 struct bpf_map *map = reg->map_ptr; 4540 u32 mem_size = map_mem_size(map); 4541 struct btf_record *rec; 4542 int err, i; 4543 4544 err = check_mem_region_access(env, reg, argno, off, size, mem_size, zero_size_allowed); 4545 if (err) 4546 return err; 4547 4548 if (IS_ERR_OR_NULL(map->record)) 4549 return 0; 4550 rec = map->record; 4551 for (i = 0; i < rec->cnt; i++) { 4552 struct btf_field *field = &rec->fields[i]; 4553 u32 p = field->offset; 4554 4555 /* If any part of a field can be touched by load/store, reject 4556 * this program. To check that [x1, x2) overlaps with [y1, y2), 4557 * it is sufficient to check x1 < y2 && y1 < x2. 4558 */ 4559 if (reg_smin(reg) + off < p + field->size && 4560 p < reg_umax(reg) + off + size) { 4561 switch (field->type) { 4562 case BPF_KPTR_UNREF: 4563 case BPF_KPTR_REF: 4564 case BPF_KPTR_PERCPU: 4565 case BPF_UPTR: 4566 if (src != ACCESS_DIRECT) { 4567 verbose(env, "%s cannot be accessed indirectly by helper\n", 4568 btf_field_type_name(field->type)); 4569 return -EACCES; 4570 } 4571 if (!tnum_is_const(reg->var_off)) { 4572 verbose(env, "%s access cannot have variable offset\n", 4573 btf_field_type_name(field->type)); 4574 return -EACCES; 4575 } 4576 if (p != off + reg->var_off.value) { 4577 verbose(env, "%s access misaligned expected=%u off=%llu\n", 4578 btf_field_type_name(field->type), 4579 p, off + reg->var_off.value); 4580 return -EACCES; 4581 } 4582 if (size != bpf_size_to_bytes(BPF_DW)) { 4583 verbose(env, "%s access size must be BPF_DW\n", 4584 btf_field_type_name(field->type)); 4585 return -EACCES; 4586 } 4587 break; 4588 default: 4589 verbose(env, "%s cannot be accessed directly by load/store\n", 4590 btf_field_type_name(field->type)); 4591 return -EACCES; 4592 } 4593 } 4594 } 4595 return 0; 4596 } 4597 4598 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4599 const struct bpf_call_arg_meta *meta, 4600 enum bpf_access_type t) 4601 { 4602 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4603 4604 switch (prog_type) { 4605 /* Program types only with direct read access go here! */ 4606 case BPF_PROG_TYPE_LWT_IN: 4607 case BPF_PROG_TYPE_LWT_OUT: 4608 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4609 case BPF_PROG_TYPE_SK_REUSEPORT: 4610 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4611 case BPF_PROG_TYPE_CGROUP_SKB: 4612 if (t == BPF_WRITE) 4613 return false; 4614 fallthrough; 4615 4616 /* Program types with direct read + write access go here! */ 4617 case BPF_PROG_TYPE_SCHED_CLS: 4618 case BPF_PROG_TYPE_SCHED_ACT: 4619 case BPF_PROG_TYPE_XDP: 4620 case BPF_PROG_TYPE_LWT_XMIT: 4621 case BPF_PROG_TYPE_SK_SKB: 4622 case BPF_PROG_TYPE_SK_MSG: 4623 if (meta) 4624 return meta->pkt_access; 4625 4626 env->seen_direct_write = true; 4627 return true; 4628 4629 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4630 if (t == BPF_WRITE) 4631 env->seen_direct_write = true; 4632 4633 return true; 4634 4635 default: 4636 return false; 4637 } 4638 } 4639 4640 static int check_packet_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 4641 int size, bool zero_size_allowed) 4642 { 4643 int err; 4644 4645 if (reg->range < 0) { 4646 verbose(env, "%s offset is outside of the packet\n", reg_arg_name(env, argno)); 4647 return -EINVAL; 4648 } 4649 4650 err = check_mem_region_access(env, reg, argno, off, size, reg->range, zero_size_allowed); 4651 if (err) 4652 return err; 4653 4654 /* __check_mem_access has made sure "off + size - 1" is within u16. 4655 * reg_umax(reg) can't be bigger than MAX_PACKET_OFF which is 0xffff, 4656 * otherwise find_good_pkt_pointers would have refused to set range info 4657 * that __check_mem_access would have rejected this pkt access. 4658 * Therefore, "off + reg_umax(reg) + size - 1" won't overflow u32. 4659 */ 4660 env->prog->aux->max_pkt_offset = 4661 max_t(u32, env->prog->aux->max_pkt_offset, 4662 off + reg_umax(reg) + size - 1); 4663 4664 return 0; 4665 } 4666 4667 static bool is_var_ctx_off_allowed(struct bpf_prog *prog) 4668 { 4669 return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL; 4670 } 4671 4672 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 4673 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 4674 enum bpf_access_type t, struct bpf_insn_access_aux *info) 4675 { 4676 if (env->ops->is_valid_access && 4677 env->ops->is_valid_access(off, size, t, env->prog, info)) { 4678 /* A non zero info.ctx_field_size indicates that this field is a 4679 * candidate for later verifier transformation to load the whole 4680 * field and then apply a mask when accessed with a narrower 4681 * access than actual ctx access size. A zero info.ctx_field_size 4682 * will only allow for whole field access and rejects any other 4683 * type of narrower access. 4684 */ 4685 if (base_type(info->reg_type) == PTR_TO_BTF_ID) { 4686 if (info->ref_id && 4687 !find_reference_state(env->cur_state, info->ref_id)) { 4688 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n", 4689 off); 4690 return -EACCES; 4691 } 4692 } else { 4693 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size; 4694 } 4695 /* remember the offset of last byte accessed in ctx */ 4696 if (env->prog->aux->max_ctx_offset < off + size) 4697 env->prog->aux->max_ctx_offset = off + size; 4698 return 0; 4699 } 4700 4701 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 4702 return -EACCES; 4703 } 4704 4705 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 4706 int off, int access_size, enum bpf_access_type t, 4707 struct bpf_insn_access_aux *info) 4708 { 4709 /* 4710 * Program types that don't rewrite ctx accesses can safely 4711 * dereference ctx pointers with fixed offsets. 4712 */ 4713 bool var_off_ok = is_var_ctx_off_allowed(env->prog); 4714 bool fixed_off_ok = !env->ops->convert_ctx_access; 4715 int err; 4716 4717 if (var_off_ok) 4718 err = check_mem_region_access(env, reg, argno, off, access_size, U16_MAX, false); 4719 else 4720 err = __check_ptr_off_reg(env, reg, argno, fixed_off_ok); 4721 if (err) 4722 return err; 4723 off += reg_umax(reg); 4724 4725 err = __check_ctx_access(env, insn_idx, off, access_size, t, info); 4726 if (err) 4727 verbose_linfo(env, insn_idx, "; "); 4728 return err; 4729 } 4730 4731 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 4732 int size) 4733 { 4734 if (size < 0 || off < 0 || 4735 (u64)off + size > sizeof(struct bpf_flow_keys)) { 4736 verbose(env, "invalid access to flow keys off=%d size=%d\n", 4737 off, size); 4738 return -EACCES; 4739 } 4740 return 0; 4741 } 4742 4743 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 4744 struct bpf_reg_state *reg, argno_t argno, int off, int size, 4745 enum bpf_access_type t) 4746 { 4747 struct bpf_insn_access_aux info = {}; 4748 bool valid; 4749 4750 if (reg_smin(reg) < 0) { 4751 verbose(env, "%s min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4752 reg_arg_name(env, argno)); 4753 return -EACCES; 4754 } 4755 4756 switch (reg->type) { 4757 case PTR_TO_SOCK_COMMON: 4758 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 4759 break; 4760 case PTR_TO_SOCKET: 4761 valid = bpf_sock_is_valid_access(off, size, t, &info); 4762 break; 4763 case PTR_TO_TCP_SOCK: 4764 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 4765 break; 4766 case PTR_TO_XDP_SOCK: 4767 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 4768 break; 4769 default: 4770 valid = false; 4771 } 4772 4773 4774 if (valid) { 4775 env->insn_aux_data[insn_idx].ctx_field_size = 4776 info.ctx_field_size; 4777 return 0; 4778 } 4779 4780 verbose(env, "%s invalid %s access off=%d size=%d\n", 4781 reg_arg_name(env, argno), reg_type_str(env, reg->type), off, size); 4782 4783 return -EACCES; 4784 } 4785 4786 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 4787 { 4788 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 4789 } 4790 4791 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 4792 { 4793 const struct bpf_reg_state *reg = reg_state(env, regno); 4794 4795 return reg->type == PTR_TO_CTX; 4796 } 4797 4798 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 4799 { 4800 const struct bpf_reg_state *reg = reg_state(env, regno); 4801 4802 return type_is_sk_pointer(reg->type); 4803 } 4804 4805 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 4806 { 4807 const struct bpf_reg_state *reg = reg_state(env, regno); 4808 4809 return type_is_pkt_pointer(reg->type); 4810 } 4811 4812 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 4813 { 4814 const struct bpf_reg_state *reg = reg_state(env, regno); 4815 4816 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 4817 return reg->type == PTR_TO_FLOW_KEYS; 4818 } 4819 4820 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 4821 { 4822 const struct bpf_reg_state *reg = reg_state(env, regno); 4823 4824 return reg->type == PTR_TO_ARENA; 4825 } 4826 4827 /* Return false if @regno contains a pointer whose type isn't supported for 4828 * atomic instruction @insn. 4829 */ 4830 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno, 4831 struct bpf_insn *insn) 4832 { 4833 if (is_ctx_reg(env, regno)) 4834 return false; 4835 if (is_pkt_reg(env, regno)) 4836 return false; 4837 if (is_flow_key_reg(env, regno)) 4838 return false; 4839 if (is_sk_reg(env, regno)) 4840 return false; 4841 if (is_arena_reg(env, regno)) 4842 return bpf_jit_supports_insn(insn, true); 4843 4844 return true; 4845 } 4846 4847 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 4848 #ifdef CONFIG_NET 4849 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 4850 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 4851 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 4852 #endif 4853 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 4854 }; 4855 4856 static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_state *reg) 4857 { 4858 /* A referenced register is always trusted. */ 4859 if (reg_is_referenced(env, reg)) 4860 return true; 4861 4862 /* Types listed in the reg2btf_ids are always trusted */ 4863 if (reg2btf_ids[base_type(reg->type)] && 4864 !bpf_type_has_unsafe_modifiers(reg->type)) 4865 return true; 4866 4867 /* If a register is not referenced, it is trusted if it has the 4868 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 4869 * other type modifiers may be safe, but we elect to take an opt-in 4870 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 4871 * not. 4872 * 4873 * Eventually, we should make PTR_TRUSTED the single source of truth 4874 * for whether a register is trusted. 4875 */ 4876 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 4877 !bpf_type_has_unsafe_modifiers(reg->type); 4878 } 4879 4880 static bool is_rcu_reg(const struct bpf_reg_state *reg) 4881 { 4882 return reg->type & MEM_RCU; 4883 } 4884 4885 static void clear_trusted_flags(enum bpf_type_flag *flag) 4886 { 4887 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 4888 } 4889 4890 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 4891 const struct bpf_reg_state *reg, 4892 int off, int size, bool strict) 4893 { 4894 struct tnum reg_off; 4895 int ip_align; 4896 4897 /* Byte size accesses are always allowed. */ 4898 if (!strict || size == 1) 4899 return 0; 4900 4901 /* For platforms that do not have a Kconfig enabling 4902 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 4903 * NET_IP_ALIGN is universally set to '2'. And on platforms 4904 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 4905 * to this code only in strict mode where we want to emulate 4906 * the NET_IP_ALIGN==2 checking. Therefore use an 4907 * unconditional IP align value of '2'. 4908 */ 4909 ip_align = 2; 4910 4911 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off)); 4912 if (!tnum_is_aligned(reg_off, size)) { 4913 char tn_buf[48]; 4914 4915 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4916 verbose(env, 4917 "misaligned packet access off %d+%s+%d size %d\n", 4918 ip_align, tn_buf, off, size); 4919 return -EACCES; 4920 } 4921 4922 return 0; 4923 } 4924 4925 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 4926 const struct bpf_reg_state *reg, 4927 const char *pointer_desc, 4928 int off, int size, bool strict) 4929 { 4930 struct tnum reg_off; 4931 4932 /* Byte size accesses are always allowed. */ 4933 if (!strict || size == 1) 4934 return 0; 4935 4936 reg_off = tnum_add(reg->var_off, tnum_const(off)); 4937 if (!tnum_is_aligned(reg_off, size)) { 4938 char tn_buf[48]; 4939 4940 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4941 verbose(env, "misaligned %saccess off %s+%d size %d\n", 4942 pointer_desc, tn_buf, off, size); 4943 return -EACCES; 4944 } 4945 4946 return 0; 4947 } 4948 4949 static int check_ptr_alignment(struct bpf_verifier_env *env, 4950 const struct bpf_reg_state *reg, int off, 4951 int size, bool strict_alignment_once) 4952 { 4953 bool strict = env->strict_alignment || strict_alignment_once; 4954 const char *pointer_desc = ""; 4955 4956 switch (reg->type) { 4957 case PTR_TO_PACKET: 4958 case PTR_TO_PACKET_META: 4959 /* Special case, because of NET_IP_ALIGN. Given metadata sits 4960 * right in front, treat it the very same way. 4961 */ 4962 return check_pkt_ptr_alignment(env, reg, off, size, strict); 4963 case PTR_TO_FLOW_KEYS: 4964 pointer_desc = "flow keys "; 4965 break; 4966 case PTR_TO_MAP_KEY: 4967 pointer_desc = "key "; 4968 break; 4969 case PTR_TO_MAP_VALUE: 4970 pointer_desc = "value "; 4971 if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY) 4972 strict = true; 4973 break; 4974 case PTR_TO_CTX: 4975 pointer_desc = "context "; 4976 break; 4977 case PTR_TO_STACK: 4978 pointer_desc = "stack "; 4979 /* The stack spill tracking logic in check_stack_write_fixed_off() 4980 * and check_stack_read_fixed_off() relies on stack accesses being 4981 * aligned. 4982 */ 4983 strict = true; 4984 break; 4985 case PTR_TO_SOCKET: 4986 pointer_desc = "sock "; 4987 break; 4988 case PTR_TO_SOCK_COMMON: 4989 pointer_desc = "sock_common "; 4990 break; 4991 case PTR_TO_TCP_SOCK: 4992 pointer_desc = "tcp_sock "; 4993 break; 4994 case PTR_TO_XDP_SOCK: 4995 pointer_desc = "xdp_sock "; 4996 break; 4997 case PTR_TO_ARENA: 4998 return 0; 4999 default: 5000 break; 5001 } 5002 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5003 strict); 5004 } 5005 5006 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 5007 { 5008 if (!bpf_jit_supports_private_stack()) 5009 return NO_PRIV_STACK; 5010 5011 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 5012 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 5013 * explicitly. 5014 */ 5015 switch (prog->type) { 5016 case BPF_PROG_TYPE_KPROBE: 5017 case BPF_PROG_TYPE_TRACEPOINT: 5018 case BPF_PROG_TYPE_PERF_EVENT: 5019 case BPF_PROG_TYPE_RAW_TRACEPOINT: 5020 return PRIV_STACK_ADAPTIVE; 5021 case BPF_PROG_TYPE_TRACING: 5022 case BPF_PROG_TYPE_LSM: 5023 case BPF_PROG_TYPE_STRUCT_OPS: 5024 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 5025 return PRIV_STACK_ADAPTIVE; 5026 fallthrough; 5027 default: 5028 break; 5029 } 5030 5031 return NO_PRIV_STACK; 5032 } 5033 5034 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5035 { 5036 if (env->prog->jit_requested) 5037 return round_up(stack_depth, 16); 5038 5039 /* round up to 32-bytes, since this is granularity 5040 * of interpreter stack size 5041 */ 5042 return round_up(max_t(u32, stack_depth, 1), 32); 5043 } 5044 5045 /* temporary state used for call frame depth calculation */ 5046 struct bpf_subprog_call_depth_info { 5047 int ret_insn; /* caller instruction where we return to. */ 5048 int caller; /* caller subprogram idx */ 5049 int frame; /* # of consecutive static call stack frames on top of stack */ 5050 }; 5051 5052 /* starting from main bpf function walk all instructions of the function 5053 * and recursively walk all callees that given function can call. 5054 * Ignore jump and exit insns. 5055 */ 5056 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 5057 struct bpf_subprog_call_depth_info *dinfo, 5058 bool priv_stack_supported) 5059 { 5060 struct bpf_subprog_info *subprog = env->subprog_info; 5061 struct bpf_insn *insn = env->prog->insnsi; 5062 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 5063 bool tail_call_reachable = false; 5064 int total; 5065 int tmp; 5066 5067 /* no caller idx */ 5068 dinfo[idx].caller = -1; 5069 5070 i = subprog[idx].start; 5071 if (!priv_stack_supported) 5072 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5073 process_func: 5074 /* protect against potential stack overflow that might happen when 5075 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5076 * depth for such case down to 256 so that the worst case scenario 5077 * would result in 8k stack size (32 which is tailcall limit * 256 = 5078 * 8k). 5079 * 5080 * To get the idea what might happen, see an example: 5081 * func1 -> sub rsp, 128 5082 * subfunc1 -> sub rsp, 256 5083 * tailcall1 -> add rsp, 256 5084 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5085 * subfunc2 -> sub rsp, 64 5086 * subfunc22 -> sub rsp, 128 5087 * tailcall2 -> add rsp, 128 5088 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5089 * 5090 * tailcall will unwind the current stack frame but it will not get rid 5091 * of caller's stack as shown on the example above. 5092 */ 5093 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5094 verbose(env, 5095 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5096 depth); 5097 return -EACCES; 5098 } 5099 5100 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 5101 if (IS_ENABLED(CONFIG_X86_64) && subprog[idx].stack_arg_cnt) { 5102 /* x86-64 uses R9 for both private stack frame pointer and arg6. */ 5103 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5104 } else if (priv_stack_supported) { 5105 /* Request private stack support only if the subprog stack 5106 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 5107 * avoid jit penalty if the stack usage is small. 5108 */ 5109 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 5110 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 5111 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 5112 } 5113 5114 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5115 if (subprog_depth > env->max_stack_depth) 5116 env->max_stack_depth = subprog_depth; 5117 if (subprog_depth > MAX_BPF_STACK) { 5118 verbose(env, "stack size of subprog %d is %d. Too large\n", 5119 idx, subprog_depth); 5120 return -EACCES; 5121 } 5122 } else { 5123 depth += subprog_depth; 5124 if (depth > env->max_stack_depth) 5125 env->max_stack_depth = depth; 5126 if (depth > MAX_BPF_STACK) { 5127 total = 0; 5128 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) 5129 total++; 5130 5131 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5132 total, depth); 5133 return -EACCES; 5134 } 5135 } 5136 continue_func: 5137 subprog_end = subprog[idx + 1].start; 5138 for (; i < subprog_end; i++) { 5139 int next_insn, sidx; 5140 5141 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5142 bool err = false; 5143 5144 if (!bpf_is_throw_kfunc(insn + i)) 5145 continue; 5146 for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) { 5147 if (subprog[tmp].is_cb) { 5148 err = true; 5149 break; 5150 } 5151 } 5152 if (!err) 5153 continue; 5154 verbose(env, 5155 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5156 i, idx); 5157 return -EINVAL; 5158 } 5159 5160 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5161 continue; 5162 /* remember insn and function to return to */ 5163 5164 /* find the callee */ 5165 next_insn = i + insn[i].imm + 1; 5166 sidx = bpf_find_subprog(env, next_insn); 5167 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn)) 5168 return -EFAULT; 5169 if (subprog[sidx].is_async_cb) { 5170 if (subprog[sidx].has_tail_call) { 5171 verifier_bug(env, "subprog has tail_call and async cb"); 5172 return -EFAULT; 5173 } 5174 /* async callbacks don't increase bpf prog stack size unless called directly */ 5175 if (!bpf_pseudo_call(insn + i)) 5176 continue; 5177 if (subprog[sidx].is_exception_cb) { 5178 verbose(env, "insn %d cannot call exception cb directly", i); 5179 return -EINVAL; 5180 } 5181 } 5182 5183 /* store caller info for after we return from callee */ 5184 dinfo[idx].frame = frame; 5185 dinfo[idx].ret_insn = i + 1; 5186 5187 /* push caller idx into callee's dinfo */ 5188 dinfo[sidx].caller = idx; 5189 5190 i = next_insn; 5191 5192 idx = sidx; 5193 if (!priv_stack_supported) 5194 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5195 5196 if (subprog[idx].has_tail_call) 5197 tail_call_reachable = true; 5198 5199 frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1; 5200 if (frame >= MAX_CALL_FRAMES) { 5201 verbose(env, "the call stack of %d frames is too deep !\n", 5202 frame); 5203 return -E2BIG; 5204 } 5205 goto process_func; 5206 } 5207 /* if tail call got detected across bpf2bpf calls then mark each of the 5208 * currently present subprog frames as tail call reachable subprogs; 5209 * this info will be utilized by JIT so that we will be preserving the 5210 * tail call counter throughout bpf2bpf calls combined with tailcalls 5211 */ 5212 if (tail_call_reachable) { 5213 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) { 5214 if (subprog[tmp].is_exception_cb) { 5215 verbose(env, "cannot tail call within exception cb\n"); 5216 return -EINVAL; 5217 } 5218 if (subprog[tmp].stack_arg_cnt) { 5219 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5220 return -EINVAL; 5221 } 5222 subprog[tmp].tail_call_reachable = true; 5223 } 5224 } else if (!idx && subprog[0].has_tail_call && subprog[0].stack_arg_cnt) { 5225 verbose(env, "tail_calls are not allowed in programs with stack args\n"); 5226 return -EINVAL; 5227 } 5228 5229 if (subprog[0].tail_call_reachable) 5230 env->prog->aux->tail_call_reachable = true; 5231 5232 /* end of for() loop means the last insn of the 'subprog' 5233 * was reached. Doesn't matter whether it was JA or EXIT 5234 */ 5235 if (frame == 0 && dinfo[idx].caller < 0) 5236 return 0; 5237 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 5238 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 5239 5240 /* pop caller idx from callee */ 5241 idx = dinfo[idx].caller; 5242 5243 /* retrieve caller state from its frame */ 5244 frame = dinfo[idx].frame; 5245 i = dinfo[idx].ret_insn; 5246 5247 /* reset tail_call_reachable to the parent's actual state */ 5248 tail_call_reachable = subprog[idx].tail_call_reachable; 5249 5250 goto continue_func; 5251 } 5252 5253 static int check_max_stack_depth(struct bpf_verifier_env *env) 5254 { 5255 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 5256 struct bpf_subprog_call_depth_info *dinfo; 5257 struct bpf_subprog_info *si = env->subprog_info; 5258 bool priv_stack_supported; 5259 int ret; 5260 5261 dinfo = kvcalloc(env->subprog_cnt, sizeof(*dinfo), GFP_KERNEL_ACCOUNT); 5262 if (!dinfo) 5263 return -ENOMEM; 5264 5265 for (int i = 0; i < env->subprog_cnt; i++) { 5266 if (si[i].has_tail_call) { 5267 priv_stack_mode = NO_PRIV_STACK; 5268 break; 5269 } 5270 } 5271 5272 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 5273 priv_stack_mode = bpf_enable_priv_stack(env->prog); 5274 5275 /* All async_cb subprogs use normal kernel stack. If a particular 5276 * subprog appears in both main prog and async_cb subtree, that 5277 * subprog will use normal kernel stack to avoid potential nesting. 5278 * The reverse subprog traversal ensures when main prog subtree is 5279 * checked, the subprogs appearing in async_cb subtrees are already 5280 * marked as using normal kernel stack, so stack size checking can 5281 * be done properly. 5282 */ 5283 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 5284 if (!i || si[i].is_async_cb) { 5285 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 5286 ret = check_max_stack_depth_subprog(env, i, dinfo, 5287 priv_stack_supported); 5288 if (ret < 0) { 5289 kvfree(dinfo); 5290 return ret; 5291 } 5292 } 5293 } 5294 5295 for (int i = 0; i < env->subprog_cnt; i++) { 5296 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5297 env->prog->aux->jits_use_priv_stack = true; 5298 break; 5299 } 5300 } 5301 5302 kvfree(dinfo); 5303 5304 return 0; 5305 } 5306 5307 static int __check_buffer_access(struct bpf_verifier_env *env, 5308 const char *buf_info, 5309 const struct bpf_reg_state *reg, 5310 argno_t argno, int off, int size) 5311 { 5312 if (off < 0) { 5313 verbose(env, 5314 "%s invalid %s buffer access: off=%d, size=%d\n", 5315 reg_arg_name(env, argno), buf_info, off, size); 5316 return -EACCES; 5317 } 5318 if (!tnum_is_const(reg->var_off)) { 5319 char tn_buf[48]; 5320 5321 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5322 verbose(env, 5323 "%s invalid variable buffer offset: off=%d, var_off=%s\n", 5324 reg_arg_name(env, argno), off, tn_buf); 5325 return -EACCES; 5326 } 5327 5328 return 0; 5329 } 5330 5331 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5332 const struct bpf_reg_state *reg, 5333 argno_t argno, int off, int size) 5334 { 5335 int err; 5336 5337 err = __check_buffer_access(env, "tracepoint", reg, argno, off, size); 5338 if (err) 5339 return err; 5340 5341 env->prog->aux->max_tp_access = max(reg->var_off.value + off + size, 5342 env->prog->aux->max_tp_access); 5343 5344 return 0; 5345 } 5346 5347 static int check_buffer_access(struct bpf_verifier_env *env, 5348 const struct bpf_reg_state *reg, 5349 argno_t argno, int off, int size, 5350 bool zero_size_allowed, 5351 u32 *max_access) 5352 { 5353 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5354 int err; 5355 5356 err = __check_buffer_access(env, buf_info, reg, argno, off, size); 5357 if (err) 5358 return err; 5359 5360 *max_access = max(reg->var_off.value + off + size, *max_access); 5361 5362 return 0; 5363 } 5364 5365 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5366 static void zext_32_to_64(struct bpf_reg_state *reg) 5367 { 5368 reg->var_off = tnum_subreg(reg->var_off); 5369 reg_set_urange64(reg, reg_u32_min(reg), reg_u32_max(reg)); 5370 } 5371 5372 /* truncate register to smaller size (in bytes) 5373 * must be called with size < BPF_REG_SIZE 5374 */ 5375 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5376 { 5377 u64 mask; 5378 5379 /* clear high bits in bit representation */ 5380 reg->var_off = tnum_cast(reg->var_off, size); 5381 5382 /* fix arithmetic bounds */ 5383 mask = ((u64)1 << (size * 8)) - 1; 5384 if ((reg_umin(reg) & ~mask) == (reg_umax(reg) & ~mask)) 5385 reg_set_urange64(reg, reg_umin(reg) & mask, reg_umax(reg) & mask); 5386 else 5387 reg_set_urange64(reg, 0, mask); 5388 5389 /* If size is smaller than 32bit register the 32bit register 5390 * values are also truncated so we push 64-bit bounds into 5391 * 32-bit bounds. Above were truncated < 32-bits already. 5392 */ 5393 if (size < 4) 5394 __mark_reg32_unbounded(reg); 5395 5396 reg_bounds_sync(reg); 5397 } 5398 5399 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 5400 { 5401 if (size == 1) { 5402 reg_set_srange64(reg, S8_MIN, S8_MAX); 5403 reg_set_srange32(reg, S8_MIN, S8_MAX); 5404 } else if (size == 2) { 5405 reg_set_srange64(reg, S16_MIN, S16_MAX); 5406 reg_set_srange32(reg, S16_MIN, S16_MAX); 5407 } else { 5408 /* size == 4 */ 5409 reg_set_srange64(reg, S32_MIN, S32_MAX); 5410 reg_set_srange32(reg, S32_MIN, S32_MAX); 5411 } 5412 reg->var_off = tnum_unknown; 5413 } 5414 5415 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 5416 { 5417 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 5418 u64 top_smax_value, top_smin_value; 5419 u64 num_bits = size * 8; 5420 5421 if (tnum_is_const(reg->var_off)) { 5422 u64_cval = reg->var_off.value; 5423 if (size == 1) 5424 reg->var_off = tnum_const((s8)u64_cval); 5425 else if (size == 2) 5426 reg->var_off = tnum_const((s16)u64_cval); 5427 else 5428 /* size == 4 */ 5429 reg->var_off = tnum_const((s32)u64_cval); 5430 5431 u64_cval = reg->var_off.value; 5432 reg->r64 = cnum64_from_urange(u64_cval, u64_cval); 5433 reg->r32 = cnum32_from_urange((u32)u64_cval, (u32)u64_cval); 5434 return; 5435 } 5436 5437 top_smax_value = ((u64)reg_smax(reg) >> num_bits) << num_bits; 5438 top_smin_value = ((u64)reg_smin(reg) >> num_bits) << num_bits; 5439 5440 if (top_smax_value != top_smin_value) 5441 goto out; 5442 5443 /* find the s64_min and s64_min after sign extension */ 5444 if (size == 1) { 5445 init_s64_max = (s8)reg_smax(reg); 5446 init_s64_min = (s8)reg_smin(reg); 5447 } else if (size == 2) { 5448 init_s64_max = (s16)reg_smax(reg); 5449 init_s64_min = (s16)reg_smin(reg); 5450 } else { 5451 init_s64_max = (s32)reg_smax(reg); 5452 init_s64_min = (s32)reg_smin(reg); 5453 } 5454 5455 s64_max = max(init_s64_max, init_s64_min); 5456 s64_min = min(init_s64_max, init_s64_min); 5457 5458 /* both of s64_max/s64_min positive or negative */ 5459 if ((s64_max >= 0) == (s64_min >= 0)) { 5460 reg_set_srange64(reg, s64_min, s64_max); 5461 reg_set_srange32(reg, s64_min, s64_max); 5462 reg->var_off = tnum_range(s64_min, s64_max); 5463 return; 5464 } 5465 5466 out: 5467 set_sext64_default_val(reg, size); 5468 } 5469 5470 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 5471 { 5472 if (size == 1) 5473 reg_set_srange32(reg, S8_MIN, S8_MAX); 5474 else 5475 /* size == 2 */ 5476 reg_set_srange32(reg, S16_MIN, S16_MAX); 5477 reg->var_off = tnum_subreg(tnum_unknown); 5478 } 5479 5480 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 5481 { 5482 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 5483 u32 top_smax_value, top_smin_value; 5484 u32 num_bits = size * 8; 5485 5486 if (tnum_is_const(reg->var_off)) { 5487 u32_val = reg->var_off.value; 5488 if (size == 1) 5489 reg->var_off = tnum_const((s8)u32_val); 5490 else 5491 reg->var_off = tnum_const((s16)u32_val); 5492 5493 u32_val = reg->var_off.value; 5494 reg_set_srange32(reg, u32_val, u32_val); 5495 return; 5496 } 5497 5498 top_smax_value = ((u32)reg_s32_max(reg) >> num_bits) << num_bits; 5499 top_smin_value = ((u32)reg_s32_min(reg) >> num_bits) << num_bits; 5500 5501 if (top_smax_value != top_smin_value) 5502 goto out; 5503 5504 /* find the s32_min and s32_min after sign extension */ 5505 if (size == 1) { 5506 init_s32_max = (s8)reg_s32_max(reg); 5507 init_s32_min = (s8)reg_s32_min(reg); 5508 } else { 5509 /* size == 2 */ 5510 init_s32_max = (s16)reg_s32_max(reg); 5511 init_s32_min = (s16)reg_s32_min(reg); 5512 } 5513 s32_max = max(init_s32_max, init_s32_min); 5514 s32_min = min(init_s32_max, init_s32_min); 5515 5516 if ((s32_min >= 0) == (s32_max >= 0)) { 5517 reg_set_srange32(reg, s32_min, s32_max); 5518 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 5519 return; 5520 } 5521 5522 out: 5523 set_sext32_default_val(reg, size); 5524 } 5525 5526 bool bpf_map_is_rdonly(const struct bpf_map *map) 5527 { 5528 /* A map is considered read-only if the following condition are true: 5529 * 5530 * 1) BPF program side cannot change any of the map content. The 5531 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 5532 * and was set at map creation time. 5533 * 2) The map value(s) have been initialized from user space by a 5534 * loader and then "frozen", such that no new map update/delete 5535 * operations from syscall side are possible for the rest of 5536 * the map's lifetime from that point onwards. 5537 * 3) Any parallel/pending map update/delete operations from syscall 5538 * side have been completed. Only after that point, it's safe to 5539 * assume that map value(s) are immutable. 5540 */ 5541 return (map->map_flags & BPF_F_RDONLY_PROG) && 5542 READ_ONCE(map->frozen) && 5543 !bpf_map_write_active(map); 5544 } 5545 5546 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 5547 bool is_ldsx) 5548 { 5549 void *ptr; 5550 u64 addr; 5551 int err; 5552 5553 err = map->ops->map_direct_value_addr(map, &addr, off); 5554 if (err) 5555 return err; 5556 ptr = (void *)(long)addr + off; 5557 5558 switch (size) { 5559 case sizeof(u8): 5560 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 5561 break; 5562 case sizeof(u16): 5563 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 5564 break; 5565 case sizeof(u32): 5566 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 5567 break; 5568 case sizeof(u64): 5569 *val = *(u64 *)ptr; 5570 break; 5571 default: 5572 return -EINVAL; 5573 } 5574 return 0; 5575 } 5576 5577 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 5578 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 5579 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 5580 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 5581 5582 /* 5583 * Allow list few fields as RCU trusted or full trusted. 5584 * This logic doesn't allow mix tagging and will be removed once GCC supports 5585 * btf_type_tag. 5586 */ 5587 5588 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 5589 BTF_TYPE_SAFE_RCU(struct task_struct) { 5590 const cpumask_t *cpus_ptr; 5591 struct css_set __rcu *cgroups; 5592 struct task_struct __rcu *real_parent; 5593 struct task_struct *group_leader; 5594 }; 5595 5596 BTF_TYPE_SAFE_RCU(struct cgroup) { 5597 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 5598 struct kernfs_node *kn; 5599 }; 5600 5601 BTF_TYPE_SAFE_RCU(struct css_set) { 5602 struct cgroup *dfl_cgrp; 5603 }; 5604 5605 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) { 5606 struct cgroup *cgroup; 5607 }; 5608 5609 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 5610 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 5611 struct file __rcu *exe_file; 5612 #ifdef CONFIG_MEMCG 5613 struct task_struct __rcu *owner; 5614 #endif 5615 }; 5616 5617 /* skb->sk, req->sk are not RCU protected, but we mark them as such 5618 * because bpf prog accessible sockets are SOCK_RCU_FREE. 5619 */ 5620 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 5621 struct sock *sk; 5622 }; 5623 5624 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 5625 struct sock *sk; 5626 }; 5627 5628 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 5629 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 5630 struct seq_file *seq; 5631 }; 5632 5633 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 5634 struct bpf_iter_meta *meta; 5635 struct task_struct *task; 5636 }; 5637 5638 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 5639 struct file *file; 5640 }; 5641 5642 BTF_TYPE_SAFE_TRUSTED(struct file) { 5643 struct inode *f_inode; 5644 }; 5645 5646 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) { 5647 struct inode *d_inode; 5648 }; 5649 5650 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 5651 struct sock *sk; 5652 }; 5653 5654 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) { 5655 struct mm_struct *vm_mm; 5656 struct file *vm_file; 5657 }; 5658 5659 static bool type_is_rcu(struct bpf_verifier_env *env, 5660 struct bpf_reg_state *reg, 5661 const char *field_name, u32 btf_id) 5662 { 5663 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 5664 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 5665 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 5666 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)); 5667 5668 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 5669 } 5670 5671 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 5672 struct bpf_reg_state *reg, 5673 const char *field_name, u32 btf_id) 5674 { 5675 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 5676 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 5677 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 5678 5679 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 5680 } 5681 5682 static bool type_is_trusted(struct bpf_verifier_env *env, 5683 struct bpf_reg_state *reg, 5684 const char *field_name, u32 btf_id) 5685 { 5686 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 5687 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 5688 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 5689 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 5690 5691 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 5692 } 5693 5694 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 5695 struct bpf_reg_state *reg, 5696 const char *field_name, u32 btf_id) 5697 { 5698 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 5699 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)); 5700 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct)); 5701 5702 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 5703 "__safe_trusted_or_null"); 5704 } 5705 5706 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 5707 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5708 argno_t argno, int off, int size, 5709 enum bpf_access_type atype, 5710 int value_regno) 5711 { 5712 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 5713 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 5714 const char *field_name = NULL; 5715 enum bpf_type_flag flag = 0; 5716 u32 btf_id = 0; 5717 int ret; 5718 5719 if (!env->allow_ptr_leaks) { 5720 verbose(env, 5721 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5722 tname); 5723 return -EPERM; 5724 } 5725 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 5726 verbose(env, 5727 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 5728 tname); 5729 return -EINVAL; 5730 } 5731 5732 if (!tnum_is_const(reg->var_off)) { 5733 char tn_buf[48]; 5734 5735 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5736 verbose(env, 5737 "%s is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 5738 reg_arg_name(env, argno), tname, off, tn_buf); 5739 return -EACCES; 5740 } 5741 5742 off += reg->var_off.value; 5743 5744 if (off < 0) { 5745 verbose(env, 5746 "%s is ptr_%s invalid negative access: off=%d\n", 5747 reg_arg_name(env, argno), tname, off); 5748 return -EACCES; 5749 } 5750 5751 if (reg->type & MEM_USER) { 5752 verbose(env, 5753 "%s is ptr_%s access user memory: off=%d\n", 5754 reg_arg_name(env, argno), tname, off); 5755 return -EACCES; 5756 } 5757 5758 if (reg->type & MEM_PERCPU) { 5759 verbose(env, 5760 "%s is ptr_%s access percpu memory: off=%d\n", 5761 reg_arg_name(env, argno), tname, off); 5762 return -EACCES; 5763 } 5764 5765 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 5766 if (!btf_is_kernel(reg->btf)) { 5767 verifier_bug(env, "reg->btf must be kernel btf"); 5768 return -EFAULT; 5769 } 5770 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 5771 } else { 5772 /* Writes are permitted with default btf_struct_access for 5773 * program allocated objects (which always have id > 0), 5774 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 5775 */ 5776 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 5777 verbose(env, "only read is supported\n"); 5778 return -EACCES; 5779 } 5780 5781 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 5782 !(reg->type & MEM_RCU) && !reg_is_referenced(env, reg)) { 5783 verifier_bug(env, "allocated object must have a referenced id"); 5784 return -EFAULT; 5785 } 5786 5787 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 5788 } 5789 5790 if (ret < 0) 5791 return ret; 5792 5793 if (ret != PTR_TO_BTF_ID) { 5794 /* just mark; */ 5795 5796 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 5797 /* If this is an untrusted pointer, all pointers formed by walking it 5798 * also inherit the untrusted flag. 5799 */ 5800 flag = PTR_UNTRUSTED; 5801 5802 } else if (is_trusted_reg(env, reg) || is_rcu_reg(reg)) { 5803 /* By default any pointer obtained from walking a trusted pointer is no 5804 * longer trusted, unless the field being accessed has explicitly been 5805 * marked as inheriting its parent's state of trust (either full or RCU). 5806 * For example: 5807 * 'cgroups' pointer is untrusted if task->cgroups dereference 5808 * happened in a sleepable program outside of bpf_rcu_read_lock() 5809 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 5810 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 5811 * 5812 * A regular RCU-protected pointer with __rcu tag can also be deemed 5813 * trusted if we are in an RCU CS. Such pointer can be NULL. 5814 */ 5815 if (type_is_trusted(env, reg, field_name, btf_id)) { 5816 flag |= PTR_TRUSTED; 5817 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 5818 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 5819 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 5820 if (type_is_rcu(env, reg, field_name, btf_id)) { 5821 /* ignore __rcu tag and mark it MEM_RCU */ 5822 flag |= MEM_RCU; 5823 } else if (flag & MEM_RCU || 5824 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 5825 /* __rcu tagged pointers can be NULL */ 5826 flag |= MEM_RCU | PTR_MAYBE_NULL; 5827 5828 /* We always trust them */ 5829 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 5830 flag & PTR_UNTRUSTED) 5831 flag &= ~PTR_UNTRUSTED; 5832 } else if (flag & (MEM_PERCPU | MEM_USER)) { 5833 /* keep as-is */ 5834 } else { 5835 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 5836 clear_trusted_flags(&flag); 5837 } 5838 } else { 5839 /* 5840 * If not in RCU CS or MEM_RCU pointer can be NULL then 5841 * aggressively mark as untrusted otherwise such 5842 * pointers will be plain PTR_TO_BTF_ID without flags 5843 * and will be allowed to be passed into helpers for 5844 * compat reasons. 5845 */ 5846 flag = PTR_UNTRUSTED; 5847 } 5848 } else { 5849 /* Old compat. Deprecated */ 5850 clear_trusted_flags(&flag); 5851 } 5852 5853 if (atype == BPF_READ && value_regno >= 0) { 5854 ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5855 if (ret < 0) 5856 return ret; 5857 } 5858 5859 return 0; 5860 } 5861 5862 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5863 struct bpf_reg_state *regs, struct bpf_reg_state *reg, 5864 argno_t argno, int off, int size, 5865 enum bpf_access_type atype, 5866 int value_regno) 5867 { 5868 struct bpf_map *map = reg->map_ptr; 5869 struct bpf_reg_state map_reg; 5870 enum bpf_type_flag flag = 0; 5871 const struct btf_type *t; 5872 const char *tname; 5873 u32 btf_id; 5874 int ret; 5875 5876 if (!btf_vmlinux) { 5877 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5878 return -ENOTSUPP; 5879 } 5880 5881 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5882 verbose(env, "map_ptr access not supported for map type %d\n", 5883 map->map_type); 5884 return -ENOTSUPP; 5885 } 5886 5887 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5888 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5889 5890 if (!env->allow_ptr_leaks) { 5891 verbose(env, 5892 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5893 tname); 5894 return -EPERM; 5895 } 5896 5897 if (off < 0) { 5898 verbose(env, "%s is %s invalid negative access: off=%d\n", 5899 reg_arg_name(env, argno), tname, off); 5900 return -EACCES; 5901 } 5902 5903 if (atype != BPF_READ) { 5904 verbose(env, "only read from %s is supported\n", tname); 5905 return -EACCES; 5906 } 5907 5908 /* Simulate access to a PTR_TO_BTF_ID */ 5909 memset(&map_reg, 0, sizeof(map_reg)); 5910 ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, 5911 btf_vmlinux, *map->ops->map_btf_id, 0); 5912 if (ret < 0) 5913 return ret; 5914 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 5915 if (ret < 0) 5916 return ret; 5917 5918 if (value_regno >= 0) { 5919 ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 5920 if (ret < 0) 5921 return ret; 5922 } 5923 5924 return 0; 5925 } 5926 5927 /* Check that the stack access at the given offset is within bounds. The 5928 * maximum valid offset is -1. 5929 * 5930 * The minimum valid offset is -MAX_BPF_STACK for writes, and 5931 * -state->allocated_stack for reads. 5932 */ 5933 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 5934 s64 off, 5935 struct bpf_func_state *state, 5936 enum bpf_access_type t) 5937 { 5938 int min_valid_off; 5939 5940 if (t == BPF_WRITE || env->allow_uninit_stack) 5941 min_valid_off = -MAX_BPF_STACK; 5942 else 5943 min_valid_off = -state->allocated_stack; 5944 5945 if (off < min_valid_off || off > -1) 5946 return -EACCES; 5947 return 0; 5948 } 5949 5950 /* Check that the stack access at 'regno + off' falls within the maximum stack 5951 * bounds. 5952 * 5953 * 'off' includes `regno->offset`, but not its dynamic part (if any). 5954 */ 5955 static int check_stack_access_within_bounds( 5956 struct bpf_verifier_env *env, struct bpf_reg_state *reg, 5957 argno_t argno, int off, int access_size, 5958 enum bpf_access_type type) 5959 { 5960 struct bpf_func_state *state = bpf_func(env, reg); 5961 s64 min_off, max_off; 5962 int err; 5963 char *err_extra; 5964 5965 if (type == BPF_READ) 5966 err_extra = " read from"; 5967 else 5968 err_extra = " write to"; 5969 5970 if (tnum_is_const(reg->var_off)) { 5971 min_off = (s64)reg->var_off.value + off; 5972 max_off = min_off + access_size; 5973 } else { 5974 if (reg_smax(reg) >= BPF_MAX_VAR_OFF || 5975 reg_smin(reg) <= -BPF_MAX_VAR_OFF) { 5976 verbose(env, "invalid unbounded variable-offset%s stack %s\n", 5977 err_extra, reg_arg_name(env, argno)); 5978 return -EACCES; 5979 } 5980 min_off = reg_smin(reg) + off; 5981 max_off = reg_smax(reg) + off + access_size; 5982 } 5983 5984 err = check_stack_slot_within_bounds(env, min_off, state, type); 5985 if (!err && max_off > 0) 5986 err = -EINVAL; /* out of stack access into non-negative offsets */ 5987 if (!err && access_size < 0) 5988 /* access_size should not be negative (or overflow an int); others checks 5989 * along the way should have prevented such an access. 5990 */ 5991 err = -EFAULT; /* invalid negative access size; integer overflow? */ 5992 5993 if (err) { 5994 if (tnum_is_const(reg->var_off)) { 5995 verbose(env, "invalid%s stack %s off=%lld size=%d\n", 5996 err_extra, reg_arg_name(env, argno), min_off, access_size); 5997 } else { 5998 char tn_buf[48]; 5999 6000 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6001 verbose(env, "invalid variable-offset%s stack %s var_off=%s off=%d size=%d\n", 6002 err_extra, reg_arg_name(env, argno), tn_buf, off, access_size); 6003 } 6004 return err; 6005 } 6006 6007 /* Note that there is no stack access with offset zero, so the needed stack 6008 * size is -min_off, not -min_off+1. 6009 */ 6010 return grow_stack_state(env, state, -min_off /* size */); 6011 } 6012 6013 static bool get_func_retval_range(struct bpf_prog *prog, 6014 struct bpf_retval_range *range) 6015 { 6016 if (prog->type == BPF_PROG_TYPE_LSM && 6017 prog->expected_attach_type == BPF_LSM_MAC && 6018 !bpf_lsm_get_retval_range(prog, range)) { 6019 return true; 6020 } 6021 return false; 6022 } 6023 6024 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val) 6025 { 6026 struct bpf_reg_state fake_reg; 6027 6028 if (!val) 6029 return; 6030 6031 fake_reg.type = SCALAR_VALUE; 6032 __mark_reg_known(&fake_reg, val); 6033 6034 scalar32_min_max_add(dst_reg, &fake_reg); 6035 scalar_min_max_add(dst_reg, &fake_reg); 6036 dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off); 6037 6038 reg_bounds_sync(dst_reg); 6039 } 6040 6041 /* check whether memory at (regno + off) is accessible for t = (read | write) 6042 * if t==write, value_regno is a register which value is stored into memory 6043 * if t==read, value_regno is a register which will receive the value from memory 6044 * if t==write && value_regno==-1, some unknown value is stored into memory 6045 * if t==read && value_regno==-1, don't care what we read from memory 6046 */ 6047 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, struct bpf_reg_state *reg, argno_t argno, 6048 int off, int bpf_size, enum bpf_access_type t, 6049 int value_regno, bool strict_alignment_once, bool is_ldsx) 6050 { 6051 struct bpf_reg_state *regs = cur_regs(env); 6052 int size, err = 0; 6053 6054 size = bpf_size_to_bytes(bpf_size); 6055 if (size < 0) 6056 return size; 6057 6058 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6059 if (err) 6060 return err; 6061 6062 if (reg->type == PTR_TO_MAP_KEY) { 6063 if (t == BPF_WRITE) { 6064 verbose(env, "write to change key %s not allowed\n", 6065 reg_arg_name(env, argno)); 6066 return -EACCES; 6067 } 6068 6069 err = check_mem_region_access(env, reg, argno, off, size, 6070 reg->map_ptr->key_size, false); 6071 if (err) 6072 return err; 6073 if (value_regno >= 0) 6074 mark_reg_unknown(env, regs, value_regno); 6075 } else if (reg->type == PTR_TO_MAP_VALUE) { 6076 struct btf_field *kptr_field = NULL; 6077 6078 if (t == BPF_WRITE && value_regno >= 0 && 6079 is_pointer_value(env, value_regno)) { 6080 verbose(env, "R%d leaks addr into map\n", value_regno); 6081 return -EACCES; 6082 } 6083 err = check_map_access_type(env, reg, off, size, t); 6084 if (err) 6085 return err; 6086 err = check_map_access(env, reg, argno, off, size, false, ACCESS_DIRECT); 6087 if (err) 6088 return err; 6089 if (tnum_is_const(reg->var_off)) 6090 kptr_field = btf_record_find(reg->map_ptr->record, 6091 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 6092 if (kptr_field) { 6093 err = check_map_kptr_access(env, value_regno, insn_idx, kptr_field); 6094 } else if (t == BPF_READ && value_regno >= 0) { 6095 struct bpf_map *map = reg->map_ptr; 6096 6097 /* 6098 * If map is read-only, track its contents as scalars, 6099 * unless it is an insn array (see the special case below) 6100 */ 6101 if (tnum_is_const(reg->var_off) && 6102 bpf_map_is_rdonly(map) && 6103 map->ops->map_direct_value_addr && 6104 map->map_type != BPF_MAP_TYPE_INSN_ARRAY) { 6105 int map_off = off + reg->var_off.value; 6106 u64 val = 0; 6107 6108 err = bpf_map_direct_read(map, map_off, size, 6109 &val, is_ldsx); 6110 if (err) 6111 return err; 6112 6113 regs[value_regno].type = SCALAR_VALUE; 6114 __mark_reg_known(®s[value_regno], val); 6115 } else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 6116 if (bpf_size != BPF_DW) { 6117 verbose(env, "Invalid read of %d bytes from insn_array\n", 6118 size); 6119 return -EACCES; 6120 } 6121 regs[value_regno] = *reg; 6122 add_scalar_to_reg(®s[value_regno], off); 6123 regs[value_regno].type = PTR_TO_INSN; 6124 } else { 6125 mark_reg_unknown(env, regs, value_regno); 6126 } 6127 } 6128 } else if (base_type(reg->type) == PTR_TO_MEM) { 6129 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6130 bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED); 6131 6132 if (type_may_be_null(reg->type)) { 6133 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6134 reg_type_str(env, reg->type)); 6135 return -EACCES; 6136 } 6137 6138 if (t == BPF_WRITE && rdonly_mem) { 6139 verbose(env, "%s cannot write into %s\n", 6140 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6141 return -EACCES; 6142 } 6143 6144 if (t == BPF_WRITE && value_regno >= 0 && 6145 is_pointer_value(env, value_regno)) { 6146 verbose(env, "R%d leaks addr into mem\n", value_regno); 6147 return -EACCES; 6148 } 6149 6150 /* 6151 * Accesses to untrusted PTR_TO_MEM are done through probe 6152 * instructions, hence no need to check bounds in that case. 6153 */ 6154 if (!rdonly_untrusted) 6155 err = check_mem_region_access(env, reg, argno, off, size, 6156 reg->mem_size, false); 6157 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6158 mark_reg_unknown(env, regs, value_regno); 6159 } else if (reg->type == PTR_TO_CTX) { 6160 struct bpf_insn_access_aux info = { 6161 .reg_type = SCALAR_VALUE, 6162 .is_ldsx = is_ldsx, 6163 .log = &env->log, 6164 }; 6165 struct bpf_retval_range range; 6166 6167 if (t == BPF_WRITE && value_regno >= 0 && 6168 is_pointer_value(env, value_regno)) { 6169 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6170 return -EACCES; 6171 } 6172 6173 err = check_ctx_access(env, insn_idx, reg, argno, off, size, t, &info); 6174 if (!err && t == BPF_READ && value_regno >= 0) { 6175 /* ctx access returns either a scalar, or a 6176 * PTR_TO_PACKET[_META,_END]. In the latter 6177 * case, we know the offset is zero. 6178 */ 6179 if (info.reg_type == SCALAR_VALUE) { 6180 if (info.is_retval && get_func_retval_range(env->prog, &range)) { 6181 err = __mark_reg_s32_range(env, regs, value_regno, 6182 range.minval, range.maxval); 6183 if (err) 6184 return err; 6185 } else { 6186 mark_reg_unknown(env, regs, value_regno); 6187 } 6188 } else { 6189 mark_reg_known_zero(env, regs, 6190 value_regno); 6191 /* A load of ctx field could have different 6192 * actual load size with the one encoded in the 6193 * insn. When the dst is PTR, it is for sure not 6194 * a sub-register. 6195 */ 6196 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6197 if (base_type(info.reg_type) == PTR_TO_BTF_ID) { 6198 regs[value_regno].btf = info.btf; 6199 regs[value_regno].btf_id = info.btf_id; 6200 regs[value_regno].id = info.ref_id; 6201 } 6202 if (type_may_be_null(info.reg_type) && !regs[value_regno].id) 6203 regs[value_regno].id = ++env->id_gen; 6204 } 6205 regs[value_regno].type = info.reg_type; 6206 } 6207 6208 } else if (reg->type == PTR_TO_STACK) { 6209 /* Basic bounds checks. */ 6210 err = check_stack_access_within_bounds(env, reg, argno, off, size, t); 6211 if (err) 6212 return err; 6213 6214 if (t == BPF_READ) 6215 err = check_stack_read(env, reg, argno, off, size, 6216 value_regno); 6217 else 6218 err = check_stack_write(env, reg, off, size, 6219 value_regno, insn_idx); 6220 } else if (reg_is_pkt_pointer(reg)) { 6221 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6222 verbose(env, "cannot write into packet\n"); 6223 return -EACCES; 6224 } 6225 if (t == BPF_WRITE && value_regno >= 0 && 6226 is_pointer_value(env, value_regno)) { 6227 verbose(env, "R%d leaks addr into packet\n", 6228 value_regno); 6229 return -EACCES; 6230 } 6231 err = check_packet_access(env, reg, argno, off, size, false); 6232 if (!err && t == BPF_READ && value_regno >= 0) 6233 mark_reg_unknown(env, regs, value_regno); 6234 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6235 if (t == BPF_WRITE && value_regno >= 0 && 6236 is_pointer_value(env, value_regno)) { 6237 verbose(env, "R%d leaks addr into flow keys\n", 6238 value_regno); 6239 return -EACCES; 6240 } 6241 6242 err = check_flow_keys_access(env, off, size); 6243 if (!err && t == BPF_READ && value_regno >= 0) 6244 mark_reg_unknown(env, regs, value_regno); 6245 } else if (type_is_sk_pointer(reg->type)) { 6246 if (t == BPF_WRITE) { 6247 verbose(env, "%s cannot write into %s\n", 6248 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6249 return -EACCES; 6250 } 6251 err = check_sock_access(env, insn_idx, reg, argno, off, size, t); 6252 if (!err && value_regno >= 0) 6253 mark_reg_unknown(env, regs, value_regno); 6254 } else if (reg->type == PTR_TO_TP_BUFFER) { 6255 err = check_tp_buffer_access(env, reg, argno, off, size); 6256 if (!err && t == BPF_READ && value_regno >= 0) 6257 mark_reg_unknown(env, regs, value_regno); 6258 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6259 !type_may_be_null(reg->type)) { 6260 err = check_ptr_to_btf_access(env, regs, reg, argno, off, size, t, 6261 value_regno); 6262 } else if (reg->type == CONST_PTR_TO_MAP) { 6263 err = check_ptr_to_map_access(env, regs, reg, argno, off, size, t, 6264 value_regno); 6265 } else if (base_type(reg->type) == PTR_TO_BUF && 6266 !type_may_be_null(reg->type)) { 6267 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6268 u32 *max_access; 6269 6270 if (rdonly_mem) { 6271 if (t == BPF_WRITE) { 6272 verbose(env, "%s cannot write into %s\n", 6273 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6274 return -EACCES; 6275 } 6276 max_access = &env->prog->aux->max_rdonly_access; 6277 } else { 6278 max_access = &env->prog->aux->max_rdwr_access; 6279 } 6280 6281 err = check_buffer_access(env, reg, argno, off, size, false, 6282 max_access); 6283 6284 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6285 mark_reg_unknown(env, regs, value_regno); 6286 } else if (reg->type == PTR_TO_ARENA) { 6287 if (t == BPF_READ && value_regno >= 0) 6288 mark_reg_unknown(env, regs, value_regno); 6289 } else { 6290 verbose(env, "%s invalid mem access '%s'\n", reg_arg_name(env, argno), 6291 reg_type_str(env, reg->type)); 6292 return -EACCES; 6293 } 6294 6295 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6296 regs[value_regno].type == SCALAR_VALUE) { 6297 if (!is_ldsx) 6298 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6299 coerce_reg_to_size(®s[value_regno], size); 6300 else 6301 coerce_reg_to_size_sx(®s[value_regno], size); 6302 } 6303 return err; 6304 } 6305 6306 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 6307 bool allow_trust_mismatch); 6308 6309 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn, 6310 bool strict_alignment_once, bool is_ldsx, 6311 bool allow_trust_mismatch, const char *ctx) 6312 { 6313 struct bpf_verifier_state *vstate = env->cur_state; 6314 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6315 struct bpf_reg_state *regs = cur_regs(env); 6316 enum bpf_reg_type src_reg_type; 6317 int err; 6318 6319 /* Handle stack arg read */ 6320 if (is_stack_arg_ldx(insn)) { 6321 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6322 if (err) 6323 return err; 6324 return check_stack_arg_read(env, state, insn->off, insn->dst_reg); 6325 } 6326 6327 /* check src operand */ 6328 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6329 if (err) 6330 return err; 6331 6332 /* check dst operand */ 6333 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6334 if (err) 6335 return err; 6336 6337 src_reg_type = regs[insn->src_reg].type; 6338 6339 /* Check if (src_reg + off) is readable. The state of dst_reg will be 6340 * updated by this call. 6341 */ 6342 err = check_mem_access(env, env->insn_idx, regs + insn->src_reg, argno_from_reg(insn->src_reg), insn->off, 6343 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg, 6344 strict_alignment_once, is_ldsx); 6345 err = err ?: save_aux_ptr_type(env, src_reg_type, 6346 allow_trust_mismatch); 6347 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx); 6348 6349 return err; 6350 } 6351 6352 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn, 6353 bool strict_alignment_once) 6354 { 6355 struct bpf_verifier_state *vstate = env->cur_state; 6356 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6357 struct bpf_reg_state *regs = cur_regs(env); 6358 enum bpf_reg_type dst_reg_type; 6359 int err; 6360 6361 /* Handle stack arg write */ 6362 if (is_stack_arg_stx(insn)) { 6363 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6364 if (err) 6365 return err; 6366 return check_stack_arg_write(env, state, insn->off, regs + insn->src_reg); 6367 } 6368 6369 /* check src1 operand */ 6370 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6371 if (err) 6372 return err; 6373 6374 /* check src2 operand */ 6375 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6376 if (err) 6377 return err; 6378 6379 dst_reg_type = regs[insn->dst_reg].type; 6380 6381 /* Check if (dst_reg + off) is writeable. */ 6382 err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6383 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg, 6384 strict_alignment_once, false); 6385 err = err ?: save_aux_ptr_type(env, dst_reg_type, false); 6386 6387 return err; 6388 } 6389 6390 static int check_atomic_rmw(struct bpf_verifier_env *env, 6391 struct bpf_insn *insn) 6392 { 6393 struct bpf_reg_state *dst_reg; 6394 int load_reg; 6395 int err; 6396 6397 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6398 verbose(env, "invalid atomic operand size\n"); 6399 return -EINVAL; 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 if (insn->imm == BPF_CMPXCHG) { 6413 /* Check comparison of R0 with memory location */ 6414 const u32 aux_reg = BPF_REG_0; 6415 6416 err = check_reg_arg(env, aux_reg, SRC_OP); 6417 if (err) 6418 return err; 6419 6420 if (is_pointer_value(env, aux_reg)) { 6421 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6422 return -EACCES; 6423 } 6424 } 6425 6426 if (is_pointer_value(env, insn->src_reg)) { 6427 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6428 return -EACCES; 6429 } 6430 6431 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6432 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6433 insn->dst_reg, 6434 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6435 return -EACCES; 6436 } 6437 6438 if (insn->imm & BPF_FETCH) { 6439 if (insn->imm == BPF_CMPXCHG) 6440 load_reg = BPF_REG_0; 6441 else 6442 load_reg = insn->src_reg; 6443 6444 /* check and record load of old value */ 6445 err = check_reg_arg(env, load_reg, DST_OP); 6446 if (err) 6447 return err; 6448 } else { 6449 /* This instruction accesses a memory location but doesn't 6450 * actually load it into a register. 6451 */ 6452 load_reg = -1; 6453 } 6454 6455 dst_reg = cur_regs(env) + insn->dst_reg; 6456 6457 /* Check whether we can read the memory, with second call for fetch 6458 * case to simulate the register fill. 6459 */ 6460 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6461 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6462 if (!err && load_reg >= 0) 6463 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), 6464 insn->off, BPF_SIZE(insn->code), 6465 BPF_READ, load_reg, true, false); 6466 if (err) 6467 return err; 6468 6469 if (is_arena_reg(env, insn->dst_reg)) { 6470 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 6471 if (err) 6472 return err; 6473 } 6474 /* Check whether we can write into the same memory. */ 6475 err = check_mem_access(env, env->insn_idx, dst_reg, argno_from_reg(insn->dst_reg), insn->off, 6476 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6477 if (err) 6478 return err; 6479 return 0; 6480 } 6481 6482 static int check_atomic_load(struct bpf_verifier_env *env, 6483 struct bpf_insn *insn) 6484 { 6485 int err; 6486 6487 err = check_load_mem(env, insn, true, false, false, "atomic_load"); 6488 if (err) 6489 return err; 6490 6491 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) { 6492 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n", 6493 insn->src_reg, 6494 reg_type_str(env, reg_state(env, insn->src_reg)->type)); 6495 return -EACCES; 6496 } 6497 6498 return 0; 6499 } 6500 6501 static int check_atomic_store(struct bpf_verifier_env *env, 6502 struct bpf_insn *insn) 6503 { 6504 int err; 6505 6506 err = check_store_reg(env, insn, true); 6507 if (err) 6508 return err; 6509 6510 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6511 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6512 insn->dst_reg, 6513 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6514 return -EACCES; 6515 } 6516 6517 return 0; 6518 } 6519 6520 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn) 6521 { 6522 switch (insn->imm) { 6523 case BPF_ADD: 6524 case BPF_ADD | BPF_FETCH: 6525 case BPF_AND: 6526 case BPF_AND | BPF_FETCH: 6527 case BPF_OR: 6528 case BPF_OR | BPF_FETCH: 6529 case BPF_XOR: 6530 case BPF_XOR | BPF_FETCH: 6531 case BPF_XCHG: 6532 case BPF_CMPXCHG: 6533 return check_atomic_rmw(env, insn); 6534 case BPF_LOAD_ACQ: 6535 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6536 verbose(env, 6537 "64-bit load-acquires are only supported on 64-bit arches\n"); 6538 return -EOPNOTSUPP; 6539 } 6540 return check_atomic_load(env, insn); 6541 case BPF_STORE_REL: 6542 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6543 verbose(env, 6544 "64-bit store-releases are only supported on 64-bit arches\n"); 6545 return -EOPNOTSUPP; 6546 } 6547 return check_atomic_store(env, insn); 6548 default: 6549 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", 6550 insn->imm); 6551 return -EINVAL; 6552 } 6553 } 6554 6555 /* When register 'regno' is used to read the stack (either directly or through 6556 * a helper function) make sure that it's within stack boundary and, depending 6557 * on the access type and privileges, that all elements of the stack are 6558 * initialized. 6559 * 6560 * All registers that have been spilled on the stack in the slots within the 6561 * read offsets are marked as read. 6562 */ 6563 static int check_stack_range_initialized( 6564 struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int off, 6565 int access_size, bool zero_size_allowed, 6566 enum bpf_access_type type, struct bpf_call_arg_meta *meta) 6567 { 6568 struct bpf_func_state *state = bpf_func(env, reg); 6569 int err, min_off, max_off, i, j, slot, spi; 6570 /* Some accesses can write anything into the stack, others are 6571 * read-only. 6572 */ 6573 bool clobber = type == BPF_WRITE; 6574 /* 6575 * Negative access_size signals global subprog/kfunc arg check where 6576 * STACK_POISON slots are acceptable. static stack liveness 6577 * might have determined that subprog doesn't read them, 6578 * but BTF based global subprog validation isn't accurate enough. 6579 */ 6580 bool allow_poison = access_size < 0 || clobber; 6581 6582 access_size = abs(access_size); 6583 6584 if (access_size == 0 && !zero_size_allowed) { 6585 verbose(env, "invalid zero-sized read\n"); 6586 return -EACCES; 6587 } 6588 6589 err = check_stack_access_within_bounds(env, reg, argno, off, access_size, type); 6590 if (err) 6591 return err; 6592 6593 6594 if (tnum_is_const(reg->var_off)) { 6595 min_off = max_off = reg->var_off.value + off; 6596 } else { 6597 /* Variable offset is prohibited for unprivileged mode for 6598 * simplicity since it requires corresponding support in 6599 * Spectre masking for stack ALU. 6600 * See also retrieve_ptr_limit(). 6601 */ 6602 if (!env->bypass_spec_v1) { 6603 char tn_buf[48]; 6604 6605 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6606 verbose(env, "%s variable offset stack access prohibited for !root, var_off=%s\n", 6607 reg_arg_name(env, argno), tn_buf); 6608 return -EACCES; 6609 } 6610 /* Only initialized buffer on stack is allowed to be accessed 6611 * with variable offset. With uninitialized buffer it's hard to 6612 * guarantee that whole memory is marked as initialized on 6613 * helper return since specific bounds are unknown what may 6614 * cause uninitialized stack leaking. 6615 */ 6616 if (meta && meta->raw_mode) 6617 meta = NULL; 6618 6619 min_off = reg_smin(reg) + off; 6620 max_off = reg_smax(reg) + off; 6621 } 6622 6623 if (meta && meta->raw_mode) { 6624 /* Ensure we won't be overwriting dynptrs when simulating byte 6625 * by byte access in check_helper_call using meta.access_size. 6626 * This would be a problem if we have a helper in the future 6627 * which takes: 6628 * 6629 * helper(uninit_mem, len, dynptr) 6630 * 6631 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 6632 * may end up writing to dynptr itself when touching memory from 6633 * arg 1. This can be relaxed on a case by case basis for known 6634 * safe cases, but reject due to the possibilitiy of aliasing by 6635 * default. 6636 */ 6637 for (i = min_off; i < max_off + access_size; i++) { 6638 int stack_off = -i - 1; 6639 6640 spi = bpf_get_spi(i); 6641 /* raw_mode may write past allocated_stack */ 6642 if (state->allocated_stack <= stack_off) 6643 continue; 6644 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 6645 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 6646 return -EACCES; 6647 } 6648 } 6649 meta->access_size = access_size; 6650 meta->regno = reg_from_argno(argno); 6651 return 0; 6652 } 6653 6654 for (i = min_off; i < max_off + access_size; i++) { 6655 u8 *stype; 6656 6657 slot = -i - 1; 6658 spi = slot / BPF_REG_SIZE; 6659 if (state->allocated_stack <= slot) { 6660 verbose(env, "allocated_stack too small\n"); 6661 return -EFAULT; 6662 } 6663 6664 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 6665 if (*stype == STACK_MISC) 6666 goto mark; 6667 if ((*stype == STACK_ZERO) || 6668 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 6669 if (clobber) { 6670 /* helper can write anything into the stack */ 6671 *stype = STACK_MISC; 6672 } 6673 goto mark; 6674 } 6675 6676 if (bpf_is_spilled_reg(&state->stack[spi]) && 6677 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 6678 env->allow_ptr_leaks)) { 6679 if (clobber) { 6680 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 6681 for (j = 0; j < BPF_REG_SIZE; j++) 6682 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 6683 } 6684 goto mark; 6685 } 6686 6687 if (*stype == STACK_POISON) { 6688 if (allow_poison) 6689 goto mark; 6690 verbose(env, "reading from stack %s off %d+%d size %d, slot poisoned by dead code elimination\n", 6691 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6692 } else if (tnum_is_const(reg->var_off)) { 6693 verbose(env, "invalid read from stack %s off %d+%d size %d\n", 6694 reg_arg_name(env, argno), min_off, i - min_off, access_size); 6695 } else { 6696 char tn_buf[48]; 6697 6698 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6699 verbose(env, "invalid read from stack %s var_off %s+%d size %d\n", 6700 reg_arg_name(env, argno), tn_buf, i - min_off, access_size); 6701 } 6702 return -EACCES; 6703 mark: 6704 ; 6705 } 6706 return 0; 6707 } 6708 6709 static int check_helper_mem_access(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 6710 int access_size, enum bpf_access_type access_type, 6711 bool zero_size_allowed, 6712 struct bpf_call_arg_meta *meta) 6713 { 6714 struct bpf_reg_state *regs = cur_regs(env); 6715 u32 *max_access; 6716 6717 switch (base_type(reg->type)) { 6718 case PTR_TO_PACKET: 6719 case PTR_TO_PACKET_META: 6720 return check_packet_access(env, reg, argno, 0, access_size, 6721 zero_size_allowed); 6722 case PTR_TO_MAP_KEY: 6723 if (access_type == BPF_WRITE) { 6724 verbose(env, "%s cannot write into %s\n", 6725 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6726 return -EACCES; 6727 } 6728 return check_mem_region_access(env, reg, argno, 0, access_size, 6729 reg->map_ptr->key_size, false); 6730 case PTR_TO_MAP_VALUE: 6731 if (check_map_access_type(env, reg, 0, access_size, access_type)) 6732 return -EACCES; 6733 return check_map_access(env, reg, argno, 0, access_size, 6734 zero_size_allowed, ACCESS_HELPER); 6735 case PTR_TO_MEM: 6736 if (type_is_rdonly_mem(reg->type)) { 6737 if (access_type == BPF_WRITE) { 6738 verbose(env, "%s cannot write into %s\n", 6739 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6740 return -EACCES; 6741 } 6742 } 6743 return check_mem_region_access(env, reg, argno, 0, 6744 access_size, reg->mem_size, 6745 zero_size_allowed); 6746 case PTR_TO_BUF: 6747 if (type_is_rdonly_mem(reg->type)) { 6748 if (access_type == BPF_WRITE) { 6749 verbose(env, "%s cannot write into %s\n", 6750 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 6751 return -EACCES; 6752 } 6753 6754 max_access = &env->prog->aux->max_rdonly_access; 6755 } else { 6756 max_access = &env->prog->aux->max_rdwr_access; 6757 } 6758 return check_buffer_access(env, reg, argno, 0, 6759 access_size, zero_size_allowed, 6760 max_access); 6761 case PTR_TO_STACK: 6762 return check_stack_range_initialized( 6763 env, reg, 6764 argno, 0, access_size, 6765 zero_size_allowed, access_type, meta); 6766 case PTR_TO_BTF_ID: 6767 return check_ptr_to_btf_access(env, regs, reg, argno, 0, 6768 access_size, BPF_READ, -1); 6769 case PTR_TO_CTX: 6770 /* Only permit reading or writing syscall context using helper calls. */ 6771 if (is_var_ctx_off_allowed(env->prog)) { 6772 int err = check_mem_region_access(env, reg, argno, 0, access_size, U16_MAX, 6773 zero_size_allowed); 6774 if (err) 6775 return err; 6776 if (env->prog->aux->max_ctx_offset < reg_umax(reg) + access_size) 6777 env->prog->aux->max_ctx_offset = reg_umax(reg) + access_size; 6778 return 0; 6779 } 6780 fallthrough; 6781 default: /* scalar_value or invalid ptr */ 6782 /* Allow zero-byte read from NULL, regardless of pointer type */ 6783 if (zero_size_allowed && access_size == 0 && 6784 bpf_register_is_null(reg)) 6785 return 0; 6786 6787 verbose(env, "%s type=%s ", reg_arg_name(env, argno), 6788 reg_type_str(env, reg->type)); 6789 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 6790 return -EACCES; 6791 } 6792 } 6793 6794 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 6795 * size. 6796 * 6797 * @mem_reg contains the pointer, @size_reg contains the access size. 6798 */ 6799 static int check_mem_size_reg(struct bpf_verifier_env *env, 6800 struct bpf_reg_state *mem_reg, 6801 struct bpf_reg_state *size_reg, argno_t mem_argno, 6802 argno_t size_argno, enum bpf_access_type access_type, 6803 bool zero_size_allowed, 6804 struct bpf_call_arg_meta *meta) 6805 { 6806 int err; 6807 6808 /* This is used to refine r0 return value bounds for helpers 6809 * that enforce this value as an upper bound on return values. 6810 * See do_refine_retval_range() for helpers that can refine 6811 * the return value. C type of helper is u32 so we pull register 6812 * bound from umax_value however, if negative verifier errors 6813 * out. Only upper bounds can be learned because retval is an 6814 * int type and negative retvals are allowed. 6815 */ 6816 meta->msize_max_value = reg_umax(size_reg); 6817 6818 /* The register is SCALAR_VALUE; the access check happens using 6819 * its boundaries. For unprivileged variable accesses, disable 6820 * raw mode so that the program is required to initialize all 6821 * the memory that the helper could just partially fill up. 6822 */ 6823 if (!tnum_is_const(size_reg->var_off)) 6824 meta = NULL; 6825 6826 if (reg_smin(size_reg) < 0) { 6827 verbose(env, "%s min value is negative, either use unsigned or 'var &= const'\n", 6828 reg_arg_name(env, size_argno)); 6829 return -EACCES; 6830 } 6831 6832 if (reg_umin(size_reg) == 0 && !zero_size_allowed) { 6833 verbose(env, "%s invalid zero-sized read: u64=[%lld,%lld]\n", 6834 reg_arg_name(env, size_argno), reg_umin(size_reg), reg_umax(size_reg)); 6835 return -EACCES; 6836 } 6837 6838 if (reg_umax(size_reg) >= BPF_MAX_VAR_SIZ) { 6839 verbose(env, "%s unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 6840 reg_arg_name(env, size_argno)); 6841 return -EACCES; 6842 } 6843 err = check_helper_mem_access(env, mem_reg, mem_argno, reg_umax(size_reg), 6844 access_type, zero_size_allowed, meta); 6845 if (!err) { 6846 int regno = reg_from_argno(size_argno); 6847 6848 if (regno >= 0) 6849 err = mark_chain_precision(env, regno); 6850 else 6851 err = mark_stack_arg_precision(env, arg_idx_from_argno(size_argno)); 6852 } 6853 return err; 6854 } 6855 6856 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6857 argno_t argno, u32 mem_size) 6858 { 6859 bool may_be_null = type_may_be_null(reg->type); 6860 struct bpf_reg_state saved_reg; 6861 int err; 6862 6863 if (bpf_register_is_null(reg)) 6864 return 0; 6865 6866 if (mem_size > S32_MAX) { 6867 verbose(env, "%s memory size %u is too large\n", 6868 reg_arg_name(env, argno), mem_size); 6869 return -EACCES; 6870 } 6871 6872 /* Assuming that the register contains a value check if the memory 6873 * access is safe. Temporarily save and restore the register's state as 6874 * the conversion shouldn't be visible to a caller. 6875 */ 6876 if (may_be_null) { 6877 saved_reg = *reg; 6878 mark_ptr_not_null_reg(reg); 6879 } 6880 6881 int size = base_type(reg->type) == PTR_TO_STACK ? -(int)mem_size : mem_size; 6882 6883 err = check_helper_mem_access(env, reg, argno, size, BPF_READ, true, NULL); 6884 err = err ?: check_helper_mem_access(env, reg, argno, size, BPF_WRITE, true, NULL); 6885 6886 if (may_be_null) 6887 *reg = saved_reg; 6888 6889 return err; 6890 } 6891 6892 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *mem_reg, 6893 struct bpf_reg_state *size_reg, argno_t mem_argno, argno_t size_argno) 6894 { 6895 bool may_be_null = type_may_be_null(mem_reg->type); 6896 struct bpf_reg_state saved_reg; 6897 struct bpf_call_arg_meta meta; 6898 int err; 6899 6900 memset(&meta, 0, sizeof(meta)); 6901 6902 if (may_be_null) { 6903 saved_reg = *mem_reg; 6904 mark_ptr_not_null_reg(mem_reg); 6905 } 6906 6907 err = check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_READ, true, &meta); 6908 err = err ?: check_mem_size_reg(env, mem_reg, size_reg, mem_argno, size_argno, BPF_WRITE, true, &meta); 6909 6910 if (may_be_null) 6911 *mem_reg = saved_reg; 6912 6913 return err; 6914 } 6915 6916 enum { 6917 PROCESS_SPIN_LOCK = (1 << 0), 6918 PROCESS_RES_LOCK = (1 << 1), 6919 PROCESS_LOCK_IRQ = (1 << 2), 6920 }; 6921 6922 /* Implementation details: 6923 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 6924 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 6925 * Two bpf_map_lookups (even with the same key) will have different reg->id. 6926 * Two separate bpf_obj_new will also have different reg->id. 6927 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 6928 * clears reg->id after value_or_null->value transition, since the verifier only 6929 * cares about the range of access to valid map value pointer and doesn't care 6930 * about actual address of the map element. 6931 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 6932 * reg->id > 0 after value_or_null->value transition. By doing so 6933 * two bpf_map_lookups will be considered two different pointers that 6934 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 6935 * returned from bpf_obj_new. 6936 * The verifier allows taking only one bpf_spin_lock at a time to avoid 6937 * dead-locks. 6938 * Since only one bpf_spin_lock is allowed the checks are simpler than 6939 * reg_is_refcounted() logic. The verifier needs to remember only 6940 * one spin_lock instead of array of acquired_refs. 6941 * env->cur_state->active_locks remembers which map value element or allocated 6942 * object got locked and clears it after bpf_spin_unlock. 6943 */ 6944 static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int flags) 6945 { 6946 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK; 6947 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin"; 6948 struct bpf_verifier_state *cur = env->cur_state; 6949 bool is_const = tnum_is_const(reg->var_off); 6950 bool is_irq = flags & PROCESS_LOCK_IRQ; 6951 u64 val = reg->var_off.value; 6952 struct bpf_map *map = NULL; 6953 struct btf *btf = NULL; 6954 struct btf_record *rec; 6955 u32 spin_lock_off; 6956 int err; 6957 6958 if (!is_const) { 6959 verbose(env, 6960 "%s doesn't have constant offset. %s_lock has to be at the constant offset\n", 6961 reg_arg_name(env, argno), lock_str); 6962 return -EINVAL; 6963 } 6964 if (reg->type == PTR_TO_MAP_VALUE) { 6965 map = reg->map_ptr; 6966 if (!map->btf) { 6967 verbose(env, 6968 "map '%s' has to have BTF in order to use %s_lock\n", 6969 map->name, lock_str); 6970 return -EINVAL; 6971 } 6972 } else { 6973 btf = reg->btf; 6974 } 6975 6976 rec = reg_btf_record(reg); 6977 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) { 6978 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local", 6979 map ? map->name : "kptr", lock_str); 6980 return -EINVAL; 6981 } 6982 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off; 6983 if (spin_lock_off != val) { 6984 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n", 6985 val, lock_str, spin_lock_off); 6986 return -EINVAL; 6987 } 6988 if (is_lock) { 6989 void *ptr; 6990 int type; 6991 6992 if (map) 6993 ptr = map; 6994 else 6995 ptr = btf; 6996 6997 if (!is_res_lock && cur->active_locks) { 6998 if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) { 6999 verbose(env, 7000 "Locking two bpf_spin_locks are not allowed\n"); 7001 return -EINVAL; 7002 } 7003 } else if (is_res_lock && cur->active_locks) { 7004 if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) { 7005 verbose(env, "Acquiring the same lock again, AA deadlock detected\n"); 7006 return -EINVAL; 7007 } 7008 } 7009 7010 if (is_res_lock && is_irq) 7011 type = REF_TYPE_RES_LOCK_IRQ; 7012 else if (is_res_lock) 7013 type = REF_TYPE_RES_LOCK; 7014 else 7015 type = REF_TYPE_LOCK; 7016 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr); 7017 if (err < 0) { 7018 verbose(env, "Failed to acquire lock state\n"); 7019 return err; 7020 } 7021 } else { 7022 void *ptr; 7023 int type; 7024 7025 if (map) 7026 ptr = map; 7027 else 7028 ptr = btf; 7029 7030 if (!cur->active_locks) { 7031 verbose(env, "%s_unlock without taking a lock\n", lock_str); 7032 return -EINVAL; 7033 } 7034 7035 if (is_res_lock && is_irq) 7036 type = REF_TYPE_RES_LOCK_IRQ; 7037 else if (is_res_lock) 7038 type = REF_TYPE_RES_LOCK; 7039 else 7040 type = REF_TYPE_LOCK; 7041 if (!find_lock_state(cur, type, reg->id, ptr)) { 7042 verbose(env, "%s_unlock of different lock\n", lock_str); 7043 return -EINVAL; 7044 } 7045 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) { 7046 verbose(env, "%s_unlock cannot be out of order\n", lock_str); 7047 return -EINVAL; 7048 } 7049 if (release_lock_state(cur, type, reg->id, ptr)) { 7050 verbose(env, "%s_unlock of different lock\n", lock_str); 7051 return -EINVAL; 7052 } 7053 7054 invalidate_non_owning_refs(env); 7055 } 7056 return 0; 7057 } 7058 7059 /* Check if @regno is a pointer to a specific field in a map value */ 7060 static int check_map_field_pointer(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7061 enum btf_field_type field_type, 7062 struct bpf_map_desc *map_desc) 7063 { 7064 bool is_const = tnum_is_const(reg->var_off); 7065 struct bpf_map *map = reg->map_ptr; 7066 u64 val = reg->var_off.value; 7067 const char *struct_name = btf_field_type_name(field_type); 7068 int field_off = -1; 7069 7070 if (!is_const) { 7071 verbose(env, 7072 "%s doesn't have constant offset. %s has to be at the constant offset\n", 7073 reg_arg_name(env, argno), struct_name); 7074 return -EINVAL; 7075 } 7076 if (!map->btf) { 7077 verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name, 7078 struct_name); 7079 return -EINVAL; 7080 } 7081 if (!btf_record_has_field(map->record, field_type)) { 7082 verbose(env, "map '%s' has no valid %s\n", map->name, struct_name); 7083 return -EINVAL; 7084 } 7085 switch (field_type) { 7086 case BPF_TIMER: 7087 field_off = map->record->timer_off; 7088 break; 7089 case BPF_TASK_WORK: 7090 field_off = map->record->task_work_off; 7091 break; 7092 case BPF_WORKQUEUE: 7093 field_off = map->record->wq_off; 7094 break; 7095 default: 7096 verifier_bug(env, "unsupported BTF field type: %s\n", struct_name); 7097 return -EINVAL; 7098 } 7099 if (field_off != val) { 7100 verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n", 7101 val, struct_name, field_off); 7102 return -EINVAL; 7103 } 7104 if (map_desc->ptr) { 7105 verifier_bug(env, "Two map pointers in a %s helper", struct_name); 7106 return -EFAULT; 7107 } 7108 map_desc->uid = reg->map_uid; 7109 map_desc->ptr = map; 7110 return 0; 7111 } 7112 7113 static int process_timer_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7114 struct bpf_map_desc *map) 7115 { 7116 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 7117 verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n"); 7118 return -EOPNOTSUPP; 7119 } 7120 return check_map_field_pointer(env, reg, argno, BPF_TIMER, map); 7121 } 7122 7123 static int process_timer_helper(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7124 struct bpf_call_arg_meta *meta) 7125 { 7126 return process_timer_func(env, reg, argno, &meta->map); 7127 } 7128 7129 static int process_timer_kfunc(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7130 struct bpf_kfunc_call_arg_meta *meta) 7131 { 7132 return process_timer_func(env, reg, argno, &meta->map); 7133 } 7134 7135 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7136 struct bpf_call_arg_meta *meta) 7137 { 7138 struct bpf_reg_state *reg = reg_state(env, regno); 7139 struct btf_field *kptr_field; 7140 struct bpf_map *map_ptr; 7141 struct btf_record *rec; 7142 u32 kptr_off; 7143 7144 if (type_is_ptr_alloc_obj(reg->type)) { 7145 rec = reg_btf_record(reg); 7146 } else { /* PTR_TO_MAP_VALUE */ 7147 map_ptr = reg->map_ptr; 7148 if (!map_ptr->btf) { 7149 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7150 map_ptr->name); 7151 return -EINVAL; 7152 } 7153 rec = map_ptr->record; 7154 meta->map.ptr = map_ptr; 7155 } 7156 7157 if (!tnum_is_const(reg->var_off)) { 7158 verbose(env, 7159 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7160 regno); 7161 return -EINVAL; 7162 } 7163 7164 if (!btf_record_has_field(rec, BPF_KPTR)) { 7165 verbose(env, "R%d has no valid kptr\n", regno); 7166 return -EINVAL; 7167 } 7168 7169 kptr_off = reg->var_off.value; 7170 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 7171 if (!kptr_field) { 7172 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7173 return -EACCES; 7174 } 7175 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7176 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7177 return -EACCES; 7178 } 7179 meta->kptr_field = kptr_field; 7180 return 0; 7181 } 7182 7183 /* 7184 * Validate dynptr arguments for helper, kfunc and subprog. 7185 * 7186 * @dynptr is both input and output. It is populated when the argument is 7187 * tagged with MEM_UNINIT (i.e., the dynptr argument that will be constructed) 7188 * and consumed when the argument is expecting to be an initialized dynptr. 7189 * @parent_id is used to track the referenced parent object (e.g., file or skb in 7190 * qdisc program) when constructing a dynptr. 7191 * 7192 * There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7193 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7194 * 7195 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7196 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7197 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7198 * 7199 * Mutability of bpf_dynptr is at two levels: the dynptr and the memory the 7200 * dynptr points to. At the first level, the verifier will make sure a 7201 * CONST_PTR_TO_DYNPTR cannot be reinitialized or destroyed. The mutability of 7202 * a dynptr's view (i.e., start and offset) is not tracked as there is not such 7203 * use case. The second level is tracked using the upper bit of bpf_dynptr->size 7204 * and checked dynamically during runtime. 7205 */ 7206 static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7207 argno_t argno, int insn_idx, enum bpf_arg_type arg_type, 7208 struct ref_obj_desc *ref_obj, struct bpf_dynptr_desc *dynptr) 7209 { 7210 int spi, err = 0; 7211 7212 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 7213 verbose(env, 7214 "%s expected pointer to stack or const struct bpf_dynptr\n", 7215 reg_arg_name(env, argno)); 7216 return -EINVAL; 7217 } 7218 7219 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7220 * constructing a mutable bpf_dynptr object. 7221 * 7222 * Currently, this is only possible with PTR_TO_STACK 7223 * pointing to a region of at least 16 bytes which doesn't 7224 * contain an existing bpf_dynptr. 7225 * 7226 * OBJ_RELEASE - Points to a initialized bpf_dynptr that will be 7227 * destroyed. 7228 * 7229 * None - Points to a initialized dynptr that cannot be 7230 * reinitialized or destroyed. However, the view of the 7231 * dynptr and the memory it points to may be mutated. 7232 */ 7233 if (arg_type & MEM_UNINIT) { 7234 int i; 7235 7236 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7237 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7238 return -EINVAL; 7239 } 7240 7241 /* we write BPF_DW bits (8 bytes) at a time */ 7242 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7243 err = check_mem_access(env, insn_idx, reg, argno, 7244 i, BPF_DW, BPF_WRITE, -1, false, false); 7245 if (err) 7246 return err; 7247 } 7248 7249 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, ref_obj, dynptr); 7250 } else /* OBJ_RELEASE and None case from above */ { 7251 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7252 if (reg->type == CONST_PTR_TO_DYNPTR && (arg_type & OBJ_RELEASE)) { 7253 verbose(env, "CONST_PTR_TO_DYNPTR cannot be released\n"); 7254 return -EINVAL; 7255 } 7256 7257 if (!is_dynptr_reg_valid_init(env, reg)) { 7258 verbose(env, "Expected an initialized dynptr as %s\n", 7259 reg_arg_name(env, argno)); 7260 return -EINVAL; 7261 } 7262 7263 /* Fold modifiers (in this case, OBJ_RELEASE) when checking expected type */ 7264 if (!is_dynptr_type_expected(env, reg, arg_type & ~OBJ_RELEASE)) { 7265 verbose(env, 7266 "Expected a dynptr of type %s as %s\n", 7267 dynptr_type_str(arg_to_dynptr_type(arg_type)), 7268 reg_arg_name(env, argno)); 7269 return -EINVAL; 7270 } 7271 7272 if (reg->type != CONST_PTR_TO_DYNPTR) { 7273 struct bpf_func_state *state = bpf_func(env, reg); 7274 7275 spi = dynptr_get_spi(env, reg); 7276 if (spi < 0) 7277 return spi; 7278 7279 /* 7280 * For CONST_PTR_TO_DYNPTR, reg is already scratched by check_reg_arg 7281 * in check_helper_call and mark_btf_func_reg_size in check_kfunc_call. 7282 */ 7283 mark_stack_slots_scratched(env, spi, BPF_DYNPTR_NR_SLOTS); 7284 7285 reg = &state->stack[spi].spilled_ptr; 7286 } 7287 7288 if (dynptr) { 7289 dynptr->type = reg->dynptr.type; 7290 dynptr->id = reg->id; 7291 dynptr->parent_id = reg->parent_id; 7292 } 7293 } 7294 return err; 7295 } 7296 7297 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7298 { 7299 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7300 } 7301 7302 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7303 { 7304 return meta->kfunc_flags & KF_ITER_NEW; 7305 } 7306 7307 7308 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7309 { 7310 return meta->kfunc_flags & KF_ITER_DESTROY; 7311 } 7312 7313 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 7314 const struct btf_param *arg) 7315 { 7316 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7317 * kfunc is iter state pointer 7318 */ 7319 if (is_iter_kfunc(meta)) 7320 return arg_idx == 0; 7321 7322 /* iter passed as an argument to a generic kfunc */ 7323 return btf_param_match_suffix(meta->btf, arg, "__iter"); 7324 } 7325 7326 static int process_iter_arg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, int insn_idx, 7327 struct bpf_kfunc_call_arg_meta *meta) 7328 { 7329 struct bpf_func_state *state = bpf_func(env, reg); 7330 const struct btf_type *t; 7331 u32 arg_idx = arg_idx_from_argno(argno); 7332 int spi, err, i, nr_slots, btf_id; 7333 7334 if (reg->type != PTR_TO_STACK) { 7335 verbose(env, "%s expected pointer to an iterator on stack\n", 7336 reg_arg_name(env, argno)); 7337 return -EINVAL; 7338 } 7339 7340 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 7341 * ensures struct convention, so we wouldn't need to do any BTF 7342 * validation here. But given iter state can be passed as a parameter 7343 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 7344 * conservative here. 7345 */ 7346 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, arg_idx); 7347 if (btf_id < 0) { 7348 verbose(env, "expected valid iter pointer as %s\n", 7349 reg_arg_name(env, argno)); 7350 return -EINVAL; 7351 } 7352 t = btf_type_by_id(meta->btf, btf_id); 7353 nr_slots = t->size / BPF_REG_SIZE; 7354 7355 if (is_iter_new_kfunc(meta)) { 7356 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7357 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7358 verbose(env, "expected uninitialized iter_%s as %s\n", 7359 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7360 return -EINVAL; 7361 } 7362 7363 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7364 err = check_mem_access(env, insn_idx, reg, argno, 7365 i, BPF_DW, BPF_WRITE, -1, false, false); 7366 if (err) 7367 return err; 7368 } 7369 7370 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7371 if (err) 7372 return err; 7373 } else { 7374 /* iter_next() or iter_destroy(), as well as any kfunc 7375 * accepting iter argument, expect initialized iter state 7376 */ 7377 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7378 switch (err) { 7379 case 0: 7380 break; 7381 case -EINVAL: 7382 verbose(env, "expected an initialized iter_%s as %s\n", 7383 iter_type_str(meta->btf, btf_id), reg_arg_name(env, argno)); 7384 return err; 7385 case -EPROTO: 7386 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7387 return err; 7388 default: 7389 return err; 7390 } 7391 7392 spi = iter_get_spi(env, reg, nr_slots); 7393 if (spi < 0) 7394 return spi; 7395 7396 mark_stack_slots_scratched(env, spi, nr_slots); 7397 7398 /* remember meta->iter info for process_iter_next_call() */ 7399 meta->iter.spi = spi; 7400 meta->iter.frameno = reg->frameno; 7401 update_ref_obj(&meta->ref_obj, &state->stack[spi].spilled_ptr); 7402 7403 if (is_iter_destroy_kfunc(meta)) { 7404 err = unmark_stack_slots_iter(env, reg, nr_slots); 7405 if (err) 7406 return err; 7407 } 7408 } 7409 7410 return 0; 7411 } 7412 7413 /* Look for a previous loop entry at insn_idx: nearest parent state 7414 * stopped at insn_idx with callsites matching those in cur->frame. 7415 */ 7416 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7417 struct bpf_verifier_state *cur, 7418 int insn_idx) 7419 { 7420 struct bpf_verifier_state_list *sl; 7421 struct bpf_verifier_state *st; 7422 struct list_head *pos, *head; 7423 7424 /* Explored states are pushed in stack order, most recent states come first */ 7425 head = bpf_explored_state(env, insn_idx); 7426 list_for_each(pos, head) { 7427 sl = container_of(pos, struct bpf_verifier_state_list, node); 7428 /* If st->branches != 0 state is a part of current DFS verification path, 7429 * hence cur & st for a loop. 7430 */ 7431 st = &sl->state; 7432 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7433 st->dfs_depth < cur->dfs_depth) 7434 return st; 7435 } 7436 7437 return NULL; 7438 } 7439 7440 /* 7441 * Check if scalar registers are exact for the purpose of not widening. 7442 * More lenient than regs_exact() 7443 */ 7444 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold, 7445 const struct bpf_reg_state *rcur) 7446 { 7447 return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)); 7448 } 7449 7450 static void maybe_widen_reg(struct bpf_verifier_env *env, 7451 struct bpf_reg_state *rold, struct bpf_reg_state *rcur) 7452 { 7453 if (rold->type != SCALAR_VALUE) 7454 return; 7455 if (rold->type != rcur->type) 7456 return; 7457 if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur)) 7458 return; 7459 __mark_reg_unknown(env, rcur); 7460 } 7461 7462 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7463 struct bpf_verifier_state *old, 7464 struct bpf_verifier_state *cur) 7465 { 7466 struct bpf_func_state *fold, *fcur; 7467 int i, fr, num_slots; 7468 7469 for (fr = old->curframe; fr >= 0; fr--) { 7470 fold = old->frame[fr]; 7471 fcur = cur->frame[fr]; 7472 7473 for (i = 0; i < MAX_BPF_REG; i++) 7474 maybe_widen_reg(env, 7475 &fold->regs[i], 7476 &fcur->regs[i]); 7477 7478 num_slots = min(fold->allocated_stack / BPF_REG_SIZE, 7479 fcur->allocated_stack / BPF_REG_SIZE); 7480 for (i = 0; i < num_slots; i++) { 7481 if (!bpf_is_spilled_reg(&fold->stack[i]) || 7482 !bpf_is_spilled_reg(&fcur->stack[i])) 7483 continue; 7484 7485 maybe_widen_reg(env, 7486 &fold->stack[i].spilled_ptr, 7487 &fcur->stack[i].spilled_ptr); 7488 } 7489 } 7490 return 0; 7491 } 7492 7493 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 7494 struct bpf_kfunc_call_arg_meta *meta) 7495 { 7496 int iter_frameno = meta->iter.frameno; 7497 int iter_spi = meta->iter.spi; 7498 7499 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7500 } 7501 7502 /* process_iter_next_call() is called when verifier gets to iterator's next 7503 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7504 * to it as just "iter_next()" in comments below. 7505 * 7506 * BPF verifier relies on a crucial contract for any iter_next() 7507 * implementation: it should *eventually* return NULL, and once that happens 7508 * it should keep returning NULL. That is, once iterator exhausts elements to 7509 * iterate, it should never reset or spuriously return new elements. 7510 * 7511 * With the assumption of such contract, process_iter_next_call() simulates 7512 * a fork in the verifier state to validate loop logic correctness and safety 7513 * without having to simulate infinite amount of iterations. 7514 * 7515 * In current state, we first assume that iter_next() returned NULL and 7516 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7517 * conditions we should not form an infinite loop and should eventually reach 7518 * exit. 7519 * 7520 * Besides that, we also fork current state and enqueue it for later 7521 * verification. In a forked state we keep iterator state as ACTIVE 7522 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7523 * also bump iteration depth to prevent erroneous infinite loop detection 7524 * later on (see iter_active_depths_differ() comment for details). In this 7525 * state we assume that we'll eventually loop back to another iter_next() 7526 * calls (it could be in exactly same location or in some other instruction, 7527 * it doesn't matter, we don't make any unnecessary assumptions about this, 7528 * everything revolves around iterator state in a stack slot, not which 7529 * instruction is calling iter_next()). When that happens, we either will come 7530 * to iter_next() with equivalent state and can conclude that next iteration 7531 * will proceed in exactly the same way as we just verified, so it's safe to 7532 * assume that loop converges. If not, we'll go on another iteration 7533 * simulation with a different input state, until all possible starting states 7534 * are validated or we reach maximum number of instructions limit. 7535 * 7536 * This way, we will either exhaustively discover all possible input states 7537 * that iterator loop can start with and eventually will converge, or we'll 7538 * effectively regress into bounded loop simulation logic and either reach 7539 * maximum number of instructions if loop is not provably convergent, or there 7540 * is some statically known limit on number of iterations (e.g., if there is 7541 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7542 * 7543 * Iteration convergence logic in is_state_visited() relies on exact 7544 * states comparison, which ignores read and precision marks. 7545 * This is necessary because read and precision marks are not finalized 7546 * while in the loop. Exact comparison might preclude convergence for 7547 * simple programs like below: 7548 * 7549 * i = 0; 7550 * while(iter_next(&it)) 7551 * i++; 7552 * 7553 * At each iteration step i++ would produce a new distinct state and 7554 * eventually instruction processing limit would be reached. 7555 * 7556 * To avoid such behavior speculatively forget (widen) range for 7557 * imprecise scalar registers, if those registers were not precise at the 7558 * end of the previous iteration and do not match exactly. 7559 * 7560 * This is a conservative heuristic that allows to verify wide range of programs, 7561 * however it precludes verification of programs that conjure an 7562 * imprecise value on the first loop iteration and use it as precise on a second. 7563 * For example, the following safe program would fail to verify: 7564 * 7565 * struct bpf_num_iter it; 7566 * int arr[10]; 7567 * int i = 0, a = 0; 7568 * bpf_iter_num_new(&it, 0, 10); 7569 * while (bpf_iter_num_next(&it)) { 7570 * if (a == 0) { 7571 * a = 1; 7572 * i = 7; // Because i changed verifier would forget 7573 * // it's range on second loop entry. 7574 * } else { 7575 * arr[i] = 42; // This would fail to verify. 7576 * } 7577 * } 7578 * bpf_iter_num_destroy(&it); 7579 */ 7580 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7581 struct bpf_kfunc_call_arg_meta *meta) 7582 { 7583 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7584 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7585 struct bpf_reg_state *cur_iter, *queued_iter; 7586 7587 BTF_TYPE_EMIT(struct bpf_iter); 7588 7589 cur_iter = get_iter_from_state(cur_st, meta); 7590 7591 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7592 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7593 verifier_bug(env, "unexpected iterator state %d (%s)", 7594 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7595 return -EFAULT; 7596 } 7597 7598 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7599 /* Because iter_next() call is a checkpoint is_state_visitied() 7600 * should guarantee parent state with same call sites and insn_idx. 7601 */ 7602 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7603 !same_callsites(cur_st->parent, cur_st)) { 7604 verifier_bug(env, "bad parent state for iter next call"); 7605 return -EFAULT; 7606 } 7607 /* Note cur_st->parent in the call below, it is necessary to skip 7608 * checkpoint created for cur_st by is_state_visited() 7609 * right at this instruction. 7610 */ 7611 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7612 /* branch out active iter state */ 7613 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7614 if (IS_ERR(queued_st)) 7615 return PTR_ERR(queued_st); 7616 7617 queued_iter = get_iter_from_state(queued_st, meta); 7618 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7619 queued_iter->iter.depth++; 7620 if (prev_st) 7621 widen_imprecise_scalars(env, prev_st, queued_st); 7622 7623 queued_fr = queued_st->frame[queued_st->curframe]; 7624 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7625 } 7626 7627 /* switch to DRAINED state, but keep the depth unchanged */ 7628 /* mark current iter state as drained and assume returned NULL */ 7629 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7630 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7631 7632 return 0; 7633 } 7634 7635 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7636 { 7637 return type == ARG_CONST_SIZE || 7638 type == ARG_CONST_SIZE_OR_ZERO; 7639 } 7640 7641 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 7642 { 7643 return base_type(type) == ARG_PTR_TO_MEM && 7644 type & MEM_UNINIT; 7645 } 7646 7647 static bool arg_type_is_release(enum bpf_arg_type type) 7648 { 7649 return type & OBJ_RELEASE; 7650 } 7651 7652 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7653 { 7654 return base_type(type) == ARG_PTR_TO_DYNPTR; 7655 } 7656 7657 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7658 const struct bpf_call_arg_meta *meta, 7659 enum bpf_arg_type *arg_type) 7660 { 7661 if (!meta->map.ptr) { 7662 /* kernel subsystem misconfigured verifier */ 7663 verifier_bug(env, "invalid map_ptr to access map->type"); 7664 return -EFAULT; 7665 } 7666 7667 switch (meta->map.ptr->map_type) { 7668 case BPF_MAP_TYPE_SOCKMAP: 7669 case BPF_MAP_TYPE_SOCKHASH: 7670 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7671 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7672 } else { 7673 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7674 return -EINVAL; 7675 } 7676 break; 7677 case BPF_MAP_TYPE_BLOOM_FILTER: 7678 if (meta->func_id == BPF_FUNC_map_peek_elem) 7679 *arg_type = ARG_PTR_TO_MAP_VALUE; 7680 break; 7681 default: 7682 break; 7683 } 7684 return 0; 7685 } 7686 7687 struct bpf_reg_types { 7688 const enum bpf_reg_type types[10]; 7689 u32 *btf_id; 7690 }; 7691 7692 static const struct bpf_reg_types sock_types = { 7693 .types = { 7694 PTR_TO_SOCK_COMMON, 7695 PTR_TO_SOCKET, 7696 PTR_TO_TCP_SOCK, 7697 PTR_TO_XDP_SOCK, 7698 }, 7699 }; 7700 7701 #ifdef CONFIG_NET 7702 static const struct bpf_reg_types btf_id_sock_common_types = { 7703 .types = { 7704 PTR_TO_SOCK_COMMON, 7705 PTR_TO_SOCKET, 7706 PTR_TO_TCP_SOCK, 7707 PTR_TO_XDP_SOCK, 7708 PTR_TO_BTF_ID, 7709 PTR_TO_BTF_ID | PTR_TRUSTED, 7710 }, 7711 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7712 }; 7713 #endif 7714 7715 static const struct bpf_reg_types mem_types = { 7716 .types = { 7717 PTR_TO_STACK, 7718 PTR_TO_PACKET, 7719 PTR_TO_PACKET_META, 7720 PTR_TO_MAP_KEY, 7721 PTR_TO_MAP_VALUE, 7722 PTR_TO_MEM, 7723 PTR_TO_MEM | MEM_RINGBUF, 7724 PTR_TO_BUF, 7725 PTR_TO_BTF_ID | PTR_TRUSTED, 7726 PTR_TO_CTX, 7727 }, 7728 }; 7729 7730 static const struct bpf_reg_types spin_lock_types = { 7731 .types = { 7732 PTR_TO_MAP_VALUE, 7733 PTR_TO_BTF_ID | MEM_ALLOC, 7734 } 7735 }; 7736 7737 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7738 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7739 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7740 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7741 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7742 static const struct bpf_reg_types btf_ptr_types = { 7743 .types = { 7744 PTR_TO_BTF_ID, 7745 PTR_TO_BTF_ID | PTR_TRUSTED, 7746 PTR_TO_BTF_ID | MEM_RCU, 7747 }, 7748 }; 7749 static const struct bpf_reg_types percpu_btf_ptr_types = { 7750 .types = { 7751 PTR_TO_BTF_ID | MEM_PERCPU, 7752 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 7753 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7754 } 7755 }; 7756 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7757 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7758 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7759 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7760 static const struct bpf_reg_types kptr_xchg_dest_types = { 7761 .types = { 7762 PTR_TO_MAP_VALUE, 7763 PTR_TO_BTF_ID | MEM_ALLOC, 7764 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF, 7765 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU, 7766 } 7767 }; 7768 static const struct bpf_reg_types dynptr_types = { 7769 .types = { 7770 PTR_TO_STACK, 7771 CONST_PTR_TO_DYNPTR, 7772 } 7773 }; 7774 7775 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7776 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7777 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7778 [ARG_CONST_SIZE] = &scalar_types, 7779 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7780 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7781 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7782 [ARG_PTR_TO_CTX] = &context_types, 7783 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7784 #ifdef CONFIG_NET 7785 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7786 #endif 7787 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7788 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7789 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7790 [ARG_PTR_TO_MEM] = &mem_types, 7791 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7792 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7793 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7794 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7795 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7796 [ARG_PTR_TO_TIMER] = &timer_types, 7797 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 7798 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7799 }; 7800 7801 static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 7802 enum bpf_arg_type arg_type, 7803 const u32 *arg_btf_id, 7804 struct bpf_call_arg_meta *meta) 7805 { 7806 enum bpf_reg_type expected, type = reg->type; 7807 const struct bpf_reg_types *compatible; 7808 int i, j, err; 7809 7810 compatible = compatible_reg_types[base_type(arg_type)]; 7811 if (!compatible) { 7812 verifier_bug(env, "unsupported arg type %d", arg_type); 7813 return -EFAULT; 7814 } 7815 7816 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7817 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7818 * 7819 * Same for MAYBE_NULL: 7820 * 7821 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7822 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7823 * 7824 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 7825 * 7826 * Therefore we fold these flags depending on the arg_type before comparison. 7827 */ 7828 if (arg_type & MEM_RDONLY) 7829 type &= ~MEM_RDONLY; 7830 if (arg_type & PTR_MAYBE_NULL) 7831 type &= ~PTR_MAYBE_NULL; 7832 if (base_type(arg_type) == ARG_PTR_TO_MEM) 7833 type &= ~DYNPTR_TYPE_FLAG_MASK; 7834 7835 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 7836 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && reg_from_argno(argno) == BPF_REG_2) { 7837 type &= ~MEM_ALLOC; 7838 type &= ~MEM_PERCPU; 7839 } 7840 7841 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7842 expected = compatible->types[i]; 7843 if (expected == NOT_INIT) 7844 break; 7845 7846 if (type == expected) 7847 goto found; 7848 } 7849 7850 verbose(env, "%s type=%s expected=", reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7851 for (j = 0; j + 1 < i; j++) 7852 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7853 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7854 return -EACCES; 7855 7856 found: 7857 if (base_type(reg->type) != PTR_TO_BTF_ID) 7858 return 0; 7859 7860 if (compatible == &mem_types) { 7861 if (!(arg_type & MEM_RDONLY)) { 7862 verbose(env, 7863 "%s() may write into memory pointed by %s type=%s\n", 7864 func_id_name(meta->func_id), 7865 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 7866 return -EACCES; 7867 } 7868 return 0; 7869 } 7870 7871 switch ((int)reg->type) { 7872 case PTR_TO_BTF_ID: 7873 case PTR_TO_BTF_ID | PTR_TRUSTED: 7874 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 7875 case PTR_TO_BTF_ID | MEM_RCU: 7876 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 7877 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 7878 { 7879 /* For bpf_sk_release, it needs to match against first member 7880 * 'struct sock_common', hence make an exception for it. This 7881 * allows bpf_sk_release to work for multiple socket types. 7882 */ 7883 bool strict_type_match = arg_type_is_release(arg_type) && 7884 meta->func_id != BPF_FUNC_sk_release; 7885 7886 if (type_may_be_null(reg->type) && 7887 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 7888 verbose(env, "Possibly NULL pointer passed to helper %s\n", 7889 reg_arg_name(env, argno)); 7890 return -EACCES; 7891 } 7892 7893 if (!arg_btf_id) { 7894 if (!compatible->btf_id) { 7895 verifier_bug(env, "missing arg compatible BTF ID"); 7896 return -EFAULT; 7897 } 7898 arg_btf_id = compatible->btf_id; 7899 } 7900 7901 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7902 if (map_kptr_match_type(env, meta->kptr_field, reg, reg_from_argno(argno))) 7903 return -EACCES; 7904 } else { 7905 if (arg_btf_id == BPF_PTR_POISON) { 7906 verbose(env, "verifier internal error:"); 7907 verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n", 7908 reg_arg_name(env, argno)); 7909 return -EACCES; 7910 } 7911 7912 err = __check_ptr_off_reg(env, reg, argno, true); 7913 if (err) 7914 return err; 7915 7916 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 7917 reg->var_off.value, btf_vmlinux, *arg_btf_id, 7918 strict_type_match)) { 7919 verbose(env, "%s is of type %s but %s is expected\n", 7920 reg_arg_name(env, argno), 7921 btf_type_name(reg->btf, reg->btf_id), 7922 btf_type_name(btf_vmlinux, *arg_btf_id)); 7923 return -EACCES; 7924 } 7925 } 7926 break; 7927 } 7928 case PTR_TO_BTF_ID | MEM_ALLOC: 7929 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 7930 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 7931 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 7932 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 7933 meta->func_id != BPF_FUNC_kptr_xchg) { 7934 verifier_bug(env, "unimplemented handling of MEM_ALLOC"); 7935 return -EFAULT; 7936 } 7937 /* Check if local kptr in src arg matches kptr in dst arg */ 7938 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7939 int regno = reg_from_argno(argno); 7940 7941 if (regno == BPF_REG_2 && 7942 map_kptr_match_type(env, meta->kptr_field, reg, regno)) 7943 return -EACCES; 7944 } 7945 break; 7946 case PTR_TO_BTF_ID | MEM_PERCPU: 7947 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 7948 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 7949 /* Handled by helper specific checks */ 7950 break; 7951 default: 7952 verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match"); 7953 return -EFAULT; 7954 } 7955 return 0; 7956 } 7957 7958 static struct btf_field * 7959 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 7960 { 7961 struct btf_field *field; 7962 struct btf_record *rec; 7963 7964 rec = reg_btf_record(reg); 7965 if (!rec) 7966 return NULL; 7967 7968 field = btf_record_find(rec, off, fields); 7969 if (!field) 7970 return NULL; 7971 7972 return field; 7973 } 7974 7975 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 7976 const struct bpf_reg_state *reg, argno_t argno, 7977 enum bpf_arg_type arg_type) 7978 { 7979 u32 type = reg->type; 7980 7981 /* When referenced register is passed to release function, its fixed 7982 * offset must be 0. 7983 * 7984 * We will check arg_type_is_release reg has id when storing 7985 * meta->release_regno. 7986 */ 7987 if (arg_type_is_release(arg_type)) { 7988 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 7989 * may not directly point to the object being released, but to 7990 * dynptr pointing to such object, which might be at some offset 7991 * on the stack. In that case, we simply to fallback to the 7992 * default handling. 7993 */ 7994 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 7995 return 0; 7996 7997 /* Doing check_ptr_off_reg check for the offset will catch this 7998 * because fixed_off_ok is false, but checking here allows us 7999 * to give the user a better error message. 8000 */ 8001 if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) { 8002 verbose(env, "%s must have zero offset when passed to release func or trusted arg to kfunc\n", 8003 reg_arg_name(env, argno)); 8004 return -EINVAL; 8005 } 8006 } 8007 8008 switch (type) { 8009 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8010 case PTR_TO_STACK: 8011 case PTR_TO_PACKET: 8012 case PTR_TO_PACKET_META: 8013 case PTR_TO_MAP_KEY: 8014 case PTR_TO_MAP_VALUE: 8015 case PTR_TO_MEM: 8016 case PTR_TO_MEM | MEM_RDONLY: 8017 case PTR_TO_MEM | MEM_RINGBUF: 8018 case PTR_TO_BUF: 8019 case PTR_TO_BUF | MEM_RDONLY: 8020 case PTR_TO_ARENA: 8021 case SCALAR_VALUE: 8022 return 0; 8023 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8024 * fixed offset. 8025 */ 8026 case PTR_TO_BTF_ID: 8027 case PTR_TO_BTF_ID | MEM_ALLOC: 8028 case PTR_TO_BTF_ID | PTR_TRUSTED: 8029 case PTR_TO_BTF_ID | MEM_RCU: 8030 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8031 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8032 /* When referenced PTR_TO_BTF_ID is passed to release function, 8033 * its fixed offset must be 0. In the other cases, fixed offset 8034 * can be non-zero. This was already checked above. So pass 8035 * fixed_off_ok as true to allow fixed offset for all other 8036 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8037 * still need to do checks instead of returning. 8038 */ 8039 return __check_ptr_off_reg(env, reg, argno, true); 8040 case PTR_TO_CTX: 8041 /* 8042 * Allow fixed and variable offsets for syscall context, but 8043 * only when the argument is passed as memory, not ctx, 8044 * otherwise we may get modified ctx in tail called programs and 8045 * global subprogs (that may act as extension prog hooks). 8046 */ 8047 if (arg_type != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog)) 8048 return 0; 8049 fallthrough; 8050 default: 8051 return __check_ptr_off_reg(env, reg, argno, false); 8052 } 8053 } 8054 8055 static int check_arg_const_str(struct bpf_verifier_env *env, 8056 struct bpf_reg_state *reg, argno_t argno) 8057 { 8058 struct bpf_map *map = reg->map_ptr; 8059 int err; 8060 int map_off; 8061 u64 map_addr; 8062 char *str_ptr; 8063 8064 if (reg->type != PTR_TO_MAP_VALUE) 8065 return -EINVAL; 8066 8067 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 8068 verbose(env, "%s points to insn_array map which cannot be used as const string\n", 8069 reg_arg_name(env, argno)); 8070 return -EACCES; 8071 } 8072 8073 if (!bpf_map_is_rdonly(map)) { 8074 verbose(env, "%s does not point to a readonly map'\n", reg_arg_name(env, argno)); 8075 return -EACCES; 8076 } 8077 8078 if (!tnum_is_const(reg->var_off)) { 8079 verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno)); 8080 return -EACCES; 8081 } 8082 8083 if (!map->ops->map_direct_value_addr) { 8084 verbose(env, "no direct value access support for this map type\n"); 8085 return -EACCES; 8086 } 8087 8088 err = check_map_access(env, reg, argno, 0, 8089 map->value_size - reg->var_off.value, false, 8090 ACCESS_HELPER); 8091 if (err) 8092 return err; 8093 8094 map_off = reg->var_off.value; 8095 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8096 if (err) { 8097 verbose(env, "direct value access on string failed\n"); 8098 return err; 8099 } 8100 8101 str_ptr = (char *)(long)(map_addr); 8102 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8103 verbose(env, "string is not zero-terminated\n"); 8104 return -EINVAL; 8105 } 8106 return 0; 8107 } 8108 8109 /* Returns constant key value in `value` if possible, else negative error */ 8110 static int get_constant_map_key(struct bpf_verifier_env *env, 8111 struct bpf_reg_state *key, 8112 u32 key_size, 8113 s64 *value) 8114 { 8115 struct bpf_func_state *state = bpf_func(env, key); 8116 struct bpf_reg_state *reg; 8117 int slot, spi, off; 8118 int spill_size = 0; 8119 int zero_size = 0; 8120 int stack_off; 8121 int i, err; 8122 u8 *stype; 8123 8124 if (!env->bpf_capable) 8125 return -EOPNOTSUPP; 8126 if (key->type != PTR_TO_STACK) 8127 return -EOPNOTSUPP; 8128 if (!tnum_is_const(key->var_off)) 8129 return -EOPNOTSUPP; 8130 8131 stack_off = key->var_off.value; 8132 slot = -stack_off - 1; 8133 spi = slot / BPF_REG_SIZE; 8134 off = slot % BPF_REG_SIZE; 8135 stype = state->stack[spi].slot_type; 8136 8137 /* First handle precisely tracked STACK_ZERO */ 8138 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) 8139 zero_size++; 8140 if (zero_size >= key_size) { 8141 *value = 0; 8142 return 0; 8143 } 8144 8145 /* Check that stack contains a scalar spill of expected size */ 8146 if (!bpf_is_spilled_scalar_reg(&state->stack[spi])) 8147 return -EOPNOTSUPP; 8148 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) 8149 spill_size++; 8150 if (spill_size != key_size) 8151 return -EOPNOTSUPP; 8152 8153 reg = &state->stack[spi].spilled_ptr; 8154 if (!tnum_is_const(reg->var_off)) 8155 /* Stack value not statically known */ 8156 return -EOPNOTSUPP; 8157 8158 /* We are relying on a constant value. So mark as precise 8159 * to prevent pruning on it. 8160 */ 8161 bpf_bt_set_frame_slot(&env->bt, key->frameno, spi); 8162 err = mark_chain_precision_batch(env, env->cur_state); 8163 if (err < 0) 8164 return err; 8165 8166 *value = reg->var_off.value; 8167 return 0; 8168 } 8169 8170 static bool can_elide_value_nullness(enum bpf_map_type type); 8171 8172 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8173 struct bpf_call_arg_meta *meta, 8174 const struct bpf_func_proto *fn, 8175 int insn_idx) 8176 { 8177 u32 regno = BPF_REG_1 + arg; 8178 struct bpf_reg_state *reg = reg_state(env, regno); 8179 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8180 argno_t argno = argno_from_arg(arg + 1); 8181 enum bpf_reg_type type = reg->type; 8182 u32 *arg_btf_id = NULL; 8183 u32 key_size; 8184 int err = 0; 8185 8186 if (arg_type == ARG_DONTCARE) 8187 return 0; 8188 8189 err = check_reg_arg(env, regno, SRC_OP); 8190 if (err) 8191 return err; 8192 8193 if (arg_type == ARG_ANYTHING) { 8194 if (is_pointer_value(env, regno)) { 8195 verbose(env, "R%d leaks addr into helper function\n", 8196 regno); 8197 return -EACCES; 8198 } 8199 return 0; 8200 } 8201 8202 if (type_is_pkt_pointer(type) && 8203 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8204 verbose(env, "helper access to the packet is not allowed\n"); 8205 return -EACCES; 8206 } 8207 8208 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8209 err = resolve_map_arg_type(env, meta, &arg_type); 8210 if (err) 8211 return err; 8212 } 8213 8214 if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) 8215 /* A NULL register has a SCALAR_VALUE type, so skip 8216 * type checking. 8217 */ 8218 goto skip_type_check; 8219 8220 /* arg_btf_id and arg_size are in a union. */ 8221 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8222 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8223 arg_btf_id = fn->arg_btf_id[arg]; 8224 8225 err = check_reg_type(env, reg, argno_from_reg(regno), arg_type, arg_btf_id, meta); 8226 if (err) 8227 return err; 8228 8229 err = check_func_arg_reg_off(env, reg, argno_from_reg(regno), arg_type); 8230 if (err) 8231 return err; 8232 8233 skip_type_check: 8234 if (arg_type_is_release(arg_type) && !arg_type_is_dynptr(arg_type) && 8235 !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) { 8236 verbose(env, "release helper %s expects referenced PTR_TO_BTF_ID passed to %s\n", 8237 func_id_name(meta->func_id), reg_arg_name(env, argno)); 8238 return -EINVAL; 8239 } 8240 8241 if (reg_is_referenced(env, reg)) 8242 update_ref_obj(&meta->ref_obj, reg); 8243 8244 switch (base_type(arg_type)) { 8245 case ARG_CONST_MAP_PTR: 8246 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8247 if (meta->map.ptr) { 8248 /* Use map_uid (which is unique id of inner map) to reject: 8249 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8250 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8251 * if (inner_map1 && inner_map2) { 8252 * timer = bpf_map_lookup_elem(inner_map1); 8253 * if (timer) 8254 * // mismatch would have been allowed 8255 * bpf_timer_init(timer, inner_map2); 8256 * } 8257 * 8258 * Comparing map_ptr is enough to distinguish normal and outer maps. 8259 */ 8260 if (meta->map.ptr != reg->map_ptr || 8261 meta->map.uid != reg->map_uid) { 8262 verbose(env, 8263 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8264 meta->map.uid, reg->map_uid); 8265 return -EINVAL; 8266 } 8267 } 8268 meta->map.ptr = reg->map_ptr; 8269 meta->map.uid = reg->map_uid; 8270 break; 8271 case ARG_PTR_TO_MAP_KEY: 8272 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8273 * check that [key, key + map->key_size) are within 8274 * stack limits and initialized 8275 */ 8276 if (!meta->map.ptr) { 8277 /* in function declaration map_ptr must come before 8278 * map_key, so that it's verified and known before 8279 * we have to check map_key here. Otherwise it means 8280 * that kernel subsystem misconfigured verifier 8281 */ 8282 verifier_bug(env, "invalid map_ptr to access map->key"); 8283 return -EFAULT; 8284 } 8285 key_size = meta->map.ptr->key_size; 8286 err = check_helper_mem_access(env, reg, argno_from_reg(regno), key_size, BPF_READ, false, NULL); 8287 if (err) 8288 return err; 8289 if (can_elide_value_nullness(meta->map.ptr->map_type)) { 8290 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key); 8291 if (err < 0) { 8292 meta->const_map_key = -1; 8293 if (err == -EOPNOTSUPP) 8294 err = 0; 8295 else 8296 return err; 8297 } 8298 } 8299 break; 8300 case ARG_PTR_TO_MAP_VALUE: 8301 if (type_may_be_null(arg_type) && bpf_register_is_null(reg)) 8302 return 0; 8303 8304 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8305 * check [value, value + map->value_size) validity 8306 */ 8307 if (!meta->map.ptr) { 8308 /* kernel subsystem misconfigured verifier */ 8309 verifier_bug(env, "invalid map_ptr to access map->value"); 8310 return -EFAULT; 8311 } 8312 meta->raw_mode = arg_type & MEM_UNINIT; 8313 err = check_helper_mem_access(env, reg, argno_from_reg(regno), meta->map.ptr->value_size, 8314 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8315 false, meta); 8316 break; 8317 case ARG_PTR_TO_PERCPU_BTF_ID: 8318 if (!reg->btf_id) { 8319 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8320 return -EACCES; 8321 } 8322 meta->ret_btf = reg->btf; 8323 meta->ret_btf_id = reg->btf_id; 8324 break; 8325 case ARG_PTR_TO_SPIN_LOCK: 8326 if (in_rbtree_lock_required_cb(env)) { 8327 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8328 return -EACCES; 8329 } 8330 if (meta->func_id == BPF_FUNC_spin_lock) { 8331 err = process_spin_lock(env, reg, argno_from_reg(regno), PROCESS_SPIN_LOCK); 8332 if (err) 8333 return err; 8334 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8335 err = process_spin_lock(env, reg, argno_from_reg(regno), 0); 8336 if (err) 8337 return err; 8338 } else { 8339 verifier_bug(env, "spin lock arg on unexpected helper"); 8340 return -EFAULT; 8341 } 8342 break; 8343 case ARG_PTR_TO_TIMER: 8344 err = process_timer_helper(env, reg, argno_from_reg(regno), meta); 8345 if (err) 8346 return err; 8347 break; 8348 case ARG_PTR_TO_FUNC: 8349 meta->subprogno = reg->subprogno; 8350 break; 8351 case ARG_PTR_TO_MEM: 8352 /* The access to this pointer is only checked when we hit the 8353 * next is_mem_size argument below. 8354 */ 8355 meta->raw_mode = arg_type & MEM_UNINIT; 8356 if (arg_type & MEM_FIXED_SIZE) { 8357 err = check_helper_mem_access(env, reg, argno_from_reg(regno), fn->arg_size[arg], 8358 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8359 false, meta); 8360 if (err) 8361 return err; 8362 if (arg_type & MEM_ALIGNED) 8363 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 8364 } 8365 break; 8366 case ARG_CONST_SIZE: 8367 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1), 8368 argno_from_reg(regno), 8369 fn->arg_type[arg - 1] & MEM_WRITE ? 8370 BPF_WRITE : BPF_READ, 8371 false, meta); 8372 break; 8373 case ARG_CONST_SIZE_OR_ZERO: 8374 err = check_mem_size_reg(env, reg_state(env, regno - 1), reg, argno_from_reg(regno - 1), 8375 argno_from_reg(regno), 8376 fn->arg_type[arg - 1] & MEM_WRITE ? 8377 BPF_WRITE : BPF_READ, 8378 true, meta); 8379 break; 8380 case ARG_PTR_TO_DYNPTR: 8381 err = process_dynptr_func(env, reg, argno_from_reg(regno), insn_idx, arg_type, &meta->ref_obj, 8382 &meta->dynptr); 8383 if (err) 8384 return err; 8385 break; 8386 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8387 if (!tnum_is_const(reg->var_off)) { 8388 verbose(env, "R%d is not a known constant'\n", 8389 regno); 8390 return -EACCES; 8391 } 8392 meta->mem_size = reg->var_off.value; 8393 err = mark_chain_precision(env, regno); 8394 if (err) 8395 return err; 8396 break; 8397 case ARG_PTR_TO_CONST_STR: 8398 { 8399 err = check_arg_const_str(env, reg, argno_from_reg(regno)); 8400 if (err) 8401 return err; 8402 break; 8403 } 8404 case ARG_KPTR_XCHG_DEST: 8405 err = process_kptr_func(env, regno, meta); 8406 if (err) 8407 return err; 8408 break; 8409 } 8410 8411 return err; 8412 } 8413 8414 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8415 { 8416 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8417 enum bpf_prog_type type = resolve_prog_type(env->prog); 8418 8419 if (func_id != BPF_FUNC_map_update_elem && 8420 func_id != BPF_FUNC_map_delete_elem) 8421 return false; 8422 8423 /* It's not possible to get access to a locked struct sock in these 8424 * contexts, so updating is safe. 8425 */ 8426 switch (type) { 8427 case BPF_PROG_TYPE_TRACING: 8428 if (eatype == BPF_TRACE_ITER) 8429 return true; 8430 break; 8431 case BPF_PROG_TYPE_SOCK_OPS: 8432 /* map_update allowed only via dedicated helpers with event type checks */ 8433 if (func_id == BPF_FUNC_map_delete_elem) 8434 return true; 8435 break; 8436 case BPF_PROG_TYPE_SOCKET_FILTER: 8437 case BPF_PROG_TYPE_SCHED_CLS: 8438 case BPF_PROG_TYPE_SCHED_ACT: 8439 case BPF_PROG_TYPE_XDP: 8440 case BPF_PROG_TYPE_SK_REUSEPORT: 8441 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8442 case BPF_PROG_TYPE_SK_LOOKUP: 8443 return true; 8444 default: 8445 break; 8446 } 8447 8448 verbose(env, "cannot update sockmap in this context\n"); 8449 return false; 8450 } 8451 8452 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8453 { 8454 return env->prog->jit_requested && 8455 bpf_jit_supports_subprog_tailcalls(); 8456 } 8457 8458 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8459 struct bpf_map *map, int func_id) 8460 { 8461 if (!map) 8462 return 0; 8463 8464 /* We need a two way check, first is from map perspective ... */ 8465 switch (map->map_type) { 8466 case BPF_MAP_TYPE_PROG_ARRAY: 8467 if (func_id != BPF_FUNC_tail_call) 8468 goto error; 8469 break; 8470 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8471 if (func_id != BPF_FUNC_perf_event_read && 8472 func_id != BPF_FUNC_perf_event_output && 8473 func_id != BPF_FUNC_skb_output && 8474 func_id != BPF_FUNC_perf_event_read_value && 8475 func_id != BPF_FUNC_xdp_output) 8476 goto error; 8477 break; 8478 case BPF_MAP_TYPE_RINGBUF: 8479 if (func_id != BPF_FUNC_ringbuf_output && 8480 func_id != BPF_FUNC_ringbuf_reserve && 8481 func_id != BPF_FUNC_ringbuf_query && 8482 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8483 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8484 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8485 goto error; 8486 break; 8487 case BPF_MAP_TYPE_USER_RINGBUF: 8488 if (func_id != BPF_FUNC_user_ringbuf_drain) 8489 goto error; 8490 break; 8491 case BPF_MAP_TYPE_STACK_TRACE: 8492 if (func_id != BPF_FUNC_get_stackid) 8493 goto error; 8494 break; 8495 case BPF_MAP_TYPE_CGROUP_ARRAY: 8496 if (func_id != BPF_FUNC_skb_under_cgroup && 8497 func_id != BPF_FUNC_current_task_under_cgroup) 8498 goto error; 8499 break; 8500 case BPF_MAP_TYPE_CGROUP_STORAGE: 8501 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8502 if (func_id != BPF_FUNC_get_local_storage) 8503 goto error; 8504 break; 8505 case BPF_MAP_TYPE_DEVMAP: 8506 case BPF_MAP_TYPE_DEVMAP_HASH: 8507 if (func_id != BPF_FUNC_redirect_map && 8508 func_id != BPF_FUNC_map_lookup_elem) 8509 goto error; 8510 break; 8511 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8512 * appear. 8513 */ 8514 case BPF_MAP_TYPE_CPUMAP: 8515 if (func_id != BPF_FUNC_redirect_map) 8516 goto error; 8517 break; 8518 case BPF_MAP_TYPE_XSKMAP: 8519 if (func_id != BPF_FUNC_redirect_map && 8520 func_id != BPF_FUNC_map_lookup_elem) 8521 goto error; 8522 break; 8523 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8524 case BPF_MAP_TYPE_HASH_OF_MAPS: 8525 if (func_id != BPF_FUNC_map_lookup_elem) 8526 goto error; 8527 break; 8528 case BPF_MAP_TYPE_SOCKMAP: 8529 if (func_id != BPF_FUNC_sk_redirect_map && 8530 func_id != BPF_FUNC_sock_map_update && 8531 func_id != BPF_FUNC_msg_redirect_map && 8532 func_id != BPF_FUNC_sk_select_reuseport && 8533 func_id != BPF_FUNC_map_lookup_elem && 8534 !may_update_sockmap(env, func_id)) 8535 goto error; 8536 break; 8537 case BPF_MAP_TYPE_SOCKHASH: 8538 if (func_id != BPF_FUNC_sk_redirect_hash && 8539 func_id != BPF_FUNC_sock_hash_update && 8540 func_id != BPF_FUNC_msg_redirect_hash && 8541 func_id != BPF_FUNC_sk_select_reuseport && 8542 func_id != BPF_FUNC_map_lookup_elem && 8543 !may_update_sockmap(env, func_id)) 8544 goto error; 8545 break; 8546 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8547 if (func_id != BPF_FUNC_sk_select_reuseport) 8548 goto error; 8549 break; 8550 case BPF_MAP_TYPE_QUEUE: 8551 case BPF_MAP_TYPE_STACK: 8552 if (func_id != BPF_FUNC_map_peek_elem && 8553 func_id != BPF_FUNC_map_pop_elem && 8554 func_id != BPF_FUNC_map_push_elem) 8555 goto error; 8556 break; 8557 case BPF_MAP_TYPE_SK_STORAGE: 8558 if (func_id != BPF_FUNC_sk_storage_get && 8559 func_id != BPF_FUNC_sk_storage_delete && 8560 func_id != BPF_FUNC_kptr_xchg) 8561 goto error; 8562 break; 8563 case BPF_MAP_TYPE_INODE_STORAGE: 8564 if (func_id != BPF_FUNC_inode_storage_get && 8565 func_id != BPF_FUNC_inode_storage_delete && 8566 func_id != BPF_FUNC_kptr_xchg) 8567 goto error; 8568 break; 8569 case BPF_MAP_TYPE_TASK_STORAGE: 8570 if (func_id != BPF_FUNC_task_storage_get && 8571 func_id != BPF_FUNC_task_storage_delete && 8572 func_id != BPF_FUNC_kptr_xchg) 8573 goto error; 8574 break; 8575 case BPF_MAP_TYPE_CGRP_STORAGE: 8576 if (func_id != BPF_FUNC_cgrp_storage_get && 8577 func_id != BPF_FUNC_cgrp_storage_delete && 8578 func_id != BPF_FUNC_kptr_xchg) 8579 goto error; 8580 break; 8581 case BPF_MAP_TYPE_BLOOM_FILTER: 8582 if (func_id != BPF_FUNC_map_peek_elem && 8583 func_id != BPF_FUNC_map_push_elem) 8584 goto error; 8585 break; 8586 case BPF_MAP_TYPE_INSN_ARRAY: 8587 goto error; 8588 default: 8589 break; 8590 } 8591 8592 /* ... and second from the function itself. */ 8593 switch (func_id) { 8594 case BPF_FUNC_tail_call: 8595 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8596 goto error; 8597 if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) { 8598 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n"); 8599 return -EINVAL; 8600 } 8601 break; 8602 case BPF_FUNC_perf_event_read: 8603 case BPF_FUNC_perf_event_output: 8604 case BPF_FUNC_perf_event_read_value: 8605 case BPF_FUNC_skb_output: 8606 case BPF_FUNC_xdp_output: 8607 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8608 goto error; 8609 break; 8610 case BPF_FUNC_ringbuf_output: 8611 case BPF_FUNC_ringbuf_reserve: 8612 case BPF_FUNC_ringbuf_query: 8613 case BPF_FUNC_ringbuf_reserve_dynptr: 8614 case BPF_FUNC_ringbuf_submit_dynptr: 8615 case BPF_FUNC_ringbuf_discard_dynptr: 8616 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8617 goto error; 8618 break; 8619 case BPF_FUNC_user_ringbuf_drain: 8620 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8621 goto error; 8622 break; 8623 case BPF_FUNC_get_stackid: 8624 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8625 goto error; 8626 break; 8627 case BPF_FUNC_current_task_under_cgroup: 8628 case BPF_FUNC_skb_under_cgroup: 8629 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8630 goto error; 8631 break; 8632 case BPF_FUNC_redirect_map: 8633 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8634 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8635 map->map_type != BPF_MAP_TYPE_CPUMAP && 8636 map->map_type != BPF_MAP_TYPE_XSKMAP) 8637 goto error; 8638 break; 8639 case BPF_FUNC_sk_redirect_map: 8640 case BPF_FUNC_msg_redirect_map: 8641 case BPF_FUNC_sock_map_update: 8642 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8643 goto error; 8644 break; 8645 case BPF_FUNC_sk_redirect_hash: 8646 case BPF_FUNC_msg_redirect_hash: 8647 case BPF_FUNC_sock_hash_update: 8648 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8649 goto error; 8650 break; 8651 case BPF_FUNC_get_local_storage: 8652 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8653 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8654 goto error; 8655 break; 8656 case BPF_FUNC_sk_select_reuseport: 8657 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8658 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8659 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8660 goto error; 8661 break; 8662 case BPF_FUNC_map_pop_elem: 8663 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8664 map->map_type != BPF_MAP_TYPE_STACK) 8665 goto error; 8666 break; 8667 case BPF_FUNC_map_peek_elem: 8668 case BPF_FUNC_map_push_elem: 8669 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8670 map->map_type != BPF_MAP_TYPE_STACK && 8671 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8672 goto error; 8673 break; 8674 case BPF_FUNC_map_lookup_percpu_elem: 8675 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8676 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8677 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8678 goto error; 8679 break; 8680 case BPF_FUNC_sk_storage_get: 8681 case BPF_FUNC_sk_storage_delete: 8682 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8683 goto error; 8684 break; 8685 case BPF_FUNC_inode_storage_get: 8686 case BPF_FUNC_inode_storage_delete: 8687 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8688 goto error; 8689 break; 8690 case BPF_FUNC_task_storage_get: 8691 case BPF_FUNC_task_storage_delete: 8692 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8693 goto error; 8694 break; 8695 case BPF_FUNC_cgrp_storage_get: 8696 case BPF_FUNC_cgrp_storage_delete: 8697 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8698 goto error; 8699 break; 8700 default: 8701 break; 8702 } 8703 8704 return 0; 8705 error: 8706 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8707 map->map_type, func_id_name(func_id), func_id); 8708 return -EINVAL; 8709 } 8710 8711 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 8712 { 8713 int count = 0; 8714 8715 if (arg_type_is_raw_mem(fn->arg1_type)) 8716 count++; 8717 if (arg_type_is_raw_mem(fn->arg2_type)) 8718 count++; 8719 if (arg_type_is_raw_mem(fn->arg3_type)) 8720 count++; 8721 if (arg_type_is_raw_mem(fn->arg4_type)) 8722 count++; 8723 if (arg_type_is_raw_mem(fn->arg5_type)) 8724 count++; 8725 8726 /* We only support one arg being in raw mode at the moment, 8727 * which is sufficient for the helper functions we have 8728 * right now. 8729 */ 8730 return count <= 1; 8731 } 8732 8733 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8734 { 8735 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8736 bool has_size = fn->arg_size[arg] != 0; 8737 bool is_next_size = false; 8738 8739 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8740 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8741 8742 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8743 return is_next_size; 8744 8745 return has_size == is_next_size || is_next_size == is_fixed; 8746 } 8747 8748 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8749 { 8750 /* bpf_xxx(..., buf, len) call will access 'len' 8751 * bytes from memory 'buf'. Both arg types need 8752 * to be paired, so make sure there's no buggy 8753 * helper function specification. 8754 */ 8755 if (arg_type_is_mem_size(fn->arg1_type) || 8756 check_args_pair_invalid(fn, 0) || 8757 check_args_pair_invalid(fn, 1) || 8758 check_args_pair_invalid(fn, 2) || 8759 check_args_pair_invalid(fn, 3) || 8760 check_args_pair_invalid(fn, 4)) 8761 return false; 8762 8763 return true; 8764 } 8765 8766 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8767 { 8768 int i; 8769 8770 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8771 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8772 return !!fn->arg_btf_id[i]; 8773 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8774 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8775 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8776 /* arg_btf_id and arg_size are in a union. */ 8777 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8778 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8779 return false; 8780 } 8781 8782 return true; 8783 } 8784 8785 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn) 8786 { 8787 int i; 8788 8789 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8790 enum bpf_arg_type arg_type = fn->arg_type[i]; 8791 8792 if (base_type(arg_type) != ARG_PTR_TO_MEM) 8793 continue; 8794 if (!(arg_type & (MEM_WRITE | MEM_RDONLY))) 8795 return false; 8796 } 8797 8798 return true; 8799 } 8800 8801 static bool check_proto_release_reg(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8802 { 8803 int i; 8804 8805 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8806 enum bpf_arg_type arg_type = fn->arg_type[i]; 8807 8808 if (arg_type_is_release(arg_type)) { 8809 if (meta->release_regno) 8810 return false; 8811 meta->release_regno = i + 1; 8812 } 8813 } 8814 8815 return true; 8816 } 8817 8818 static int check_func_proto(const struct bpf_func_proto *fn, struct bpf_call_arg_meta *meta) 8819 { 8820 return check_raw_mode_ok(fn) && 8821 check_arg_pair_ok(fn) && 8822 check_mem_arg_rw_flag_ok(fn) && 8823 check_proto_release_reg(fn, meta) && 8824 check_btf_id_ok(fn) ? 0 : -EINVAL; 8825 } 8826 8827 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8828 * are now invalid, so turn them into unknown SCALAR_VALUE. 8829 * 8830 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8831 * since these slices point to packet data. 8832 */ 8833 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8834 { 8835 struct bpf_func_state *state; 8836 struct bpf_reg_state *reg; 8837 8838 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8839 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8840 mark_reg_invalid(env, reg); 8841 })); 8842 } 8843 8844 enum { 8845 AT_PKT_END = -1, 8846 BEYOND_PKT_END = -2, 8847 }; 8848 8849 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8850 { 8851 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8852 struct bpf_reg_state *reg = &state->regs[regn]; 8853 8854 if (reg->type != PTR_TO_PACKET) 8855 /* PTR_TO_PACKET_META is not supported yet */ 8856 return; 8857 8858 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8859 * How far beyond pkt_end it goes is unknown. 8860 * if (!range_open) it's the case of pkt >= pkt_end 8861 * if (range_open) it's the case of pkt > pkt_end 8862 * hence this pointer is at least 1 byte bigger than pkt_end 8863 */ 8864 if (range_open) 8865 reg->range = BEYOND_PKT_END; 8866 else 8867 reg->range = AT_PKT_END; 8868 } 8869 8870 static int release_reference_nomark(struct bpf_verifier_state *state, int id) 8871 { 8872 int i; 8873 8874 for (i = 0; i < state->acquired_refs; i++) { 8875 if (state->refs[i].type != REF_TYPE_PTR) 8876 continue; 8877 if (state->refs[i].id == id) { 8878 release_reference_state(state, i); 8879 return 0; 8880 } 8881 } 8882 return -EINVAL; 8883 } 8884 8885 static int idstack_push(struct bpf_idmap *idmap, u32 id) 8886 { 8887 int i; 8888 8889 if (!id) 8890 return 0; 8891 8892 for (i = 0; i < idmap->cnt; i++) 8893 if (idmap->map[i].old == id) 8894 return 0; 8895 8896 if (WARN_ON_ONCE(idmap->cnt >= BPF_ID_MAP_SIZE)) 8897 return -EFAULT; 8898 8899 idmap->map[idmap->cnt++].old = id; 8900 return 0; 8901 } 8902 8903 static int idstack_pop(struct bpf_idmap *idmap) 8904 { 8905 if (!idmap->cnt) 8906 return 0; 8907 8908 return idmap->map[--idmap->cnt].old; 8909 } 8910 8911 /* Release id and objects derived from it iteratively in a DFS manner */ 8912 static int release_reference(struct bpf_verifier_env *env, int id) 8913 { 8914 u32 mask = (1 << STACK_SPILL) | (1 << STACK_DYNPTR); 8915 struct bpf_verifier_state *vstate = env->cur_state; 8916 struct bpf_idmap *idstack = &env->idmap_scratch; 8917 struct bpf_stack_state *stack; 8918 struct bpf_func_state *state; 8919 struct bpf_reg_state *reg; 8920 int i, err; 8921 8922 idstack->cnt = 0; 8923 err = idstack_push(idstack, id); 8924 if (err) 8925 return err; 8926 8927 if (find_reference_state(vstate, id)) 8928 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 8929 8930 while ((id = idstack_pop(idstack))) { 8931 /* 8932 * Child references are inaccessible after parent is released, 8933 * any child references that exist at this point are a leak. 8934 */ 8935 for (i = 0; i < vstate->acquired_refs; i++) { 8936 if (vstate->refs[i].type != REF_TYPE_PTR) 8937 continue; 8938 if (vstate->refs[i].parent_id != id) 8939 continue; 8940 verbose(env, "Leaking reference id=%d alloc_insn=%d. Release it first.\n", 8941 vstate->refs[i].id, vstate->refs[i].insn_idx); 8942 return -EINVAL; 8943 } 8944 8945 bpf_for_each_reg_in_vstate_mask(vstate, state, reg, stack, mask, ({ 8946 if (reg->id != id && reg->parent_id != id) 8947 continue; 8948 8949 /* Free objects derived from the current object */ 8950 if (reg->parent_id == id) { 8951 err = idstack_push(idstack, reg->id); 8952 if (err) 8953 return err; 8954 } 8955 8956 if (!stack || stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL) 8957 mark_reg_invalid(env, reg); 8958 else if (stack->slot_type[BPF_REG_SIZE - 1] == STACK_DYNPTR) 8959 invalidate_dynptr(env, stack); 8960 })); 8961 } 8962 8963 return 0; 8964 } 8965 8966 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 8967 { 8968 struct bpf_func_state *unused; 8969 struct bpf_reg_state *reg; 8970 8971 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 8972 if (type_is_non_owning_ref(reg->type)) 8973 mark_reg_invalid(env, reg); 8974 })); 8975 } 8976 8977 static void invalidate_rcu_protected_refs(struct bpf_verifier_env *env) 8978 { 8979 struct bpf_stack_state *stack; 8980 struct bpf_func_state *state; 8981 struct bpf_reg_state *reg; 8982 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 8983 8984 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, stack, clear_mask, ({ 8985 if (reg->type & MEM_RCU) { 8986 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 8987 reg->type |= PTR_UNTRUSTED; 8988 } 8989 })); 8990 } 8991 8992 static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id) 8993 { 8994 struct bpf_func_state *state; 8995 struct bpf_reg_state *reg; 8996 int err; 8997 8998 err = release_reference_nomark(env->cur_state, id); 8999 9000 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9001 if (reg->id != id) 9002 continue; 9003 if ((reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 9004 reg->id = 0; 9005 reg->type &= ~MEM_ALLOC; 9006 reg->type |= MEM_RCU; 9007 } 9008 })); 9009 9010 return err; 9011 } 9012 9013 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9014 struct bpf_reg_state *regs) 9015 { 9016 int i; 9017 9018 /* after the call registers r0 - r5 were scratched */ 9019 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9020 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 9021 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9022 } 9023 } 9024 9025 static void invalidate_outgoing_stack_args(const struct bpf_verifier_env *env, 9026 struct bpf_func_state *state) 9027 { 9028 int i, nslots = state->out_stack_arg_cnt; 9029 9030 for (i = 0; i < nslots; i++) 9031 bpf_mark_reg_not_init(env, &state->stack_arg_regs[i]); 9032 } 9033 9034 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9035 struct bpf_func_state *caller, 9036 struct bpf_func_state *callee, 9037 int insn_idx); 9038 9039 static int set_callee_state(struct bpf_verifier_env *env, 9040 struct bpf_func_state *caller, 9041 struct bpf_func_state *callee, int insn_idx); 9042 9043 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9044 set_callee_state_fn set_callee_state_cb, 9045 struct bpf_verifier_state *state) 9046 { 9047 struct bpf_func_state *caller, *callee; 9048 int err; 9049 9050 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9051 verbose(env, "the call stack of %d frames is too deep\n", 9052 state->curframe + 2); 9053 return -E2BIG; 9054 } 9055 9056 if (state->frame[state->curframe + 1]) { 9057 verifier_bug(env, "Frame %d already allocated", state->curframe + 1); 9058 return -EFAULT; 9059 } 9060 9061 caller = state->frame[state->curframe]; 9062 callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT); 9063 if (!callee) 9064 return -ENOMEM; 9065 state->frame[state->curframe + 1] = callee; 9066 9067 /* callee cannot access r0, r6 - r9 for reading and has to write 9068 * into its own stack before reading from it. 9069 * callee can read/write into caller's stack 9070 */ 9071 init_func_state(env, callee, 9072 /* remember the callsite, it will be used by bpf_exit */ 9073 callsite, 9074 state->curframe + 1 /* frameno within this callchain */, 9075 subprog /* subprog number within this prog */); 9076 err = set_callee_state_cb(env, caller, callee, callsite); 9077 if (err) 9078 goto err_out; 9079 9080 /* only increment it after check_reg_arg() finished */ 9081 state->curframe++; 9082 9083 return 0; 9084 9085 err_out: 9086 free_func_state(callee); 9087 state->frame[state->curframe + 1] = NULL; 9088 return err; 9089 } 9090 9091 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9092 const struct btf *btf, 9093 struct bpf_reg_state *regs) 9094 { 9095 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9096 struct bpf_func_state *caller = cur_func(env); 9097 struct bpf_verifier_log *log = &env->log; 9098 struct ref_obj_desc ref_obj = {}; 9099 u32 i; 9100 int ret, err; 9101 9102 ret = btf_prepare_func_args(env, subprog); 9103 if (ret) { 9104 if (bpf_in_stack_arg_cnt(sub) > 0) { 9105 err = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9106 if (err) 9107 return err; 9108 } 9109 return ret; 9110 } 9111 9112 ret = check_outgoing_stack_args(env, caller, sub->arg_cnt); 9113 if (ret) 9114 return ret; 9115 9116 /* check that BTF function arguments match actual types that the 9117 * verifier sees. 9118 */ 9119 for (i = 0; i < sub->arg_cnt; i++) { 9120 argno_t argno = argno_from_arg(i + 1); 9121 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 9122 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9123 9124 if (arg->arg_type == ARG_ANYTHING) { 9125 if (reg->type != SCALAR_VALUE) { 9126 bpf_log(log, "%s is not a scalar\n", reg_arg_name(env, argno)); 9127 return -EINVAL; 9128 } 9129 } else if (arg->arg_type & PTR_UNTRUSTED) { 9130 /* 9131 * Anything is allowed for untrusted arguments, as these are 9132 * read-only and probe read instructions would protect against 9133 * invalid memory access. 9134 */ 9135 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9136 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_CTX); 9137 if (ret < 0) 9138 return ret; 9139 /* If function expects ctx type in BTF check that caller 9140 * is passing PTR_TO_CTX. 9141 */ 9142 if (reg->type != PTR_TO_CTX) { 9143 bpf_log(log, "%s expects pointer to ctx\n", 9144 reg_arg_name(env, argno)); 9145 return -EINVAL; 9146 } 9147 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9148 ret = check_func_arg_reg_off(env, reg, argno, ARG_DONTCARE); 9149 if (ret < 0) 9150 return ret; 9151 if (check_mem_reg(env, reg, argno, arg->mem_size)) 9152 return -EINVAL; 9153 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9154 bpf_log(log, "%s is expected to be non-NULL\n", 9155 reg_arg_name(env, argno)); 9156 return -EINVAL; 9157 } 9158 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9159 /* 9160 * Can pass any value and the kernel won't crash, but 9161 * only PTR_TO_ARENA or SCALAR make sense. Everything 9162 * else is a bug in the bpf program. Point it out to 9163 * the user at the verification time instead of 9164 * run-time debug nightmare. 9165 */ 9166 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9167 bpf_log(log, "%s is not a pointer to arena or scalar.\n", 9168 reg_arg_name(env, argno)); 9169 return -EINVAL; 9170 } 9171 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 9172 ret = check_func_arg_reg_off(env, reg, argno, ARG_PTR_TO_DYNPTR); 9173 if (ret) 9174 return ret; 9175 9176 ret = process_dynptr_func(env, reg, argno, -1, arg->arg_type, &ref_obj, NULL); 9177 if (ret) 9178 return ret; 9179 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9180 struct bpf_call_arg_meta meta; 9181 int err; 9182 9183 if (bpf_register_is_null(reg) && type_may_be_null(arg->arg_type)) 9184 continue; 9185 9186 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9187 err = check_reg_type(env, reg, argno, arg->arg_type, &arg->btf_id, &meta); 9188 err = err ?: check_func_arg_reg_off(env, reg, argno, arg->arg_type); 9189 if (err) 9190 return err; 9191 } else { 9192 verifier_bug(env, "unrecognized %s type %d", 9193 reg_arg_name(env, argno), arg->arg_type); 9194 return -EFAULT; 9195 } 9196 } 9197 9198 return 0; 9199 } 9200 9201 /* Compare BTF of a function call with given bpf_reg_state. 9202 * Returns: 9203 * EFAULT - there is a verifier bug. Abort verification. 9204 * EINVAL - there is a type mismatch or BTF is not available. 9205 * 0 - BTF matches with what bpf_reg_state expects. 9206 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9207 */ 9208 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9209 struct bpf_reg_state *regs) 9210 { 9211 struct bpf_prog *prog = env->prog; 9212 struct btf *btf = prog->aux->btf; 9213 u32 btf_id; 9214 int err; 9215 9216 if (!prog->aux->func_info) 9217 return -EINVAL; 9218 9219 btf_id = prog->aux->func_info[subprog].type_id; 9220 if (!btf_id) 9221 return -EFAULT; 9222 9223 if (prog->aux->func_info_aux[subprog].unreliable) 9224 return -EINVAL; 9225 9226 err = btf_check_func_arg_match(env, subprog, btf, regs); 9227 /* Compiler optimizations can remove arguments from static functions 9228 * or mismatched type can be passed into a global function. 9229 * In such cases mark the function as unreliable from BTF point of view. 9230 */ 9231 if (err) 9232 prog->aux->func_info_aux[subprog].unreliable = true; 9233 return err; 9234 } 9235 9236 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9237 int insn_idx, int subprog, 9238 set_callee_state_fn set_callee_state_cb) 9239 { 9240 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9241 struct bpf_func_state *caller, *callee; 9242 int err; 9243 9244 caller = state->frame[state->curframe]; 9245 err = btf_check_subprog_call(env, subprog, caller->regs); 9246 if (err == -EFAULT) 9247 return err; 9248 9249 /* set_callee_state is used for direct subprog calls, but we are 9250 * interested in validating only BPF helpers that can call subprogs as 9251 * callbacks 9252 */ 9253 env->subprog_info[subprog].is_cb = true; 9254 if (bpf_pseudo_kfunc_call(insn) && 9255 !is_callback_calling_kfunc(insn->imm)) { 9256 verifier_bug(env, "kfunc %s#%d not marked as callback-calling", 9257 func_id_name(insn->imm), insn->imm); 9258 return -EFAULT; 9259 } else if (!bpf_pseudo_kfunc_call(insn) && 9260 !is_callback_calling_function(insn->imm)) { /* helper */ 9261 verifier_bug(env, "helper %s#%d not marked as callback-calling", 9262 func_id_name(insn->imm), insn->imm); 9263 return -EFAULT; 9264 } 9265 9266 if (bpf_is_async_callback_calling_insn(insn)) { 9267 struct bpf_verifier_state *async_cb; 9268 9269 /* there is no real recursion here. timer and workqueue callbacks are async */ 9270 env->subprog_info[subprog].is_async_cb = true; 9271 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9272 insn_idx, subprog, 9273 is_async_cb_sleepable(env, insn)); 9274 if (IS_ERR(async_cb)) 9275 return PTR_ERR(async_cb); 9276 callee = async_cb->frame[0]; 9277 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9278 9279 /* Convert bpf_timer_set_callback() args into timer callback args */ 9280 err = set_callee_state_cb(env, caller, callee, insn_idx); 9281 if (err) 9282 return err; 9283 9284 return 0; 9285 } 9286 9287 /* for callback functions enqueue entry to callback and 9288 * proceed with next instruction within current frame. 9289 */ 9290 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9291 if (IS_ERR(callback_state)) 9292 return PTR_ERR(callback_state); 9293 9294 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9295 callback_state); 9296 if (err) 9297 return err; 9298 9299 callback_state->callback_unroll_depth++; 9300 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9301 caller->callback_depth = 0; 9302 return 0; 9303 } 9304 9305 static int process_bpf_exit_full(struct bpf_verifier_env *env, 9306 bool *do_print_state, bool exception_exit); 9307 9308 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9309 int *insn_idx) 9310 { 9311 struct bpf_verifier_state *state = env->cur_state; 9312 struct bpf_subprog_info *caller_info; 9313 u16 callee_incoming, stack_arg_cnt; 9314 struct bpf_func_state *caller; 9315 int err, subprog, target_insn; 9316 9317 target_insn = *insn_idx + insn->imm + 1; 9318 subprog = bpf_find_subprog(env, target_insn); 9319 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program", 9320 target_insn)) 9321 return -EFAULT; 9322 9323 caller = state->frame[state->curframe]; 9324 err = btf_check_subprog_call(env, subprog, caller->regs); 9325 if (err == -EFAULT) 9326 return err; 9327 if (bpf_subprog_is_global(env, subprog)) { 9328 const char *sub_name = subprog_name(env, subprog); 9329 9330 if (env->cur_state->active_locks) { 9331 verbose(env, "global function calls are not allowed while holding a lock,\n" 9332 "use static function instead\n"); 9333 return -EINVAL; 9334 } 9335 9336 if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) { 9337 verbose(env, "sleepable global function %s() called in %s\n", 9338 sub_name, non_sleepable_context_description(env)); 9339 return -EINVAL; 9340 } 9341 9342 if (err) { 9343 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9344 subprog, sub_name); 9345 return err; 9346 } 9347 9348 if (env->log.level & BPF_LOG_LEVEL) 9349 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9350 subprog, sub_name); 9351 if (env->subprog_info[subprog].changes_pkt_data) 9352 clear_all_pkt_pointers(env); 9353 /* mark global subprog for verifying after main prog */ 9354 subprog_aux(env, subprog)->called = true; 9355 clear_caller_saved_regs(env, caller->regs); 9356 invalidate_outgoing_stack_args(env, cur_func(env)); 9357 9358 /* All non-void global functions return a 64-bit SCALAR_VALUE. */ 9359 if (!subprog_returns_void(env, subprog)) { 9360 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9361 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9362 } 9363 9364 if (env->subprog_info[subprog].might_throw) { 9365 struct bpf_verifier_state *branch; 9366 9367 branch = push_stack(env, *insn_idx + 1, *insn_idx, false); 9368 if (IS_ERR(branch)) { 9369 verbose(env, "failed to push state for global subprog exception path\n"); 9370 return PTR_ERR(branch); 9371 } 9372 return process_bpf_exit_full(env, NULL, true); 9373 } 9374 9375 /* continue with next insn after call */ 9376 return 0; 9377 } 9378 9379 /* 9380 * Track caller's total stack arg count (incoming + max outgoing). 9381 * This is needed so the JIT knows how much stack arg space to allocate. 9382 */ 9383 caller_info = &env->subprog_info[caller->subprogno]; 9384 callee_incoming = bpf_in_stack_arg_cnt(&env->subprog_info[subprog]); 9385 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + callee_incoming; 9386 if (stack_arg_cnt > caller_info->stack_arg_cnt) 9387 caller_info->stack_arg_cnt = stack_arg_cnt; 9388 9389 /* for regular function entry setup new frame and continue 9390 * from that frame. 9391 */ 9392 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9393 if (err) 9394 return err; 9395 9396 clear_caller_saved_regs(env, caller->regs); 9397 9398 /* and go analyze first insn of the callee */ 9399 *insn_idx = env->subprog_info[subprog].start - 1; 9400 9401 if (env->log.level & BPF_LOG_LEVEL) { 9402 verbose(env, "caller:\n"); 9403 print_verifier_state(env, state, caller->frameno, true); 9404 verbose(env, "callee:\n"); 9405 print_verifier_state(env, state, state->curframe, true); 9406 } 9407 9408 return 0; 9409 } 9410 9411 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9412 struct bpf_func_state *caller, 9413 struct bpf_func_state *callee) 9414 { 9415 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9416 * void *callback_ctx, u64 flags); 9417 * callback_fn(struct bpf_map *map, void *key, void *value, 9418 * void *callback_ctx); 9419 */ 9420 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9421 9422 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9423 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9424 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9425 9426 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9427 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9428 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9429 9430 /* pointer to stack or null */ 9431 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9432 9433 /* unused */ 9434 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9435 return 0; 9436 } 9437 9438 static int set_callee_state(struct bpf_verifier_env *env, 9439 struct bpf_func_state *caller, 9440 struct bpf_func_state *callee, int insn_idx) 9441 { 9442 int i; 9443 9444 /* copy r1 - r5 args that callee can access. The copy includes parent 9445 * pointers, which connects us up to the liveness chain 9446 */ 9447 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9448 callee->regs[i] = caller->regs[i]; 9449 return 0; 9450 } 9451 9452 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9453 struct bpf_func_state *caller, 9454 struct bpf_func_state *callee, 9455 int insn_idx) 9456 { 9457 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9458 struct bpf_map *map; 9459 int err; 9460 9461 /* valid map_ptr and poison value does not matter */ 9462 map = insn_aux->map_ptr_state.map_ptr; 9463 if (!map->ops->map_set_for_each_callback_args || 9464 !map->ops->map_for_each_callback) { 9465 verbose(env, "callback function not allowed for map\n"); 9466 return -ENOTSUPP; 9467 } 9468 9469 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9470 if (err) 9471 return err; 9472 9473 callee->in_callback_fn = true; 9474 callee->callback_ret_range = retval_range(0, 1); 9475 return 0; 9476 } 9477 9478 static int set_loop_callback_state(struct bpf_verifier_env *env, 9479 struct bpf_func_state *caller, 9480 struct bpf_func_state *callee, 9481 int insn_idx) 9482 { 9483 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9484 * u64 flags); 9485 * callback_fn(u64 index, void *callback_ctx); 9486 */ 9487 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9488 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9489 9490 /* unused */ 9491 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9492 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9493 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9494 9495 callee->in_callback_fn = true; 9496 callee->callback_ret_range = retval_range(0, 1); 9497 return 0; 9498 } 9499 9500 static int set_timer_callback_state(struct bpf_verifier_env *env, 9501 struct bpf_func_state *caller, 9502 struct bpf_func_state *callee, 9503 int insn_idx) 9504 { 9505 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9506 9507 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9508 * callback_fn(struct bpf_map *map, void *key, void *value); 9509 */ 9510 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9511 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9512 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9513 9514 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9515 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9516 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9517 9518 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9519 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9520 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9521 9522 /* unused */ 9523 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9524 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9525 callee->in_async_callback_fn = true; 9526 callee->callback_ret_range = retval_range(0, 0); 9527 return 0; 9528 } 9529 9530 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9531 struct bpf_func_state *caller, 9532 struct bpf_func_state *callee, 9533 int insn_idx) 9534 { 9535 /* bpf_find_vma(struct task_struct *task, u64 addr, 9536 * void *callback_fn, void *callback_ctx, u64 flags) 9537 * (callback_fn)(struct task_struct *task, 9538 * struct vm_area_struct *vma, void *callback_ctx); 9539 */ 9540 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9541 9542 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9543 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9544 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9545 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9546 9547 /* pointer to stack or null */ 9548 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9549 9550 /* unused */ 9551 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9552 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9553 callee->in_callback_fn = true; 9554 callee->callback_ret_range = retval_range(0, 1); 9555 return 0; 9556 } 9557 9558 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9559 struct bpf_func_state *caller, 9560 struct bpf_func_state *callee, 9561 int insn_idx) 9562 { 9563 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9564 * callback_ctx, u64 flags); 9565 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9566 */ 9567 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9568 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9569 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9570 9571 /* unused */ 9572 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9573 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9574 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9575 9576 callee->in_callback_fn = true; 9577 callee->callback_ret_range = retval_range(0, 1); 9578 return 0; 9579 } 9580 9581 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9582 struct bpf_func_state *caller, 9583 struct bpf_func_state *callee, 9584 int insn_idx) 9585 { 9586 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9587 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9588 * 9589 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9590 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9591 * by this point, so look at 'root' 9592 */ 9593 struct btf_field *field; 9594 9595 field = reg_find_field_offset(&caller->regs[BPF_REG_1], 9596 caller->regs[BPF_REG_1].var_off.value, 9597 BPF_RB_ROOT); 9598 if (!field || !field->graph_root.value_btf_id) 9599 return -EFAULT; 9600 9601 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9602 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9603 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9604 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9605 9606 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9607 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9608 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9609 callee->in_callback_fn = true; 9610 callee->callback_ret_range = retval_range(0, 1); 9611 return 0; 9612 } 9613 9614 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env, 9615 struct bpf_func_state *caller, 9616 struct bpf_func_state *callee, 9617 int insn_idx) 9618 { 9619 struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr; 9620 9621 /* 9622 * callback_fn(struct bpf_map *map, void *key, void *value); 9623 */ 9624 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9625 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9626 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9627 9628 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9629 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9630 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9631 9632 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9633 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9634 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9635 9636 /* unused */ 9637 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9638 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9639 callee->in_async_callback_fn = true; 9640 callee->callback_ret_range = retval_range(S32_MIN, S32_MAX); 9641 return 0; 9642 } 9643 9644 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9645 9646 /* Are we currently verifying the callback for a rbtree helper that must 9647 * be called with lock held? If so, no need to complain about unreleased 9648 * lock 9649 */ 9650 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9651 { 9652 struct bpf_verifier_state *state = env->cur_state; 9653 struct bpf_insn *insn = env->prog->insnsi; 9654 struct bpf_func_state *callee; 9655 int kfunc_btf_id; 9656 9657 if (!state->curframe) 9658 return false; 9659 9660 callee = state->frame[state->curframe]; 9661 9662 if (!callee->in_callback_fn) 9663 return false; 9664 9665 kfunc_btf_id = insn[callee->callsite].imm; 9666 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9667 } 9668 9669 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9670 { 9671 if (range.return_32bit) 9672 return range.minval <= reg_s32_min(reg) && reg_s32_max(reg) <= range.maxval; 9673 else 9674 return range.minval <= reg_smin(reg) && reg_smax(reg) <= range.maxval; 9675 } 9676 9677 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9678 { 9679 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9680 struct bpf_func_state *caller, *callee; 9681 struct bpf_reg_state *r0; 9682 bool in_callback_fn; 9683 int err; 9684 9685 callee = state->frame[state->curframe]; 9686 r0 = &callee->regs[BPF_REG_0]; 9687 if (r0->type == PTR_TO_STACK) { 9688 /* technically it's ok to return caller's stack pointer 9689 * (or caller's caller's pointer) back to the caller, 9690 * since these pointers are valid. Only current stack 9691 * pointer will be invalid as soon as function exits, 9692 * but let's be conservative 9693 */ 9694 verbose(env, "cannot return stack pointer to the caller\n"); 9695 return -EINVAL; 9696 } 9697 9698 caller = state->frame[state->curframe - 1]; 9699 if (callee->in_callback_fn) { 9700 if (r0->type != SCALAR_VALUE) { 9701 verbose(env, "R0 not a scalar value\n"); 9702 return -EACCES; 9703 } 9704 9705 /* we are going to rely on register's precise value */ 9706 err = mark_chain_precision(env, BPF_REG_0); 9707 if (err) 9708 return err; 9709 9710 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 9711 if (!retval_range_within(callee->callback_ret_range, r0)) { 9712 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9713 "At callback return", "R0"); 9714 return -EINVAL; 9715 } 9716 if (!bpf_calls_callback(env, callee->callsite)) { 9717 verifier_bug(env, "in callback at %d, callsite %d !calls_callback", 9718 *insn_idx, callee->callsite); 9719 return -EFAULT; 9720 } 9721 } else { 9722 /* return to the caller whatever r0 had in the callee */ 9723 caller->regs[BPF_REG_0] = *r0; 9724 } 9725 9726 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9727 * there function call logic would reschedule callback visit. If iteration 9728 * converges is_state_visited() would prune that visit eventually. 9729 */ 9730 in_callback_fn = callee->in_callback_fn; 9731 if (in_callback_fn) 9732 *insn_idx = callee->callsite; 9733 else 9734 *insn_idx = callee->callsite + 1; 9735 9736 if (env->log.level & BPF_LOG_LEVEL) { 9737 verbose(env, "returning from callee:\n"); 9738 print_verifier_state(env, state, callee->frameno, true); 9739 verbose(env, "to caller at %d:\n", *insn_idx); 9740 print_verifier_state(env, state, caller->frameno, true); 9741 } 9742 /* clear everything in the callee. In case of exceptional exits using 9743 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9744 free_func_state(callee); 9745 state->frame[state->curframe--] = NULL; 9746 invalidate_outgoing_stack_args(env, caller); 9747 9748 /* for callbacks widen imprecise scalars to make programs like below verify: 9749 * 9750 * struct ctx { int i; } 9751 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9752 * ... 9753 * struct ctx = { .i = 0; } 9754 * bpf_loop(100, cb, &ctx, 0); 9755 * 9756 * This is similar to what is done in process_iter_next_call() for open 9757 * coded iterators. 9758 */ 9759 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9760 if (prev_st) { 9761 err = widen_imprecise_scalars(env, prev_st, state); 9762 if (err) 9763 return err; 9764 } 9765 return 0; 9766 } 9767 9768 static int do_refine_retval_range(struct bpf_verifier_env *env, 9769 struct bpf_reg_state *regs, int ret_type, 9770 int func_id, 9771 struct bpf_call_arg_meta *meta) 9772 { 9773 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9774 9775 if (ret_type != RET_INTEGER) 9776 return 0; 9777 9778 switch (func_id) { 9779 case BPF_FUNC_get_stack: 9780 case BPF_FUNC_get_task_stack: 9781 case BPF_FUNC_probe_read_str: 9782 case BPF_FUNC_probe_read_kernel_str: 9783 case BPF_FUNC_probe_read_user_str: 9784 reg_set_srange64(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9785 reg_set_srange32(ret_reg, -MAX_ERRNO, meta->msize_max_value); 9786 reg_bounds_sync(ret_reg); 9787 break; 9788 case BPF_FUNC_get_smp_processor_id: 9789 reg_set_urange64(ret_reg, 0, nr_cpu_ids - 1); 9790 reg_set_urange32(ret_reg, 0, nr_cpu_ids - 1); 9791 reg_bounds_sync(ret_reg); 9792 break; 9793 } 9794 9795 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9796 } 9797 9798 static int 9799 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9800 int func_id, int insn_idx) 9801 { 9802 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9803 struct bpf_map *map = meta->map.ptr; 9804 9805 if (func_id != BPF_FUNC_tail_call && 9806 func_id != BPF_FUNC_map_lookup_elem && 9807 func_id != BPF_FUNC_map_update_elem && 9808 func_id != BPF_FUNC_map_delete_elem && 9809 func_id != BPF_FUNC_map_push_elem && 9810 func_id != BPF_FUNC_map_pop_elem && 9811 func_id != BPF_FUNC_map_peek_elem && 9812 func_id != BPF_FUNC_for_each_map_elem && 9813 func_id != BPF_FUNC_redirect_map && 9814 func_id != BPF_FUNC_map_lookup_percpu_elem) 9815 return 0; 9816 9817 if (map == NULL) { 9818 verifier_bug(env, "expected map for helper call"); 9819 return -EFAULT; 9820 } 9821 9822 /* In case of read-only, some additional restrictions 9823 * need to be applied in order to prevent altering the 9824 * state of the map from program side. 9825 */ 9826 if ((map->map_flags & BPF_F_RDONLY_PROG) && 9827 (func_id == BPF_FUNC_map_delete_elem || 9828 func_id == BPF_FUNC_map_update_elem || 9829 func_id == BPF_FUNC_map_push_elem || 9830 func_id == BPF_FUNC_map_pop_elem)) { 9831 verbose(env, "write into map forbidden\n"); 9832 return -EACCES; 9833 } 9834 9835 if (!aux->map_ptr_state.map_ptr) 9836 bpf_map_ptr_store(aux, meta->map.ptr, 9837 !meta->map.ptr->bypass_spec_v1, false); 9838 else if (aux->map_ptr_state.map_ptr != meta->map.ptr) 9839 bpf_map_ptr_store(aux, meta->map.ptr, 9840 !meta->map.ptr->bypass_spec_v1, true); 9841 return 0; 9842 } 9843 9844 static int 9845 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9846 int func_id, int insn_idx) 9847 { 9848 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9849 struct bpf_reg_state *reg; 9850 struct bpf_map *map = meta->map.ptr; 9851 u64 val, max; 9852 int err; 9853 9854 if (func_id != BPF_FUNC_tail_call) 9855 return 0; 9856 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 9857 verbose(env, "expected prog array map for tail call"); 9858 return -EINVAL; 9859 } 9860 9861 reg = reg_state(env, BPF_REG_3); 9862 val = reg->var_off.value; 9863 max = map->max_entries; 9864 9865 if (!(is_reg_const(reg, false) && val < max)) { 9866 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9867 return 0; 9868 } 9869 9870 err = mark_chain_precision(env, BPF_REG_3); 9871 if (err) 9872 return err; 9873 if (bpf_map_key_unseen(aux)) 9874 bpf_map_key_store(aux, val); 9875 else if (!bpf_map_key_poisoned(aux) && 9876 bpf_map_key_immediate(aux) != val) 9877 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 9878 return 0; 9879 } 9880 9881 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 9882 { 9883 struct bpf_verifier_state *state = env->cur_state; 9884 enum bpf_prog_type type = resolve_prog_type(env->prog); 9885 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 9886 bool refs_lingering = false; 9887 int i; 9888 9889 if (!exception_exit && cur_func(env)->frameno) 9890 return 0; 9891 9892 for (i = 0; i < state->acquired_refs; i++) { 9893 if (state->refs[i].type != REF_TYPE_PTR) 9894 continue; 9895 /* Allow struct_ops programs to return a referenced kptr back to 9896 * kernel. Type checks are performed later in check_return_code. 9897 */ 9898 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && 9899 reg->id == state->refs[i].id) 9900 continue; 9901 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 9902 state->refs[i].id, state->refs[i].insn_idx); 9903 refs_lingering = true; 9904 } 9905 return refs_lingering ? -EINVAL : 0; 9906 } 9907 9908 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 9909 { 9910 int err; 9911 9912 if (check_lock && env->cur_state->active_locks) { 9913 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 9914 return -EINVAL; 9915 } 9916 9917 err = check_reference_leak(env, exception_exit); 9918 if (err) { 9919 verbose(env, "%s would lead to reference leak\n", prefix); 9920 return err; 9921 } 9922 9923 if (check_lock && env->cur_state->active_irq_id) { 9924 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix); 9925 return -EINVAL; 9926 } 9927 9928 if (check_lock && env->cur_state->active_rcu_locks) { 9929 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 9930 return -EINVAL; 9931 } 9932 9933 if (check_lock && env->cur_state->active_preempt_locks) { 9934 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 9935 return -EINVAL; 9936 } 9937 9938 return 0; 9939 } 9940 9941 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 9942 struct bpf_reg_state *regs) 9943 { 9944 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 9945 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 9946 struct bpf_map *fmt_map = fmt_reg->map_ptr; 9947 struct bpf_bprintf_data data = {}; 9948 int err, fmt_map_off, num_args; 9949 u64 fmt_addr; 9950 char *fmt; 9951 9952 /* data must be an array of u64 */ 9953 if (data_len_reg->var_off.value % 8) 9954 return -EINVAL; 9955 num_args = data_len_reg->var_off.value / 8; 9956 9957 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 9958 * and map_direct_value_addr is set. 9959 */ 9960 fmt_map_off = fmt_reg->var_off.value; 9961 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 9962 fmt_map_off); 9963 if (err) { 9964 verbose(env, "failed to retrieve map value address\n"); 9965 return -EFAULT; 9966 } 9967 fmt = (char *)(long)fmt_addr + fmt_map_off; 9968 9969 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9970 * can focus on validating the format specifiers. 9971 */ 9972 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9973 if (err < 0) 9974 verbose(env, "Invalid format string\n"); 9975 9976 return err; 9977 } 9978 9979 static int check_get_func_ip(struct bpf_verifier_env *env) 9980 { 9981 enum bpf_prog_type type = resolve_prog_type(env->prog); 9982 int func_id = BPF_FUNC_get_func_ip; 9983 9984 if (type == BPF_PROG_TYPE_TRACING) { 9985 if (!bpf_prog_has_trampoline(env->prog)) { 9986 verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n", 9987 func_id_name(func_id), func_id); 9988 return -ENOTSUPP; 9989 } 9990 return 0; 9991 } else if (type == BPF_PROG_TYPE_KPROBE) { 9992 return 0; 9993 } 9994 9995 verbose(env, "func %s#%d not supported for program type %d\n", 9996 func_id_name(func_id), func_id, type); 9997 return -ENOTSUPP; 9998 } 9999 10000 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env) 10001 { 10002 return &env->insn_aux_data[env->insn_idx]; 10003 } 10004 10005 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10006 { 10007 struct bpf_reg_state *reg = reg_state(env, BPF_REG_4); 10008 bool reg_is_null = bpf_register_is_null(reg); 10009 10010 if (reg_is_null) 10011 mark_chain_precision(env, BPF_REG_4); 10012 10013 return reg_is_null; 10014 } 10015 10016 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10017 { 10018 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10019 10020 if (!state->initialized) { 10021 state->initialized = 1; 10022 state->fit_for_inline = loop_flag_is_zero(env); 10023 state->callback_subprogno = subprogno; 10024 return; 10025 } 10026 10027 if (!state->fit_for_inline) 10028 return; 10029 10030 state->fit_for_inline = (loop_flag_is_zero(env) && 10031 state->callback_subprogno == subprogno); 10032 } 10033 10034 /* Returns whether or not the given map type can potentially elide 10035 * lookup return value nullness check. This is possible if the key 10036 * is statically known. 10037 */ 10038 static bool can_elide_value_nullness(enum bpf_map_type type) 10039 { 10040 switch (type) { 10041 case BPF_MAP_TYPE_ARRAY: 10042 case BPF_MAP_TYPE_PERCPU_ARRAY: 10043 return true; 10044 default: 10045 return false; 10046 } 10047 } 10048 10049 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id, 10050 const struct bpf_func_proto **ptr) 10051 { 10052 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 10053 return -ERANGE; 10054 10055 if (!env->ops->get_func_proto) 10056 return -EINVAL; 10057 10058 *ptr = env->ops->get_func_proto(func_id, env->prog); 10059 return *ptr && (*ptr)->func ? 0 : -EINVAL; 10060 } 10061 10062 /* Check if we're in a sleepable context. */ 10063 static inline bool in_sleepable_context(struct bpf_verifier_env *env) 10064 { 10065 return !env->cur_state->active_rcu_locks && 10066 !env->cur_state->active_preempt_locks && 10067 !env->cur_state->active_locks && 10068 !env->cur_state->active_irq_id && 10069 in_sleepable(env); 10070 } 10071 10072 static const char *non_sleepable_context_description(struct bpf_verifier_env *env) 10073 { 10074 if (env->cur_state->active_rcu_locks) 10075 return "rcu_read_lock region"; 10076 if (env->cur_state->active_preempt_locks) 10077 return "non-preemptible region"; 10078 if (env->cur_state->active_irq_id) 10079 return "IRQ-disabled region"; 10080 if (env->cur_state->active_locks) 10081 return "lock region"; 10082 return "non-sleepable prog"; 10083 } 10084 10085 static int release_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 10086 bool convert_rcu, bool release_dynptr) 10087 { 10088 int err = -EINVAL; 10089 10090 if (bpf_register_is_null(reg)) 10091 return 0; 10092 10093 if (release_dynptr) 10094 err = unmark_stack_slots_dynptr(env, reg); 10095 else if (convert_rcu) 10096 err = ref_convert_alloc_rcu_protected(env, reg->id); 10097 else if (reg_is_referenced(env, reg)) 10098 err = release_reference(env, reg->id); 10099 10100 return err; 10101 } 10102 10103 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10104 int *insn_idx_p) 10105 { 10106 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10107 bool returns_cpu_specific_alloc_ptr = false; 10108 const struct bpf_func_proto *fn = NULL; 10109 enum bpf_return_type ret_type; 10110 enum bpf_type_flag ret_flag; 10111 struct bpf_reg_state *regs; 10112 struct bpf_call_arg_meta meta; 10113 int insn_idx = *insn_idx_p; 10114 bool changes_data; 10115 int i, err, func_id; 10116 10117 /* find function prototype */ 10118 func_id = insn->imm; 10119 err = bpf_get_helper_proto(env, insn->imm, &fn); 10120 if (err == -ERANGE) { 10121 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 10122 return -EINVAL; 10123 } 10124 10125 if (err) { 10126 verbose(env, "program of this type cannot use helper %s#%d\n", 10127 func_id_name(func_id), func_id); 10128 return err; 10129 } 10130 10131 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10132 if (!env->prog->gpl_compatible && fn->gpl_only) { 10133 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10134 return -EINVAL; 10135 } 10136 10137 if (fn->allowed && !fn->allowed(env->prog)) { 10138 verbose(env, "helper call is not allowed in probe\n"); 10139 return -EINVAL; 10140 } 10141 10142 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10143 changes_data = bpf_helper_changes_pkt_data(func_id); 10144 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10145 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id); 10146 return -EFAULT; 10147 } 10148 10149 memset(&meta, 0, sizeof(meta)); 10150 meta.pkt_access = fn->pkt_access; 10151 10152 err = check_func_proto(fn, &meta); 10153 if (err) { 10154 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id); 10155 return err; 10156 } 10157 10158 if (fn->might_sleep && !in_sleepable_context(env)) { 10159 verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id, 10160 non_sleepable_context_description(env)); 10161 return -EINVAL; 10162 } 10163 10164 /* Track non-sleepable context for helpers. */ 10165 if (!in_sleepable_context(env)) 10166 env->insn_aux_data[insn_idx].non_sleepable = true; 10167 10168 meta.func_id = func_id; 10169 /* check args */ 10170 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10171 err = check_func_arg(env, i, &meta, fn, insn_idx); 10172 if (err) 10173 return err; 10174 } 10175 10176 err = record_func_map(env, &meta, func_id, insn_idx); 10177 if (err) 10178 return err; 10179 10180 err = record_func_key(env, &meta, func_id, insn_idx); 10181 if (err) 10182 return err; 10183 10184 regs = cur_regs(env); 10185 10186 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10187 * is inferred from register state. 10188 */ 10189 for (i = 0; i < meta.access_size; i++) { 10190 err = check_mem_access(env, insn_idx, regs + meta.regno, argno_from_reg(meta.regno), i, BPF_B, 10191 BPF_WRITE, -1, false, false); 10192 if (err) 10193 return err; 10194 } 10195 10196 if (meta.release_regno) { 10197 struct bpf_reg_state *reg = ®s[meta.release_regno]; 10198 bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) && 10199 (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU); 10200 10201 err = release_reg(env, reg, convert_rcu, !!meta.dynptr.id); 10202 if (err) 10203 return err; 10204 } 10205 10206 switch (func_id) { 10207 case BPF_FUNC_tail_call: 10208 err = check_resource_leak(env, false, true, "tail_call"); 10209 if (err) 10210 return err; 10211 break; 10212 case BPF_FUNC_get_local_storage: 10213 /* check that flags argument in get_local_storage(map, flags) is 0, 10214 * this is required because get_local_storage() can't return an error. 10215 */ 10216 if (!bpf_register_is_null(®s[BPF_REG_2])) { 10217 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10218 return -EINVAL; 10219 } 10220 break; 10221 case BPF_FUNC_for_each_map_elem: 10222 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10223 set_map_elem_callback_state); 10224 break; 10225 case BPF_FUNC_timer_set_callback: 10226 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10227 set_timer_callback_state); 10228 break; 10229 case BPF_FUNC_find_vma: 10230 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10231 set_find_vma_callback_state); 10232 break; 10233 case BPF_FUNC_snprintf: 10234 err = check_bpf_snprintf_call(env, regs); 10235 break; 10236 case BPF_FUNC_loop: 10237 update_loop_inline_state(env, meta.subprogno); 10238 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10239 * is finished, thus mark it precise. 10240 */ 10241 err = mark_chain_precision(env, BPF_REG_1); 10242 if (err) 10243 return err; 10244 if (cur_func(env)->callback_depth < reg_umax(®s[BPF_REG_1])) { 10245 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10246 set_loop_callback_state); 10247 } else { 10248 cur_func(env)->callback_depth = 0; 10249 if (env->log.level & BPF_LOG_LEVEL2) 10250 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10251 env->cur_state->curframe); 10252 } 10253 break; 10254 case BPF_FUNC_dynptr_from_mem: 10255 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10256 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10257 reg_type_str(env, regs[BPF_REG_1].type)); 10258 return -EACCES; 10259 } 10260 break; 10261 case BPF_FUNC_set_retval: 10262 if (prog_type == BPF_PROG_TYPE_LSM && 10263 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10264 if (!env->prog->aux->attach_func_proto->type) { 10265 /* Make sure programs that attach to void 10266 * hooks don't try to modify return value. 10267 */ 10268 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10269 return -EINVAL; 10270 } 10271 } 10272 break; 10273 case BPF_FUNC_dynptr_write: 10274 { 10275 enum bpf_dynptr_type dynptr_type = meta.dynptr.type; 10276 10277 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10278 return -EFAULT; 10279 10280 if (dynptr_type == BPF_DYNPTR_TYPE_SKB || 10281 dynptr_type == BPF_DYNPTR_TYPE_SKB_META) 10282 /* this will trigger clear_all_pkt_pointers(), which will 10283 * invalidate all dynptr slices associated with the skb 10284 */ 10285 changes_data = true; 10286 10287 break; 10288 } 10289 case BPF_FUNC_per_cpu_ptr: 10290 case BPF_FUNC_this_cpu_ptr: 10291 { 10292 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10293 const struct btf_type *type; 10294 10295 if (reg->type & MEM_RCU) { 10296 type = btf_type_by_id(reg->btf, reg->btf_id); 10297 if (!type || !btf_type_is_struct(type)) { 10298 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10299 return -EFAULT; 10300 } 10301 returns_cpu_specific_alloc_ptr = true; 10302 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10303 } 10304 break; 10305 } 10306 case BPF_FUNC_user_ringbuf_drain: 10307 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10308 set_user_ringbuf_callback_state); 10309 break; 10310 } 10311 10312 if (err) 10313 return err; 10314 10315 /* reset caller saved regs */ 10316 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10317 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 10318 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10319 } 10320 invalidate_outgoing_stack_args(env, cur_func(env)); 10321 10322 /* helper call returns 64-bit value. */ 10323 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10324 10325 /* update return register (already marked as written above) */ 10326 ret_type = fn->ret_type; 10327 ret_flag = type_flag(ret_type); 10328 10329 switch (base_type(ret_type)) { 10330 case RET_INTEGER: 10331 /* sets type to SCALAR_VALUE */ 10332 mark_reg_unknown(env, regs, BPF_REG_0); 10333 break; 10334 case RET_VOID: 10335 regs[BPF_REG_0].type = NOT_INIT; 10336 break; 10337 case RET_PTR_TO_MAP_VALUE: 10338 /* There is no offset yet applied, variable or fixed */ 10339 mark_reg_known_zero(env, regs, BPF_REG_0); 10340 /* remember map_ptr, so that check_map_access() 10341 * can check 'value_size' boundary of memory access 10342 * to map element returned from bpf_map_lookup_elem() 10343 */ 10344 if (meta.map.ptr == NULL) { 10345 verifier_bug(env, "unexpected null map_ptr"); 10346 return -EFAULT; 10347 } 10348 10349 if (func_id == BPF_FUNC_map_lookup_elem && 10350 can_elide_value_nullness(meta.map.ptr->map_type) && 10351 meta.const_map_key >= 0 && 10352 meta.const_map_key < meta.map.ptr->max_entries) 10353 ret_flag &= ~PTR_MAYBE_NULL; 10354 10355 regs[BPF_REG_0].map_ptr = meta.map.ptr; 10356 regs[BPF_REG_0].map_uid = meta.map.uid; 10357 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10358 if (!type_may_be_null(ret_flag) && 10359 btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 10360 regs[BPF_REG_0].id = ++env->id_gen; 10361 } 10362 break; 10363 case RET_PTR_TO_SOCKET: 10364 mark_reg_known_zero(env, regs, BPF_REG_0); 10365 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10366 break; 10367 case RET_PTR_TO_SOCK_COMMON: 10368 mark_reg_known_zero(env, regs, BPF_REG_0); 10369 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10370 break; 10371 case RET_PTR_TO_TCP_SOCK: 10372 mark_reg_known_zero(env, regs, BPF_REG_0); 10373 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10374 break; 10375 case RET_PTR_TO_MEM: 10376 mark_reg_known_zero(env, regs, BPF_REG_0); 10377 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10378 regs[BPF_REG_0].mem_size = meta.mem_size; 10379 break; 10380 case RET_PTR_TO_MEM_OR_BTF_ID: 10381 { 10382 const struct btf_type *t; 10383 10384 mark_reg_known_zero(env, regs, BPF_REG_0); 10385 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10386 if (!btf_type_is_struct(t)) { 10387 u32 tsize; 10388 const struct btf_type *ret; 10389 const char *tname; 10390 10391 /* resolve the type size of ksym. */ 10392 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10393 if (IS_ERR(ret)) { 10394 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10395 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10396 tname, PTR_ERR(ret)); 10397 return -EINVAL; 10398 } 10399 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10400 regs[BPF_REG_0].mem_size = tsize; 10401 } else { 10402 if (returns_cpu_specific_alloc_ptr) { 10403 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10404 } else { 10405 /* MEM_RDONLY may be carried from ret_flag, but it 10406 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10407 * it will confuse the check of PTR_TO_BTF_ID in 10408 * check_mem_access(). 10409 */ 10410 ret_flag &= ~MEM_RDONLY; 10411 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10412 } 10413 10414 regs[BPF_REG_0].btf = meta.ret_btf; 10415 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10416 } 10417 break; 10418 } 10419 case RET_PTR_TO_BTF_ID: 10420 { 10421 struct btf *ret_btf; 10422 int ret_btf_id; 10423 10424 mark_reg_known_zero(env, regs, BPF_REG_0); 10425 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10426 if (func_id == BPF_FUNC_kptr_xchg) { 10427 ret_btf = meta.kptr_field->kptr.btf; 10428 ret_btf_id = meta.kptr_field->kptr.btf_id; 10429 if (!btf_is_kernel(ret_btf)) { 10430 regs[BPF_REG_0].type |= MEM_ALLOC; 10431 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10432 regs[BPF_REG_0].type |= MEM_PERCPU; 10433 } 10434 } else { 10435 if (fn->ret_btf_id == BPF_PTR_POISON) { 10436 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type", 10437 func_id_name(func_id)); 10438 return -EFAULT; 10439 } 10440 ret_btf = btf_vmlinux; 10441 ret_btf_id = *fn->ret_btf_id; 10442 } 10443 if (ret_btf_id == 0) { 10444 verbose(env, "invalid return type %u of func %s#%d\n", 10445 base_type(ret_type), func_id_name(func_id), 10446 func_id); 10447 return -EINVAL; 10448 } 10449 regs[BPF_REG_0].btf = ret_btf; 10450 regs[BPF_REG_0].btf_id = ret_btf_id; 10451 break; 10452 } 10453 default: 10454 verbose(env, "unknown return type %u of func %s#%d\n", 10455 base_type(ret_type), func_id_name(func_id), func_id); 10456 return -EINVAL; 10457 } 10458 10459 if (type_may_be_null(regs[BPF_REG_0].type)) 10460 regs[BPF_REG_0].id = ++env->id_gen; 10461 10462 if (is_ptr_cast_function(func_id) && 10463 find_reference_state(env->cur_state, meta.ref_obj.id)) { 10464 struct bpf_verifier_state *branch; 10465 struct bpf_reg_state *r0; 10466 10467 err = validate_ref_obj(env, &meta.ref_obj); 10468 if (err) 10469 return err; 10470 10471 /* 10472 * In order for a release of any of the original or cast pointers 10473 * to invalidate all other pointers, reuse the same reference id for 10474 * the cast result. 10475 * This reference id can't be used for nullness propagation, 10476 * as cast might return NULL for a non-NULL input. 10477 * Hence, explore the NULL case as a separate branch. 10478 */ 10479 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10480 if (IS_ERR(branch)) 10481 return PTR_ERR(branch); 10482 10483 r0 = &branch->frame[branch->curframe]->regs[BPF_REG_0]; 10484 __mark_reg_known_zero(r0); 10485 r0->type = SCALAR_VALUE; 10486 10487 regs[BPF_REG_0].type &= ~PTR_MAYBE_NULL; 10488 regs[BPF_REG_0].id = meta.ref_obj.id; 10489 } else if (is_acquire_function(func_id, meta.map.ptr)) { 10490 int id = acquire_reference(env, insn_idx, 0); 10491 10492 if (id < 0) 10493 return id; 10494 10495 regs[BPF_REG_0].id = id; 10496 } 10497 10498 if (func_id == BPF_FUNC_dynptr_data) 10499 regs[BPF_REG_0].parent_id = meta.dynptr.id; 10500 10501 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10502 if (err) 10503 return err; 10504 10505 err = check_map_func_compatibility(env, meta.map.ptr, func_id); 10506 if (err) 10507 return err; 10508 10509 if ((func_id == BPF_FUNC_get_stack || 10510 func_id == BPF_FUNC_get_task_stack) && 10511 !env->prog->has_callchain_buf) { 10512 const char *err_str; 10513 10514 #ifdef CONFIG_PERF_EVENTS 10515 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10516 err_str = "cannot get callchain buffer for func %s#%d\n"; 10517 #else 10518 err = -ENOTSUPP; 10519 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10520 #endif 10521 if (err) { 10522 verbose(env, err_str, func_id_name(func_id), func_id); 10523 return err; 10524 } 10525 10526 env->prog->has_callchain_buf = true; 10527 } 10528 10529 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10530 env->prog->call_get_stack = true; 10531 10532 if (func_id == BPF_FUNC_get_func_ip) { 10533 if (check_get_func_ip(env)) 10534 return -ENOTSUPP; 10535 env->prog->call_get_func_ip = true; 10536 } 10537 10538 if (func_id == BPF_FUNC_tail_call) { 10539 if (env->cur_state->curframe) { 10540 struct bpf_verifier_state *branch; 10541 10542 mark_reg_scratched(env, BPF_REG_0); 10543 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10544 if (IS_ERR(branch)) 10545 return PTR_ERR(branch); 10546 clear_all_pkt_pointers(env); 10547 mark_reg_unknown(env, regs, BPF_REG_0); 10548 err = prepare_func_exit(env, &env->insn_idx); 10549 if (err) 10550 return err; 10551 env->insn_idx--; 10552 } else { 10553 changes_data = false; 10554 } 10555 } 10556 10557 if (changes_data) 10558 clear_all_pkt_pointers(env); 10559 return 0; 10560 } 10561 10562 /* mark_btf_func_reg_size() is used when the reg size is determined by 10563 * the BTF func_proto's return value size and argument. 10564 */ 10565 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs, 10566 u32 regno, size_t reg_size) 10567 { 10568 struct bpf_reg_state *reg = ®s[regno]; 10569 10570 if (regno == BPF_REG_0) { 10571 /* Function return value */ 10572 reg->subreg_def = reg_size == sizeof(u64) ? 10573 DEF_NOT_SUBREG : env->insn_idx + 1; 10574 } else if (reg_size == sizeof(u64)) { 10575 /* Function argument */ 10576 mark_insn_zext(env, reg); 10577 } 10578 } 10579 10580 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10581 size_t reg_size) 10582 { 10583 return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size); 10584 } 10585 10586 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10587 { 10588 return meta->kfunc_flags & KF_ACQUIRE; 10589 } 10590 10591 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10592 { 10593 return meta->kfunc_flags & KF_RELEASE; 10594 } 10595 10596 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10597 { 10598 return meta->kfunc_flags & KF_DESTRUCTIVE; 10599 } 10600 10601 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10602 { 10603 return meta->kfunc_flags & KF_RCU; 10604 } 10605 10606 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10607 { 10608 return meta->kfunc_flags & KF_RCU_PROTECTED; 10609 } 10610 10611 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10612 const struct btf_param *arg, 10613 const struct bpf_reg_state *reg) 10614 { 10615 const struct btf_type *t; 10616 10617 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10618 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10619 return false; 10620 10621 return btf_param_match_suffix(btf, arg, "__sz"); 10622 } 10623 10624 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10625 const struct btf_param *arg, 10626 const struct bpf_reg_state *reg) 10627 { 10628 const struct btf_type *t; 10629 10630 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10631 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10632 return false; 10633 10634 return btf_param_match_suffix(btf, arg, "__szk"); 10635 } 10636 10637 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10638 { 10639 return btf_param_match_suffix(btf, arg, "__k"); 10640 } 10641 10642 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10643 { 10644 return btf_param_match_suffix(btf, arg, "__ign"); 10645 } 10646 10647 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 10648 { 10649 return btf_param_match_suffix(btf, arg, "__map"); 10650 } 10651 10652 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10653 { 10654 return btf_param_match_suffix(btf, arg, "__alloc"); 10655 } 10656 10657 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10658 { 10659 return btf_param_match_suffix(btf, arg, "__uninit"); 10660 } 10661 10662 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10663 { 10664 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 10665 } 10666 10667 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10668 { 10669 return btf_param_match_suffix(btf, arg, "__nullable"); 10670 } 10671 10672 static bool is_kfunc_arg_nonown_allowed(const struct btf *btf, const struct btf_param *arg) 10673 { 10674 return btf_param_match_suffix(btf, arg, "__nonown_allowed"); 10675 } 10676 10677 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10678 { 10679 return btf_param_match_suffix(btf, arg, "__str"); 10680 } 10681 10682 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg) 10683 { 10684 return btf_param_match_suffix(btf, arg, "__irq_flag"); 10685 } 10686 10687 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10688 const struct btf_param *arg, 10689 const char *name) 10690 { 10691 int len, target_len = strlen(name); 10692 const char *param_name; 10693 10694 param_name = btf_name_by_offset(btf, arg->name_off); 10695 if (str_is_empty(param_name)) 10696 return false; 10697 len = strlen(param_name); 10698 if (len != target_len) 10699 return false; 10700 if (strcmp(param_name, name)) 10701 return false; 10702 10703 return true; 10704 } 10705 10706 enum { 10707 KF_ARG_DYNPTR_ID, 10708 KF_ARG_LIST_HEAD_ID, 10709 KF_ARG_LIST_NODE_ID, 10710 KF_ARG_RB_ROOT_ID, 10711 KF_ARG_RB_NODE_ID, 10712 KF_ARG_WORKQUEUE_ID, 10713 KF_ARG_RES_SPIN_LOCK_ID, 10714 KF_ARG_TASK_WORK_ID, 10715 KF_ARG_PROG_AUX_ID, 10716 KF_ARG_TIMER_ID 10717 }; 10718 10719 BTF_ID_LIST(kf_arg_btf_ids) 10720 BTF_ID(struct, bpf_dynptr) 10721 BTF_ID(struct, bpf_list_head) 10722 BTF_ID(struct, bpf_list_node) 10723 BTF_ID(struct, bpf_rb_root) 10724 BTF_ID(struct, bpf_rb_node) 10725 BTF_ID(struct, bpf_wq) 10726 BTF_ID(struct, bpf_res_spin_lock) 10727 BTF_ID(struct, bpf_task_work) 10728 BTF_ID(struct, bpf_prog_aux) 10729 BTF_ID(struct, bpf_timer) 10730 10731 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10732 const struct btf_param *arg, int type) 10733 { 10734 const struct btf_type *t; 10735 u32 res_id; 10736 10737 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10738 if (!t) 10739 return false; 10740 if (!btf_type_is_ptr(t)) 10741 return false; 10742 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10743 if (!t) 10744 return false; 10745 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10746 } 10747 10748 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10749 { 10750 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10751 } 10752 10753 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10754 { 10755 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10756 } 10757 10758 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10759 { 10760 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10761 } 10762 10763 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10764 { 10765 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10766 } 10767 10768 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10769 { 10770 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10771 } 10772 10773 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg) 10774 { 10775 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID); 10776 } 10777 10778 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 10779 { 10780 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 10781 } 10782 10783 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg) 10784 { 10785 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID); 10786 } 10787 10788 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg) 10789 { 10790 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID); 10791 } 10792 10793 static bool is_rbtree_node_type(const struct btf_type *t) 10794 { 10795 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]); 10796 } 10797 10798 static bool is_list_node_type(const struct btf_type *t) 10799 { 10800 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]); 10801 } 10802 10803 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10804 const struct btf_param *arg) 10805 { 10806 const struct btf_type *t; 10807 10808 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10809 if (!t) 10810 return false; 10811 10812 return true; 10813 } 10814 10815 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg) 10816 { 10817 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID); 10818 } 10819 10820 /* 10821 * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF: 10822 * - the _impl prototype with full arg list (meta->func_proto) 10823 * - the BPF API prototype w/o implicit args (func->type in BTF) 10824 * To determine whether an argument is implicit, we compare its position 10825 * against the number of arguments in the prototype w/o implicit args. 10826 */ 10827 static bool is_kfunc_arg_implicit(const struct bpf_kfunc_call_arg_meta *meta, u32 arg_idx) 10828 { 10829 const struct btf_type *func, *func_proto; 10830 u32 argn; 10831 10832 if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS)) 10833 return false; 10834 10835 func = btf_type_by_id(meta->btf, meta->func_id); 10836 func_proto = btf_type_by_id(meta->btf, func->type); 10837 argn = btf_type_vlen(func_proto); 10838 10839 return argn <= arg_idx; 10840 } 10841 10842 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10843 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10844 const struct btf *btf, 10845 const struct btf_type *t, int rec) 10846 { 10847 const struct btf_type *member_type; 10848 const struct btf_member *member; 10849 u32 i; 10850 10851 if (!btf_type_is_struct(t)) 10852 return false; 10853 10854 for_each_member(i, t, member) { 10855 const struct btf_array *array; 10856 10857 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10858 if (btf_type_is_struct(member_type)) { 10859 if (rec >= 3) { 10860 verbose(env, "max struct nesting depth exceeded\n"); 10861 return false; 10862 } 10863 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10864 return false; 10865 continue; 10866 } 10867 if (btf_type_is_array(member_type)) { 10868 array = btf_array(member_type); 10869 if (!array->nelems) 10870 return false; 10871 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10872 if (!btf_type_is_scalar(member_type)) 10873 return false; 10874 continue; 10875 } 10876 if (!btf_type_is_scalar(member_type)) 10877 return false; 10878 } 10879 return true; 10880 } 10881 10882 enum kfunc_ptr_arg_type { 10883 KF_ARG_PTR_TO_CTX, 10884 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10885 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10886 KF_ARG_PTR_TO_DYNPTR, 10887 KF_ARG_PTR_TO_ITER, 10888 KF_ARG_PTR_TO_LIST_HEAD, 10889 KF_ARG_PTR_TO_LIST_NODE, 10890 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10891 KF_ARG_PTR_TO_MEM, 10892 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10893 KF_ARG_PTR_TO_CALLBACK, 10894 KF_ARG_PTR_TO_RB_ROOT, 10895 KF_ARG_PTR_TO_RB_NODE, 10896 KF_ARG_PTR_TO_NULL, 10897 KF_ARG_PTR_TO_CONST_STR, 10898 KF_ARG_PTR_TO_MAP, 10899 KF_ARG_PTR_TO_TIMER, 10900 KF_ARG_PTR_TO_WORKQUEUE, 10901 KF_ARG_PTR_TO_IRQ_FLAG, 10902 KF_ARG_PTR_TO_RES_SPIN_LOCK, 10903 KF_ARG_PTR_TO_TASK_WORK, 10904 }; 10905 10906 enum special_kfunc_type { 10907 KF_bpf_obj_new_impl, 10908 KF_bpf_obj_new, 10909 KF_bpf_obj_drop_impl, 10910 KF_bpf_obj_drop, 10911 KF_bpf_refcount_acquire_impl, 10912 KF_bpf_refcount_acquire, 10913 KF_bpf_list_push_front_impl, 10914 KF_bpf_list_push_front, 10915 KF_bpf_list_push_back_impl, 10916 KF_bpf_list_push_back, 10917 KF_bpf_list_add, 10918 KF_bpf_list_pop_front, 10919 KF_bpf_list_pop_back, 10920 KF_bpf_list_del, 10921 KF_bpf_list_front, 10922 KF_bpf_list_back, 10923 KF_bpf_list_is_first, 10924 KF_bpf_list_is_last, 10925 KF_bpf_list_empty, 10926 KF_bpf_cast_to_kern_ctx, 10927 KF_bpf_rdonly_cast, 10928 KF_bpf_rcu_read_lock, 10929 KF_bpf_rcu_read_unlock, 10930 KF_bpf_rbtree_remove, 10931 KF_bpf_rbtree_add_impl, 10932 KF_bpf_rbtree_add, 10933 KF_bpf_rbtree_first, 10934 KF_bpf_rbtree_root, 10935 KF_bpf_rbtree_left, 10936 KF_bpf_rbtree_right, 10937 KF_bpf_dynptr_from_skb, 10938 KF_bpf_dynptr_from_xdp, 10939 KF_bpf_dynptr_from_skb_meta, 10940 KF_bpf_xdp_pull_data, 10941 KF_bpf_dynptr_slice, 10942 KF_bpf_dynptr_slice_rdwr, 10943 KF_bpf_dynptr_clone, 10944 KF_bpf_percpu_obj_new_impl, 10945 KF_bpf_percpu_obj_new, 10946 KF_bpf_percpu_obj_drop_impl, 10947 KF_bpf_percpu_obj_drop, 10948 KF_bpf_throw, 10949 KF_bpf_wq_set_callback, 10950 KF_bpf_preempt_disable, 10951 KF_bpf_preempt_enable, 10952 KF_bpf_iter_css_task_new, 10953 KF_bpf_session_cookie, 10954 KF_bpf_get_kmem_cache, 10955 KF_bpf_local_irq_save, 10956 KF_bpf_local_irq_restore, 10957 KF_bpf_iter_num_new, 10958 KF_bpf_iter_num_next, 10959 KF_bpf_iter_num_destroy, 10960 KF_bpf_set_dentry_xattr, 10961 KF_bpf_remove_dentry_xattr, 10962 KF_bpf_res_spin_lock, 10963 KF_bpf_res_spin_unlock, 10964 KF_bpf_res_spin_lock_irqsave, 10965 KF_bpf_res_spin_unlock_irqrestore, 10966 KF_bpf_dynptr_from_file, 10967 KF_bpf_dynptr_file_discard, 10968 KF___bpf_trap, 10969 KF_bpf_task_work_schedule_signal, 10970 KF_bpf_task_work_schedule_resume, 10971 KF_bpf_arena_alloc_pages, 10972 KF_bpf_arena_free_pages, 10973 KF_bpf_arena_reserve_pages, 10974 KF_bpf_session_is_return, 10975 KF_bpf_stream_vprintk, 10976 KF_bpf_stream_print_stack, 10977 }; 10978 10979 BTF_ID_LIST(special_kfunc_list) 10980 BTF_ID(func, bpf_obj_new_impl) 10981 BTF_ID(func, bpf_obj_new) 10982 BTF_ID(func, bpf_obj_drop_impl) 10983 BTF_ID(func, bpf_obj_drop) 10984 BTF_ID(func, bpf_refcount_acquire_impl) 10985 BTF_ID(func, bpf_refcount_acquire) 10986 BTF_ID(func, bpf_list_push_front_impl) 10987 BTF_ID(func, bpf_list_push_front) 10988 BTF_ID(func, bpf_list_push_back_impl) 10989 BTF_ID(func, bpf_list_push_back) 10990 BTF_ID(func, bpf_list_add) 10991 BTF_ID(func, bpf_list_pop_front) 10992 BTF_ID(func, bpf_list_pop_back) 10993 BTF_ID(func, bpf_list_del) 10994 BTF_ID(func, bpf_list_front) 10995 BTF_ID(func, bpf_list_back) 10996 BTF_ID(func, bpf_list_is_first) 10997 BTF_ID(func, bpf_list_is_last) 10998 BTF_ID(func, bpf_list_empty) 10999 BTF_ID(func, bpf_cast_to_kern_ctx) 11000 BTF_ID(func, bpf_rdonly_cast) 11001 BTF_ID(func, bpf_rcu_read_lock) 11002 BTF_ID(func, bpf_rcu_read_unlock) 11003 BTF_ID(func, bpf_rbtree_remove) 11004 BTF_ID(func, bpf_rbtree_add_impl) 11005 BTF_ID(func, bpf_rbtree_add) 11006 BTF_ID(func, bpf_rbtree_first) 11007 BTF_ID(func, bpf_rbtree_root) 11008 BTF_ID(func, bpf_rbtree_left) 11009 BTF_ID(func, bpf_rbtree_right) 11010 #ifdef CONFIG_NET 11011 BTF_ID(func, bpf_dynptr_from_skb) 11012 BTF_ID(func, bpf_dynptr_from_xdp) 11013 BTF_ID(func, bpf_dynptr_from_skb_meta) 11014 BTF_ID(func, bpf_xdp_pull_data) 11015 #else 11016 BTF_ID_UNUSED 11017 BTF_ID_UNUSED 11018 BTF_ID_UNUSED 11019 BTF_ID_UNUSED 11020 #endif 11021 BTF_ID(func, bpf_dynptr_slice) 11022 BTF_ID(func, bpf_dynptr_slice_rdwr) 11023 BTF_ID(func, bpf_dynptr_clone) 11024 BTF_ID(func, bpf_percpu_obj_new_impl) 11025 BTF_ID(func, bpf_percpu_obj_new) 11026 BTF_ID(func, bpf_percpu_obj_drop_impl) 11027 BTF_ID(func, bpf_percpu_obj_drop) 11028 BTF_ID(func, bpf_throw) 11029 BTF_ID(func, bpf_wq_set_callback) 11030 BTF_ID(func, bpf_preempt_disable) 11031 BTF_ID(func, bpf_preempt_enable) 11032 #ifdef CONFIG_CGROUPS 11033 BTF_ID(func, bpf_iter_css_task_new) 11034 #else 11035 BTF_ID_UNUSED 11036 #endif 11037 #ifdef CONFIG_BPF_EVENTS 11038 BTF_ID(func, bpf_session_cookie) 11039 #else 11040 BTF_ID_UNUSED 11041 #endif 11042 BTF_ID(func, bpf_get_kmem_cache) 11043 BTF_ID(func, bpf_local_irq_save) 11044 BTF_ID(func, bpf_local_irq_restore) 11045 BTF_ID(func, bpf_iter_num_new) 11046 BTF_ID(func, bpf_iter_num_next) 11047 BTF_ID(func, bpf_iter_num_destroy) 11048 #ifdef CONFIG_BPF_LSM 11049 BTF_ID(func, bpf_set_dentry_xattr) 11050 BTF_ID(func, bpf_remove_dentry_xattr) 11051 #else 11052 BTF_ID_UNUSED 11053 BTF_ID_UNUSED 11054 #endif 11055 BTF_ID(func, bpf_res_spin_lock) 11056 BTF_ID(func, bpf_res_spin_unlock) 11057 BTF_ID(func, bpf_res_spin_lock_irqsave) 11058 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 11059 BTF_ID(func, bpf_dynptr_from_file) 11060 BTF_ID(func, bpf_dynptr_file_discard) 11061 BTF_ID(func, __bpf_trap) 11062 BTF_ID(func, bpf_task_work_schedule_signal) 11063 BTF_ID(func, bpf_task_work_schedule_resume) 11064 BTF_ID(func, bpf_arena_alloc_pages) 11065 BTF_ID(func, bpf_arena_free_pages) 11066 BTF_ID(func, bpf_arena_reserve_pages) 11067 #ifdef CONFIG_BPF_EVENTS 11068 BTF_ID(func, bpf_session_is_return) 11069 #else 11070 BTF_ID_UNUSED 11071 #endif 11072 BTF_ID(func, bpf_stream_vprintk) 11073 BTF_ID(func, bpf_stream_print_stack) 11074 11075 static bool is_bpf_obj_new_kfunc(u32 func_id) 11076 { 11077 return func_id == special_kfunc_list[KF_bpf_obj_new] || 11078 func_id == special_kfunc_list[KF_bpf_obj_new_impl]; 11079 } 11080 11081 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id) 11082 { 11083 return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] || 11084 func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]; 11085 } 11086 11087 static bool is_bpf_obj_drop_kfunc(u32 func_id) 11088 { 11089 return func_id == special_kfunc_list[KF_bpf_obj_drop] || 11090 func_id == special_kfunc_list[KF_bpf_obj_drop_impl]; 11091 } 11092 11093 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id) 11094 { 11095 return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] || 11096 func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]; 11097 } 11098 11099 static bool is_bpf_refcount_acquire_kfunc(u32 func_id) 11100 { 11101 return func_id == special_kfunc_list[KF_bpf_refcount_acquire] || 11102 func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11103 } 11104 11105 static bool is_bpf_list_push_kfunc(u32 func_id) 11106 { 11107 return func_id == special_kfunc_list[KF_bpf_list_push_front] || 11108 func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11109 func_id == special_kfunc_list[KF_bpf_list_push_back] || 11110 func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11111 func_id == special_kfunc_list[KF_bpf_list_add]; 11112 } 11113 11114 static bool is_bpf_rbtree_add_kfunc(u32 func_id) 11115 { 11116 return func_id == special_kfunc_list[KF_bpf_rbtree_add] || 11117 func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11118 } 11119 11120 static bool is_task_work_add_kfunc(u32 func_id) 11121 { 11122 return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] || 11123 func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume]; 11124 } 11125 11126 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11127 { 11128 if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref) 11129 return false; 11130 11131 return meta->kfunc_flags & KF_RET_NULL; 11132 } 11133 11134 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11135 { 11136 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11137 } 11138 11139 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11140 { 11141 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11142 } 11143 11144 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11145 { 11146 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11147 } 11148 11149 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11150 { 11151 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11152 } 11153 11154 bool bpf_is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta) 11155 { 11156 return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data]; 11157 } 11158 11159 static enum kfunc_ptr_arg_type 11160 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, struct bpf_func_state *caller, 11161 struct bpf_reg_state *regs, struct bpf_kfunc_call_arg_meta *meta, 11162 const struct btf_type *t, const struct btf_type *ref_t, 11163 const char *ref_tname, const struct btf_param *args, 11164 int arg, int nargs, argno_t argno, struct bpf_reg_state *reg) 11165 { 11166 bool arg_mem_size = false; 11167 11168 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 11169 meta->func_id == special_kfunc_list[KF_bpf_session_is_return] || 11170 meta->func_id == special_kfunc_list[KF_bpf_session_cookie]) 11171 return KF_ARG_PTR_TO_CTX; 11172 11173 if (arg + 1 < nargs && 11174 (is_kfunc_arg_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)) || 11175 is_kfunc_arg_const_mem_size(meta->btf, &args[arg + 1], get_func_arg_reg(caller, regs, arg + 1)))) 11176 arg_mem_size = true; 11177 11178 /* In this function, we verify the kfunc's BTF as per the argument type, 11179 * leaving the rest of the verification with respect to the register 11180 * type to our caller. When a set of conditions hold in the BTF type of 11181 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11182 */ 11183 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), arg)) 11184 return KF_ARG_PTR_TO_CTX; 11185 11186 if (is_kfunc_arg_nullable(meta->btf, &args[arg]) && bpf_register_is_null(reg) && 11187 !arg_mem_size) 11188 return KF_ARG_PTR_TO_NULL; 11189 11190 if (is_kfunc_arg_alloc_obj(meta->btf, &args[arg])) 11191 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11192 11193 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[arg])) 11194 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11195 11196 if (is_kfunc_arg_dynptr(meta->btf, &args[arg])) 11197 return KF_ARG_PTR_TO_DYNPTR; 11198 11199 if (is_kfunc_arg_iter(meta, arg, &args[arg])) 11200 return KF_ARG_PTR_TO_ITER; 11201 11202 if (is_kfunc_arg_list_head(meta->btf, &args[arg])) 11203 return KF_ARG_PTR_TO_LIST_HEAD; 11204 11205 if (is_kfunc_arg_list_node(meta->btf, &args[arg])) 11206 return KF_ARG_PTR_TO_LIST_NODE; 11207 11208 if (is_kfunc_arg_rbtree_root(meta->btf, &args[arg])) 11209 return KF_ARG_PTR_TO_RB_ROOT; 11210 11211 if (is_kfunc_arg_rbtree_node(meta->btf, &args[arg])) 11212 return KF_ARG_PTR_TO_RB_NODE; 11213 11214 if (is_kfunc_arg_const_str(meta->btf, &args[arg])) 11215 return KF_ARG_PTR_TO_CONST_STR; 11216 11217 if (is_kfunc_arg_map(meta->btf, &args[arg])) 11218 return KF_ARG_PTR_TO_MAP; 11219 11220 if (is_kfunc_arg_wq(meta->btf, &args[arg])) 11221 return KF_ARG_PTR_TO_WORKQUEUE; 11222 11223 if (is_kfunc_arg_timer(meta->btf, &args[arg])) 11224 return KF_ARG_PTR_TO_TIMER; 11225 11226 if (is_kfunc_arg_task_work(meta->btf, &args[arg])) 11227 return KF_ARG_PTR_TO_TASK_WORK; 11228 11229 if (is_kfunc_arg_irq_flag(meta->btf, &args[arg])) 11230 return KF_ARG_PTR_TO_IRQ_FLAG; 11231 11232 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[arg])) 11233 return KF_ARG_PTR_TO_RES_SPIN_LOCK; 11234 11235 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11236 if (!btf_type_is_struct(ref_t)) { 11237 verbose(env, "kernel function %s %s pointer type %s %s is not supported\n", 11238 meta->func_name, reg_arg_name(env, argno), 11239 btf_type_str(ref_t), ref_tname); 11240 return -EINVAL; 11241 } 11242 return KF_ARG_PTR_TO_BTF_ID; 11243 } 11244 11245 if (is_kfunc_arg_callback(env, meta->btf, &args[arg])) 11246 return KF_ARG_PTR_TO_CALLBACK; 11247 11248 /* This is the catch all argument type of register types supported by 11249 * check_helper_mem_access. However, we only allow when argument type is 11250 * pointer to scalar, or struct composed (recursively) of scalars. When 11251 * arg_mem_size is true, the pointer can be void *. 11252 */ 11253 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11254 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11255 verbose(env, "%s pointer type %s %s must point to %sscalar, or struct with scalar\n", 11256 reg_arg_name(env, argno), 11257 btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11258 return -EINVAL; 11259 } 11260 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11261 } 11262 11263 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11264 struct bpf_reg_state *reg, 11265 const struct btf_type *ref_t, 11266 const char *ref_tname, u32 ref_id, 11267 struct bpf_kfunc_call_arg_meta *meta, 11268 int arg, argno_t argno) 11269 { 11270 const struct btf_type *reg_ref_t; 11271 bool strict_type_match = false; 11272 const struct btf *reg_btf; 11273 const char *reg_ref_tname; 11274 bool taking_projection; 11275 bool struct_same; 11276 u32 reg_ref_id; 11277 11278 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11279 reg_btf = reg->btf; 11280 reg_ref_id = reg->btf_id; 11281 } else { 11282 reg_btf = btf_vmlinux; 11283 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11284 } 11285 11286 /* Enforce strict type matching for calls to kfuncs that are acquiring 11287 * or releasing a reference, or are no-cast aliases. We do _not_ 11288 * enforce strict matching for kfuncs by default, 11289 * as we want to enable BPF programs to pass types that are bitwise 11290 * equivalent without forcing them to explicitly cast with something 11291 * like bpf_cast_to_kern_ctx(). 11292 * 11293 * For example, say we had a type like the following: 11294 * 11295 * struct bpf_cpumask { 11296 * cpumask_t cpumask; 11297 * refcount_t usage; 11298 * }; 11299 * 11300 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11301 * to a struct cpumask, so it would be safe to pass a struct 11302 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11303 * 11304 * The philosophy here is similar to how we allow scalars of different 11305 * types to be passed to kfuncs as long as the size is the same. The 11306 * only difference here is that we're simply allowing 11307 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11308 * resolve types. 11309 */ 11310 if ((is_kfunc_release(meta) && reg_is_referenced(env, reg)) || 11311 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11312 strict_type_match = true; 11313 11314 WARN_ON_ONCE(is_kfunc_release(meta) && !tnum_is_const(reg->var_off)); 11315 11316 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11317 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11318 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->var_off.value, 11319 meta->btf, ref_id, strict_type_match); 11320 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11321 * actually use it -- it must cast to the underlying type. So we allow 11322 * caller to pass in the underlying type. 11323 */ 11324 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11325 if (!taking_projection && !struct_same) { 11326 verbose(env, "kernel function %s %s expected pointer to %s %s but %s has a pointer to %s %s\n", 11327 meta->func_name, reg_arg_name(env, argno), 11328 btf_type_str(ref_t), ref_tname, reg_arg_name(env, argno), 11329 btf_type_str(reg_ref_t), reg_ref_tname); 11330 return -EINVAL; 11331 } 11332 return 0; 11333 } 11334 11335 static int process_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, argno_t argno, 11336 struct bpf_kfunc_call_arg_meta *meta) 11337 { 11338 int err, spi, kfunc_class = IRQ_NATIVE_KFUNC; 11339 bool irq_save; 11340 11341 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] || 11342 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) { 11343 irq_save = true; 11344 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 11345 kfunc_class = IRQ_LOCK_KFUNC; 11346 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] || 11347 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) { 11348 irq_save = false; 11349 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 11350 kfunc_class = IRQ_LOCK_KFUNC; 11351 } else { 11352 verifier_bug(env, "unknown irq flags kfunc"); 11353 return -EFAULT; 11354 } 11355 11356 if (irq_save) { 11357 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 11358 verbose(env, "expected uninitialized irq flag as %s\n", 11359 reg_arg_name(env, argno)); 11360 return -EINVAL; 11361 } 11362 11363 err = check_mem_access(env, env->insn_idx, reg, argno, 0, BPF_DW, 11364 BPF_WRITE, -1, false, false); 11365 if (err) 11366 return err; 11367 11368 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 11369 if (err) 11370 return err; 11371 } else { 11372 err = is_irq_flag_reg_valid_init(env, reg); 11373 if (err) { 11374 verbose(env, "expected an initialized irq flag as %s\n", 11375 reg_arg_name(env, argno)); 11376 return err; 11377 } 11378 11379 spi = irq_flag_get_spi(env, reg); 11380 if (spi < 0) 11381 return spi; 11382 11383 mark_stack_slots_scratched(env, spi, 1); 11384 11385 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 11386 if (err) 11387 return err; 11388 } 11389 return 0; 11390 } 11391 11392 11393 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11394 { 11395 struct btf_record *rec = reg_btf_record(reg); 11396 11397 if (!env->cur_state->active_locks) { 11398 verifier_bug(env, "%s w/o active lock", __func__); 11399 return -EFAULT; 11400 } 11401 11402 if (type_flag(reg->type) & NON_OWN_REF) { 11403 verifier_bug(env, "NON_OWN_REF already set"); 11404 return -EFAULT; 11405 } 11406 11407 reg->type |= NON_OWN_REF; 11408 if (rec->refcount_off >= 0) 11409 reg->type |= MEM_RCU; 11410 11411 return 0; 11412 } 11413 11414 static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id) 11415 { 11416 struct bpf_func_state *unused; 11417 struct bpf_reg_state *reg; 11418 11419 WARN_ON_ONCE(release_reference_nomark(env->cur_state, id)); 11420 11421 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11422 if (reg->id == id) { 11423 reg->id = 0; 11424 ref_set_non_owning(env, reg); 11425 } 11426 })); 11427 11428 return; 11429 } 11430 11431 /* Implementation details: 11432 * 11433 * Each register points to some region of memory, which we define as an 11434 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11435 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11436 * allocation. The lock and the data it protects are colocated in the same 11437 * memory region. 11438 * 11439 * Hence, everytime a register holds a pointer value pointing to such 11440 * allocation, the verifier preserves a unique reg->id for it. 11441 * 11442 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11443 * bpf_spin_lock is called. 11444 * 11445 * To enable this, lock state in the verifier captures two values: 11446 * active_lock.ptr = Register's type specific pointer 11447 * active_lock.id = A unique ID for each register pointer value 11448 * 11449 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11450 * supported register types. 11451 * 11452 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11453 * allocated objects is the reg->btf pointer. 11454 * 11455 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11456 * can establish the provenance of the map value statically for each distinct 11457 * lookup into such maps. They always contain a single map value hence unique 11458 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11459 * 11460 * So, in case of global variables, they use array maps with max_entries = 1, 11461 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11462 * into the same map value as max_entries is 1, as described above). 11463 * 11464 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11465 * outer map pointer (in verifier context), but each lookup into an inner map 11466 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11467 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11468 * will get different reg->id assigned to each lookup, hence different 11469 * active_lock.id. 11470 * 11471 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11472 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11473 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11474 */ 11475 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11476 { 11477 struct bpf_reference_state *s; 11478 void *ptr; 11479 u32 id; 11480 11481 switch ((int)reg->type) { 11482 case PTR_TO_MAP_VALUE: 11483 ptr = reg->map_ptr; 11484 break; 11485 case PTR_TO_BTF_ID | MEM_ALLOC: 11486 ptr = reg->btf; 11487 break; 11488 default: 11489 verifier_bug(env, "unknown reg type for lock check"); 11490 return -EFAULT; 11491 } 11492 id = reg->id; 11493 11494 if (!env->cur_state->active_locks) 11495 return -EINVAL; 11496 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 11497 if (!s) { 11498 verbose(env, "held lock and object are not in the same allocation\n"); 11499 return -EINVAL; 11500 } 11501 return 0; 11502 } 11503 11504 static bool is_bpf_list_api_kfunc(u32 btf_id) 11505 { 11506 return is_bpf_list_push_kfunc(btf_id) || 11507 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11508 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 11509 btf_id == special_kfunc_list[KF_bpf_list_del] || 11510 btf_id == special_kfunc_list[KF_bpf_list_front] || 11511 btf_id == special_kfunc_list[KF_bpf_list_back] || 11512 btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11513 btf_id == special_kfunc_list[KF_bpf_list_is_last] || 11514 btf_id == special_kfunc_list[KF_bpf_list_empty]; 11515 } 11516 11517 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11518 { 11519 return is_bpf_rbtree_add_kfunc(btf_id) || 11520 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11521 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 11522 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 11523 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11524 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 11525 } 11526 11527 static bool is_bpf_iter_num_api_kfunc(u32 btf_id) 11528 { 11529 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] || 11530 btf_id == special_kfunc_list[KF_bpf_iter_num_next] || 11531 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy]; 11532 } 11533 11534 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11535 { 11536 return is_bpf_list_api_kfunc(btf_id) || 11537 is_bpf_rbtree_api_kfunc(btf_id) || 11538 is_bpf_refcount_acquire_kfunc(btf_id); 11539 } 11540 11541 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id) 11542 { 11543 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 11544 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 11545 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 11546 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]; 11547 } 11548 11549 static bool is_bpf_arena_kfunc(u32 btf_id) 11550 { 11551 return btf_id == special_kfunc_list[KF_bpf_arena_alloc_pages] || 11552 btf_id == special_kfunc_list[KF_bpf_arena_free_pages] || 11553 btf_id == special_kfunc_list[KF_bpf_arena_reserve_pages]; 11554 } 11555 11556 static bool is_bpf_stream_kfunc(u32 btf_id) 11557 { 11558 return btf_id == special_kfunc_list[KF_bpf_stream_vprintk] || 11559 btf_id == special_kfunc_list[KF_bpf_stream_print_stack]; 11560 } 11561 11562 static bool kfunc_spin_allowed(u32 btf_id) 11563 { 11564 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) || 11565 is_bpf_res_spin_lock_kfunc(btf_id) || is_bpf_arena_kfunc(btf_id) || 11566 is_bpf_stream_kfunc(btf_id); 11567 } 11568 11569 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11570 { 11571 return is_bpf_rbtree_add_kfunc(btf_id); 11572 } 11573 11574 static bool is_async_callback_calling_kfunc(u32 btf_id) 11575 { 11576 return is_bpf_wq_set_callback_kfunc(btf_id) || 11577 is_task_work_add_kfunc(btf_id); 11578 } 11579 11580 bool bpf_is_throw_kfunc(struct bpf_insn *insn) 11581 { 11582 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11583 insn->imm == special_kfunc_list[KF_bpf_throw]; 11584 } 11585 11586 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id) 11587 { 11588 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback]; 11589 } 11590 11591 static bool is_callback_calling_kfunc(u32 btf_id) 11592 { 11593 return is_sync_callback_calling_kfunc(btf_id) || 11594 is_async_callback_calling_kfunc(btf_id); 11595 } 11596 11597 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11598 { 11599 return is_bpf_rbtree_api_kfunc(btf_id); 11600 } 11601 11602 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11603 enum btf_field_type head_field_type, 11604 u32 kfunc_btf_id) 11605 { 11606 bool ret; 11607 11608 switch (head_field_type) { 11609 case BPF_LIST_HEAD: 11610 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11611 break; 11612 case BPF_RB_ROOT: 11613 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11614 break; 11615 default: 11616 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11617 btf_field_type_name(head_field_type)); 11618 return false; 11619 } 11620 11621 if (!ret) 11622 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11623 btf_field_type_name(head_field_type)); 11624 return ret; 11625 } 11626 11627 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11628 enum btf_field_type node_field_type, 11629 u32 kfunc_btf_id) 11630 { 11631 bool ret; 11632 11633 switch (node_field_type) { 11634 case BPF_LIST_NODE: 11635 ret = is_bpf_list_push_kfunc(kfunc_btf_id) || 11636 kfunc_btf_id == special_kfunc_list[KF_bpf_list_del] || 11637 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_first] || 11638 kfunc_btf_id == special_kfunc_list[KF_bpf_list_is_last]; 11639 break; 11640 case BPF_RB_NODE: 11641 ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) || 11642 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11643 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11644 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 11645 break; 11646 default: 11647 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11648 btf_field_type_name(node_field_type)); 11649 return false; 11650 } 11651 11652 if (!ret) 11653 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11654 btf_field_type_name(node_field_type)); 11655 return ret; 11656 } 11657 11658 static int 11659 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11660 struct bpf_reg_state *reg, argno_t argno, 11661 struct bpf_kfunc_call_arg_meta *meta, 11662 enum btf_field_type head_field_type, 11663 struct btf_field **head_field) 11664 { 11665 const char *head_type_name; 11666 struct btf_field *field; 11667 struct btf_record *rec; 11668 u32 head_off; 11669 11670 if (meta->btf != btf_vmlinux) { 11671 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11672 return -EFAULT; 11673 } 11674 11675 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11676 return -EFAULT; 11677 11678 head_type_name = btf_field_type_name(head_field_type); 11679 if (!tnum_is_const(reg->var_off)) { 11680 verbose(env, 11681 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11682 reg_arg_name(env, argno), head_type_name); 11683 return -EINVAL; 11684 } 11685 11686 rec = reg_btf_record(reg); 11687 head_off = reg->var_off.value; 11688 field = btf_record_find(rec, head_off, head_field_type); 11689 if (!field) { 11690 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11691 return -EINVAL; 11692 } 11693 11694 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11695 if (check_reg_allocation_locked(env, reg)) { 11696 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11697 rec->spin_lock_off, head_type_name); 11698 return -EINVAL; 11699 } 11700 11701 if (*head_field) { 11702 verifier_bug(env, "repeating %s arg", head_type_name); 11703 return -EFAULT; 11704 } 11705 *head_field = field; 11706 return 0; 11707 } 11708 11709 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11710 struct bpf_reg_state *reg, argno_t argno, 11711 struct bpf_kfunc_call_arg_meta *meta) 11712 { 11713 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_LIST_HEAD, 11714 &meta->arg_list_head.field); 11715 } 11716 11717 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11718 struct bpf_reg_state *reg, argno_t argno, 11719 struct bpf_kfunc_call_arg_meta *meta) 11720 { 11721 return __process_kf_arg_ptr_to_graph_root(env, reg, argno, meta, BPF_RB_ROOT, 11722 &meta->arg_rbtree_root.field); 11723 } 11724 11725 static int 11726 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11727 struct bpf_reg_state *reg, argno_t argno, 11728 struct bpf_kfunc_call_arg_meta *meta, 11729 enum btf_field_type head_field_type, 11730 enum btf_field_type node_field_type, 11731 struct btf_field **node_field) 11732 { 11733 const char *node_type_name; 11734 const struct btf_type *et, *t; 11735 struct btf_field *field; 11736 u32 node_off; 11737 11738 if (meta->btf != btf_vmlinux) { 11739 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11740 return -EFAULT; 11741 } 11742 11743 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11744 return -EFAULT; 11745 11746 node_type_name = btf_field_type_name(node_field_type); 11747 if (!tnum_is_const(reg->var_off)) { 11748 verbose(env, 11749 "%s doesn't have constant offset. %s has to be at the constant offset\n", 11750 reg_arg_name(env, argno), node_type_name); 11751 return -EINVAL; 11752 } 11753 11754 node_off = reg->var_off.value; 11755 field = reg_find_field_offset(reg, node_off, node_field_type); 11756 if (!field) { 11757 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11758 return -EINVAL; 11759 } 11760 11761 field = *node_field; 11762 11763 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11764 t = btf_type_by_id(reg->btf, reg->btf_id); 11765 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11766 field->graph_root.value_btf_id, true)) { 11767 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11768 "in struct %s, but arg is at offset=%d in struct %s\n", 11769 btf_field_type_name(head_field_type), 11770 btf_field_type_name(node_field_type), 11771 field->graph_root.node_offset, 11772 btf_name_by_offset(field->graph_root.btf, et->name_off), 11773 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11774 return -EINVAL; 11775 } 11776 meta->arg_btf = reg->btf; 11777 meta->arg_btf_id = reg->btf_id; 11778 11779 if (node_off != field->graph_root.node_offset) { 11780 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11781 node_off, btf_field_type_name(node_field_type), 11782 field->graph_root.node_offset, 11783 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11784 return -EINVAL; 11785 } 11786 11787 return 0; 11788 } 11789 11790 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11791 struct bpf_reg_state *reg, argno_t argno, 11792 struct bpf_kfunc_call_arg_meta *meta) 11793 { 11794 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 11795 BPF_LIST_HEAD, BPF_LIST_NODE, 11796 &meta->arg_list_head.field); 11797 } 11798 11799 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11800 struct bpf_reg_state *reg, argno_t argno, 11801 struct bpf_kfunc_call_arg_meta *meta) 11802 { 11803 return __process_kf_arg_ptr_to_graph_node(env, reg, argno, meta, 11804 BPF_RB_ROOT, BPF_RB_NODE, 11805 &meta->arg_rbtree_root.field); 11806 } 11807 11808 /* 11809 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11810 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11811 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11812 * them can only be attached to some specific hook points. 11813 */ 11814 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11815 { 11816 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11817 11818 switch (prog_type) { 11819 case BPF_PROG_TYPE_LSM: 11820 return true; 11821 case BPF_PROG_TYPE_TRACING: 11822 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11823 return true; 11824 fallthrough; 11825 default: 11826 return in_sleepable(env); 11827 } 11828 } 11829 11830 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11831 int insn_idx) 11832 { 11833 const char *func_name = meta->func_name, *ref_tname; 11834 struct bpf_func_state *caller = cur_func(env); 11835 struct bpf_reg_state *regs = cur_regs(env); 11836 const struct btf *btf = meta->btf; 11837 const struct btf_param *args; 11838 struct btf_record *rec; 11839 u32 i, nargs; 11840 int ret; 11841 11842 args = (const struct btf_param *)(meta->func_proto + 1); 11843 nargs = btf_type_vlen(meta->func_proto); 11844 if (nargs > MAX_BPF_FUNC_ARGS) { 11845 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11846 MAX_BPF_FUNC_ARGS); 11847 return -EINVAL; 11848 } 11849 if (nargs > MAX_BPF_FUNC_REG_ARGS && !bpf_jit_supports_stack_args()) { 11850 verbose(env, "JIT does not support kfunc %s() with %d args\n", 11851 func_name, nargs); 11852 return -ENOTSUPP; 11853 } 11854 11855 ret = check_outgoing_stack_args(env, caller, nargs); 11856 if (ret) 11857 return ret; 11858 11859 /* Check that BTF function arguments match actual types that the 11860 * verifier sees. 11861 */ 11862 for (i = 0; i < nargs; i++) { 11863 struct bpf_reg_state *reg = get_func_arg_reg(caller, regs, i); 11864 const struct btf_type *t, *ref_t, *resolve_ret; 11865 enum bpf_arg_type arg_type = ARG_DONTCARE; 11866 argno_t argno = argno_from_arg(i + 1); 11867 int regno = reg_from_argno(argno); 11868 u32 ref_id, type_size; 11869 bool is_ret_buf_sz = false; 11870 int kf_arg_type; 11871 11872 if (is_kfunc_arg_prog_aux(btf, &args[i])) { 11873 /* Reject repeated use bpf_prog_aux */ 11874 if (meta->arg_prog) { 11875 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc"); 11876 return -EFAULT; 11877 } 11878 if (regno < 0) { 11879 verbose(env, "%s prog->aux cannot be a stack argument\n", 11880 reg_arg_name(env, argno)); 11881 return -EINVAL; 11882 } 11883 meta->arg_prog = true; 11884 cur_aux(env)->arg_prog = regno; 11885 continue; 11886 } 11887 11888 if (is_kfunc_arg_ignore(btf, &args[i]) || is_kfunc_arg_implicit(meta, i)) 11889 continue; 11890 11891 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11892 11893 if (btf_type_is_scalar(t)) { 11894 if (reg->type != SCALAR_VALUE) { 11895 verbose(env, "%s is not a scalar\n", reg_arg_name(env, argno)); 11896 return -EINVAL; 11897 } 11898 11899 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11900 if (meta->arg_constant.found) { 11901 verifier_bug(env, "only one constant argument permitted"); 11902 return -EFAULT; 11903 } 11904 if (!tnum_is_const(reg->var_off)) { 11905 verbose(env, "%s must be a known constant\n", 11906 reg_arg_name(env, argno)); 11907 return -EINVAL; 11908 } 11909 if (regno >= 0) 11910 ret = mark_chain_precision(env, regno); 11911 else 11912 ret = mark_stack_arg_precision(env, i); 11913 if (ret < 0) 11914 return ret; 11915 meta->arg_constant.found = true; 11916 meta->arg_constant.value = reg->var_off.value; 11917 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11918 meta->r0_rdonly = true; 11919 is_ret_buf_sz = true; 11920 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11921 is_ret_buf_sz = true; 11922 } 11923 11924 if (is_ret_buf_sz) { 11925 if (meta->r0_size) { 11926 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11927 return -EINVAL; 11928 } 11929 11930 if (!tnum_is_const(reg->var_off)) { 11931 verbose(env, "%s is not a const\n", 11932 reg_arg_name(env, argno)); 11933 return -EINVAL; 11934 } 11935 11936 meta->r0_size = reg->var_off.value; 11937 if (regno >= 0) 11938 ret = mark_chain_precision(env, regno); 11939 else 11940 ret = mark_stack_arg_precision(env, i); 11941 if (ret) 11942 return ret; 11943 } 11944 continue; 11945 } 11946 11947 if (!btf_type_is_ptr(t)) { 11948 verbose(env, "Unrecognized %s type %s\n", 11949 reg_arg_name(env, argno), btf_type_str(t)); 11950 return -EINVAL; 11951 } 11952 11953 if ((bpf_register_is_null(reg) || type_may_be_null(reg->type)) && 11954 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11955 verbose(env, "Possibly NULL pointer passed to trusted %s\n", 11956 reg_arg_name(env, argno)); 11957 return -EACCES; 11958 } 11959 11960 if (regno == meta->release_regno && !is_kfunc_arg_dynptr(meta->btf, &args[i]) && 11961 !reg_is_referenced(env, reg) && !bpf_register_is_null(reg)) { 11962 verbose(env, "release kfunc %s expects referenced PTR_TO_BTF_ID passed to %s\n", 11963 func_name, reg_arg_name(env, argno)); 11964 return -EINVAL; 11965 } 11966 11967 if (reg_is_referenced(env, reg)) 11968 update_ref_obj(&meta->ref_obj, reg); 11969 11970 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11971 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11972 11973 kf_arg_type = get_kfunc_ptr_arg_type(env, caller, regs, meta, t, ref_t, ref_tname, 11974 args, i, nargs, argno, reg); 11975 if (kf_arg_type < 0) 11976 return kf_arg_type; 11977 11978 switch (kf_arg_type) { 11979 case KF_ARG_PTR_TO_NULL: 11980 continue; 11981 case KF_ARG_PTR_TO_MAP: 11982 if (!reg->map_ptr) { 11983 verbose(env, "pointer in %s isn't map pointer\n", 11984 reg_arg_name(env, argno)); 11985 return -EINVAL; 11986 } 11987 if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 || 11988 reg->map_ptr->record->task_work_off >= 0)) { 11989 /* Use map_uid (which is unique id of inner map) to reject: 11990 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 11991 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 11992 * if (inner_map1 && inner_map2) { 11993 * wq = bpf_map_lookup_elem(inner_map1); 11994 * if (wq) 11995 * // mismatch would have been allowed 11996 * bpf_wq_init(wq, inner_map2); 11997 * } 11998 * 11999 * Comparing map_ptr is enough to distinguish normal and outer maps. 12000 */ 12001 if (meta->map.ptr != reg->map_ptr || 12002 meta->map.uid != reg->map_uid) { 12003 if (reg->map_ptr->record->task_work_off >= 0) { 12004 verbose(env, 12005 "bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n", 12006 meta->map.uid, reg->map_uid); 12007 return -EINVAL; 12008 } 12009 verbose(env, 12010 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 12011 meta->map.uid, reg->map_uid); 12012 return -EINVAL; 12013 } 12014 } 12015 meta->map.ptr = reg->map_ptr; 12016 meta->map.uid = reg->map_uid; 12017 fallthrough; 12018 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12019 case KF_ARG_PTR_TO_BTF_ID: 12020 if (!is_trusted_reg(env, reg)) { 12021 if (!is_kfunc_rcu(meta)) { 12022 verbose(env, "%s must be referenced or trusted\n", 12023 reg_arg_name(env, argno)); 12024 return -EINVAL; 12025 } 12026 if (!is_rcu_reg(reg)) { 12027 verbose(env, "%s must be a rcu pointer\n", 12028 reg_arg_name(env, argno)); 12029 return -EINVAL; 12030 } 12031 } 12032 fallthrough; 12033 case KF_ARG_PTR_TO_ITER: 12034 case KF_ARG_PTR_TO_LIST_HEAD: 12035 case KF_ARG_PTR_TO_LIST_NODE: 12036 case KF_ARG_PTR_TO_RB_ROOT: 12037 case KF_ARG_PTR_TO_RB_NODE: 12038 case KF_ARG_PTR_TO_MEM: 12039 case KF_ARG_PTR_TO_MEM_SIZE: 12040 case KF_ARG_PTR_TO_CALLBACK: 12041 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12042 case KF_ARG_PTR_TO_CONST_STR: 12043 case KF_ARG_PTR_TO_WORKQUEUE: 12044 case KF_ARG_PTR_TO_TIMER: 12045 case KF_ARG_PTR_TO_TASK_WORK: 12046 case KF_ARG_PTR_TO_IRQ_FLAG: 12047 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12048 break; 12049 case KF_ARG_PTR_TO_DYNPTR: 12050 arg_type = ARG_PTR_TO_DYNPTR; 12051 break; 12052 case KF_ARG_PTR_TO_CTX: 12053 arg_type = ARG_PTR_TO_CTX; 12054 break; 12055 default: 12056 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type); 12057 return -EFAULT; 12058 } 12059 12060 if (regno == meta->release_regno) 12061 arg_type |= OBJ_RELEASE; 12062 ret = check_func_arg_reg_off(env, reg, argno, arg_type); 12063 if (ret < 0) 12064 return ret; 12065 12066 switch (kf_arg_type) { 12067 case KF_ARG_PTR_TO_CTX: 12068 if (reg->type != PTR_TO_CTX) { 12069 verbose(env, "%s expected pointer to ctx, but got %s\n", 12070 reg_arg_name(env, argno), reg_type_str(env, reg->type)); 12071 return -EINVAL; 12072 } 12073 12074 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12075 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 12076 if (ret < 0) 12077 return -EINVAL; 12078 meta->ret_btf_id = ret; 12079 } 12080 break; 12081 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12082 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 12083 if (!is_bpf_obj_drop_kfunc(meta->func_id)) { 12084 verbose(env, "%s expected for bpf_obj_drop()\n", 12085 reg_arg_name(env, argno)); 12086 return -EINVAL; 12087 } 12088 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 12089 if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) { 12090 verbose(env, "%s expected for bpf_percpu_obj_drop()\n", 12091 reg_arg_name(env, argno)); 12092 return -EINVAL; 12093 } 12094 } else { 12095 verbose(env, "%s expected pointer to allocated object\n", 12096 reg_arg_name(env, argno)); 12097 return -EINVAL; 12098 } 12099 if (!reg_is_referenced(env, reg)) { 12100 verbose(env, "allocated object must be referenced\n"); 12101 return -EINVAL; 12102 } 12103 if (meta->btf == btf_vmlinux) { 12104 meta->arg_btf = reg->btf; 12105 meta->arg_btf_id = reg->btf_id; 12106 } 12107 break; 12108 case KF_ARG_PTR_TO_DYNPTR: 12109 { 12110 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 12111 12112 if (is_kfunc_arg_uninit(btf, &args[i])) 12113 dynptr_arg_type |= MEM_UNINIT; 12114 12115 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 12116 dynptr_arg_type |= DYNPTR_TYPE_SKB; 12117 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 12118 dynptr_arg_type |= DYNPTR_TYPE_XDP; 12119 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) { 12120 dynptr_arg_type |= DYNPTR_TYPE_SKB_META; 12121 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 12122 dynptr_arg_type |= DYNPTR_TYPE_FILE; 12123 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) { 12124 dynptr_arg_type |= DYNPTR_TYPE_FILE | OBJ_RELEASE; 12125 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 12126 (dynptr_arg_type & MEM_UNINIT)) { 12127 enum bpf_dynptr_type parent_type = meta->dynptr.type; 12128 12129 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 12130 verifier_bug(env, "no dynptr type for parent of clone"); 12131 return -EFAULT; 12132 } 12133 12134 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12135 } 12136 12137 ret = process_dynptr_func(env, reg, argno, insn_idx, dynptr_arg_type, 12138 &meta->ref_obj, &meta->dynptr); 12139 if (ret < 0) 12140 return ret; 12141 break; 12142 } 12143 case KF_ARG_PTR_TO_ITER: 12144 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12145 if (!check_css_task_iter_allowlist(env)) { 12146 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12147 return -EINVAL; 12148 } 12149 } 12150 ret = process_iter_arg(env, reg, argno, insn_idx, meta); 12151 if (ret < 0) 12152 return ret; 12153 break; 12154 case KF_ARG_PTR_TO_LIST_HEAD: 12155 if (reg->type != PTR_TO_MAP_VALUE && 12156 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12157 verbose(env, "%s expected pointer to map value or allocated object\n", 12158 reg_arg_name(env, argno)); 12159 return -EINVAL; 12160 } 12161 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 12162 !reg_is_referenced(env, reg)) { 12163 verbose(env, "allocated object must be referenced\n"); 12164 return -EINVAL; 12165 } 12166 ret = process_kf_arg_ptr_to_list_head(env, reg, argno, meta); 12167 if (ret < 0) 12168 return ret; 12169 break; 12170 case KF_ARG_PTR_TO_RB_ROOT: 12171 if (reg->type != PTR_TO_MAP_VALUE && 12172 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12173 verbose(env, "%s expected pointer to map value or allocated object\n", 12174 reg_arg_name(env, argno)); 12175 return -EINVAL; 12176 } 12177 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && 12178 !reg_is_referenced(env, reg)) { 12179 verbose(env, "allocated object must be referenced\n"); 12180 return -EINVAL; 12181 } 12182 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, argno, meta); 12183 if (ret < 0) 12184 return ret; 12185 break; 12186 case KF_ARG_PTR_TO_LIST_NODE: 12187 if (is_kfunc_arg_nonown_allowed(btf, &args[i]) && 12188 type_is_non_owning_ref(reg->type) && !reg_is_referenced(env, reg)) { 12189 /* Allow bpf_list_front/back return value for 12190 * __nonown_allowed list-node arguments. 12191 */ 12192 goto check_ok; 12193 } 12194 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 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 check_ok: 12204 ret = process_kf_arg_ptr_to_list_node(env, reg, argno, meta); 12205 if (ret < 0) 12206 return ret; 12207 break; 12208 case KF_ARG_PTR_TO_RB_NODE: 12209 if (is_bpf_rbtree_add_kfunc(meta->func_id)) { 12210 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12211 verbose(env, "%s expected pointer to allocated object\n", 12212 reg_arg_name(env, argno)); 12213 return -EINVAL; 12214 } 12215 if (!reg_is_referenced(env, reg)) { 12216 verbose(env, "allocated object must be referenced\n"); 12217 return -EINVAL; 12218 } 12219 } else { 12220 if (!type_is_non_owning_ref(reg->type) && 12221 !reg_is_referenced(env, reg)) { 12222 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name); 12223 return -EINVAL; 12224 } 12225 if (in_rbtree_lock_required_cb(env)) { 12226 verbose(env, "%s not allowed in rbtree cb\n", func_name); 12227 return -EINVAL; 12228 } 12229 } 12230 12231 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, argno, meta); 12232 if (ret < 0) 12233 return ret; 12234 break; 12235 case KF_ARG_PTR_TO_MAP: 12236 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12237 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12238 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12239 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12240 fallthrough; 12241 case KF_ARG_PTR_TO_BTF_ID: 12242 /* Only base_type is checked, further checks are done here */ 12243 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12244 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12245 !reg2btf_ids[base_type(reg->type)]) { 12246 verbose(env, "%s is %s ", reg_arg_name(env, argno), 12247 reg_type_str(env, reg->type)); 12248 verbose(env, "expected %s or socket\n", 12249 reg_type_str(env, base_type(reg->type) | 12250 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12251 return -EINVAL; 12252 } 12253 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i, argno); 12254 if (ret < 0) 12255 return ret; 12256 break; 12257 case KF_ARG_PTR_TO_MEM: 12258 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12259 if (IS_ERR(resolve_ret)) { 12260 verbose(env, "%s reference type('%s %s') size cannot be determined: %ld\n", 12261 reg_arg_name(env, argno), btf_type_str(ref_t), 12262 ref_tname, PTR_ERR(resolve_ret)); 12263 return -EINVAL; 12264 } 12265 ret = check_mem_reg(env, reg, argno, type_size); 12266 if (ret < 0) 12267 return ret; 12268 break; 12269 case KF_ARG_PTR_TO_MEM_SIZE: 12270 { 12271 struct bpf_reg_state *buff_reg = reg; 12272 const struct btf_param *buff_arg = &args[i]; 12273 struct bpf_reg_state *size_reg = get_func_arg_reg(caller, regs, i + 1); 12274 const struct btf_param *size_arg = &args[i + 1]; 12275 argno_t next_argno = argno_from_arg(i + 2); 12276 12277 if (!bpf_register_is_null(buff_reg) || !is_kfunc_arg_nullable(meta->btf, buff_arg)) { 12278 ret = check_kfunc_mem_size_reg(env, buff_reg, size_reg, 12279 argno, next_argno); 12280 if (ret < 0) { 12281 verbose(env, "%s and ", reg_arg_name(env, argno)); 12282 verbose(env, "%s memory, len pair leads to invalid memory access\n", 12283 reg_arg_name(env, next_argno)); 12284 return ret; 12285 } 12286 } 12287 12288 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12289 if (meta->arg_constant.found) { 12290 verifier_bug(env, "only one constant argument permitted"); 12291 return -EFAULT; 12292 } 12293 if (!tnum_is_const(size_reg->var_off)) { 12294 verbose(env, "%s must be a known constant\n", 12295 reg_arg_name(env, next_argno)); 12296 return -EINVAL; 12297 } 12298 meta->arg_constant.found = true; 12299 meta->arg_constant.value = size_reg->var_off.value; 12300 } 12301 12302 /* Skip next '__sz' or '__szk' argument */ 12303 i++; 12304 break; 12305 } 12306 case KF_ARG_PTR_TO_CALLBACK: 12307 if (reg->type != PTR_TO_FUNC) { 12308 verbose(env, "%s expected pointer to func\n", reg_arg_name(env, argno)); 12309 return -EINVAL; 12310 } 12311 meta->subprogno = reg->subprogno; 12312 break; 12313 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12314 if (!type_is_ptr_alloc_obj(reg->type)) { 12315 verbose(env, "%s is neither owning or non-owning ref\n", 12316 reg_arg_name(env, argno)); 12317 return -EINVAL; 12318 } 12319 if (!type_is_non_owning_ref(reg->type)) 12320 meta->arg_owning_ref = true; 12321 12322 rec = reg_btf_record(reg); 12323 if (!rec) { 12324 verifier_bug(env, "Couldn't find btf_record"); 12325 return -EFAULT; 12326 } 12327 12328 if (rec->refcount_off < 0) { 12329 verbose(env, "%s doesn't point to a type with bpf_refcount field\n", 12330 reg_arg_name(env, argno)); 12331 return -EINVAL; 12332 } 12333 12334 meta->arg_btf = reg->btf; 12335 meta->arg_btf_id = reg->btf_id; 12336 break; 12337 case KF_ARG_PTR_TO_CONST_STR: 12338 if (reg->type != PTR_TO_MAP_VALUE) { 12339 verbose(env, "%s doesn't point to a const string\n", 12340 reg_arg_name(env, argno)); 12341 return -EINVAL; 12342 } 12343 ret = check_arg_const_str(env, reg, argno); 12344 if (ret) 12345 return ret; 12346 break; 12347 case KF_ARG_PTR_TO_WORKQUEUE: 12348 if (reg->type != PTR_TO_MAP_VALUE) { 12349 verbose(env, "%s doesn't point to a map value\n", 12350 reg_arg_name(env, argno)); 12351 return -EINVAL; 12352 } 12353 ret = check_map_field_pointer(env, reg, argno, BPF_WORKQUEUE, &meta->map); 12354 if (ret < 0) 12355 return ret; 12356 break; 12357 case KF_ARG_PTR_TO_TIMER: 12358 if (reg->type != PTR_TO_MAP_VALUE) { 12359 verbose(env, "%s doesn't point to a map value\n", 12360 reg_arg_name(env, argno)); 12361 return -EINVAL; 12362 } 12363 ret = process_timer_kfunc(env, reg, argno, meta); 12364 if (ret < 0) 12365 return ret; 12366 break; 12367 case KF_ARG_PTR_TO_TASK_WORK: 12368 if (reg->type != PTR_TO_MAP_VALUE) { 12369 verbose(env, "%s doesn't point to a map value\n", 12370 reg_arg_name(env, argno)); 12371 return -EINVAL; 12372 } 12373 ret = check_map_field_pointer(env, reg, argno, BPF_TASK_WORK, &meta->map); 12374 if (ret < 0) 12375 return ret; 12376 break; 12377 case KF_ARG_PTR_TO_IRQ_FLAG: 12378 if (reg->type != PTR_TO_STACK) { 12379 verbose(env, "%s doesn't point to an irq flag on stack\n", 12380 reg_arg_name(env, argno)); 12381 return -EINVAL; 12382 } 12383 ret = process_irq_flag(env, reg, argno, meta); 12384 if (ret < 0) 12385 return ret; 12386 break; 12387 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12388 { 12389 int flags = PROCESS_RES_LOCK; 12390 12391 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12392 verbose(env, "%s doesn't point to map value or allocated object\n", 12393 reg_arg_name(env, argno)); 12394 return -EINVAL; 12395 } 12396 12397 if (!is_bpf_res_spin_lock_kfunc(meta->func_id)) 12398 return -EFAULT; 12399 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 12400 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 12401 flags |= PROCESS_SPIN_LOCK; 12402 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 12403 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 12404 flags |= PROCESS_LOCK_IRQ; 12405 ret = process_spin_lock(env, reg, argno, flags); 12406 if (ret < 0) 12407 return ret; 12408 break; 12409 } 12410 } 12411 } 12412 12413 return 0; 12414 } 12415 12416 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, 12417 s32 func_id, 12418 s16 offset, 12419 struct bpf_kfunc_call_arg_meta *meta) 12420 { 12421 struct bpf_kfunc_meta kfunc; 12422 int err; 12423 12424 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 12425 if (err) 12426 return err; 12427 12428 memset(meta, 0, sizeof(*meta)); 12429 meta->btf = kfunc.btf; 12430 meta->func_id = kfunc.id; 12431 meta->func_proto = kfunc.proto; 12432 meta->func_name = kfunc.name; 12433 12434 if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog)) 12435 return -EACCES; 12436 12437 meta->kfunc_flags = *kfunc.flags; 12438 12439 /* Only support release referenced argument passed by register */ 12440 if (is_kfunc_release(meta)) 12441 meta->release_regno = BPF_REG_1; 12442 12443 return 0; 12444 } 12445 12446 /* 12447 * Determine how many bytes a helper accesses through a stack pointer at 12448 * argument position @arg (0-based, corresponding to R1-R5). 12449 * 12450 * Returns: 12451 * > 0 known read access size in bytes 12452 * 0 doesn't read anything directly 12453 * S64_MIN unknown 12454 * < 0 known write access of (-return) bytes 12455 */ 12456 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12457 int arg, int insn_idx) 12458 { 12459 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12460 const struct bpf_func_proto *fn; 12461 enum bpf_arg_type at; 12462 s64 size; 12463 12464 if (bpf_get_helper_proto(env, insn->imm, &fn) < 0) 12465 return S64_MIN; 12466 12467 at = fn->arg_type[arg]; 12468 12469 switch (base_type(at)) { 12470 case ARG_PTR_TO_MAP_KEY: 12471 case ARG_PTR_TO_MAP_VALUE: { 12472 bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY; 12473 u64 val; 12474 int i, map_reg; 12475 12476 for (i = 0; i < arg; i++) { 12477 if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR) 12478 break; 12479 } 12480 if (i >= arg) 12481 goto scan_all_maps; 12482 12483 map_reg = BPF_REG_1 + i; 12484 12485 if (!(aux->const_reg_map_mask & BIT(map_reg))) 12486 goto scan_all_maps; 12487 12488 i = aux->const_reg_vals[map_reg]; 12489 if (i < env->used_map_cnt) { 12490 size = is_key ? env->used_maps[i]->key_size 12491 : env->used_maps[i]->value_size; 12492 goto out; 12493 } 12494 scan_all_maps: 12495 /* 12496 * Map pointer is not known at this call site (e.g. different 12497 * maps on merged paths). Conservatively return the largest 12498 * key_size or value_size across all maps used by the program. 12499 */ 12500 val = 0; 12501 for (i = 0; i < env->used_map_cnt; i++) { 12502 struct bpf_map *map = env->used_maps[i]; 12503 u32 sz = is_key ? map->key_size : map->value_size; 12504 12505 if (sz > val) 12506 val = sz; 12507 if (map->inner_map_meta) { 12508 sz = is_key ? map->inner_map_meta->key_size 12509 : map->inner_map_meta->value_size; 12510 if (sz > val) 12511 val = sz; 12512 } 12513 } 12514 if (!val) 12515 return S64_MIN; 12516 size = val; 12517 goto out; 12518 } 12519 case ARG_PTR_TO_MEM: 12520 if (at & MEM_FIXED_SIZE) { 12521 size = fn->arg_size[arg]; 12522 goto out; 12523 } 12524 if (arg + 1 < ARRAY_SIZE(fn->arg_type) && 12525 arg_type_is_mem_size(fn->arg_type[arg + 1])) { 12526 int size_reg = BPF_REG_1 + arg + 1; 12527 12528 if (aux->const_reg_mask & BIT(size_reg)) { 12529 size = (s64)aux->const_reg_vals[size_reg]; 12530 goto out; 12531 } 12532 /* 12533 * Size arg is const on each path but differs across merged 12534 * paths. MAX_BPF_STACK is a safe upper bound for reads. 12535 */ 12536 if (at & MEM_UNINIT) 12537 return 0; 12538 return MAX_BPF_STACK; 12539 } 12540 return S64_MIN; 12541 case ARG_PTR_TO_DYNPTR: 12542 size = BPF_DYNPTR_SIZE; 12543 break; 12544 case ARG_PTR_TO_STACK: 12545 /* 12546 * Only used by bpf_calls_callback() helpers. The helper itself 12547 * doesn't access stack. The callback subprog does and it's 12548 * analyzed separately. 12549 */ 12550 return 0; 12551 default: 12552 return S64_MIN; 12553 } 12554 out: 12555 /* 12556 * MEM_UNINIT args are write-only: the helper initializes the 12557 * buffer without reading it. 12558 */ 12559 if (at & MEM_UNINIT) 12560 return -size; 12561 return size; 12562 } 12563 12564 /* 12565 * Determine how many bytes a kfunc accesses through a stack pointer at 12566 * argument position @arg (0-based, corresponding to R1-R5). 12567 * 12568 * Returns: 12569 * > 0 known read access size in bytes 12570 * 0 doesn't access memory through that argument (ex: not a pointer) 12571 * S64_MIN unknown 12572 * < 0 known write access of (-return) bytes 12573 */ 12574 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12575 int arg, int insn_idx) 12576 { 12577 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12578 struct bpf_kfunc_call_arg_meta meta; 12579 const struct btf_param *args; 12580 const struct btf_type *t, *ref_t; 12581 const struct btf *btf; 12582 u32 nargs, type_size; 12583 s64 size; 12584 12585 if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0) 12586 return S64_MIN; 12587 12588 btf = meta.btf; 12589 args = btf_params(meta.func_proto); 12590 nargs = btf_type_vlen(meta.func_proto); 12591 if (arg >= nargs) 12592 return 0; 12593 12594 t = btf_type_skip_modifiers(btf, args[arg].type, NULL); 12595 if (!btf_type_is_ptr(t)) 12596 return 0; 12597 12598 /* dynptr: fixed 16-byte on-stack representation */ 12599 if (is_kfunc_arg_dynptr(btf, &args[arg])) { 12600 size = BPF_DYNPTR_SIZE; 12601 goto out; 12602 } 12603 12604 /* ptr + __sz/__szk pair: size is in the next register */ 12605 if (arg + 1 < nargs && 12606 (btf_param_match_suffix(btf, &args[arg + 1], "__sz") || 12607 btf_param_match_suffix(btf, &args[arg + 1], "__szk"))) { 12608 int size_reg = BPF_REG_1 + arg + 1; 12609 12610 if (aux->const_reg_mask & BIT(size_reg)) { 12611 size = (s64)aux->const_reg_vals[size_reg]; 12612 goto out; 12613 } 12614 return MAX_BPF_STACK; 12615 } 12616 12617 /* fixed-size pointed-to type: resolve via BTF */ 12618 ref_t = btf_type_skip_modifiers(btf, t->type, NULL); 12619 if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) { 12620 size = type_size; 12621 goto out; 12622 } 12623 12624 return S64_MIN; 12625 out: 12626 /* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */ 12627 if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW) 12628 return -size; 12629 if (is_kfunc_arg_uninit(btf, &args[arg])) 12630 return -size; 12631 return size; 12632 } 12633 12634 /* check special kfuncs and return: 12635 * 1 - not fall-through to 'else' branch, continue verification 12636 * 0 - fall-through to 'else' branch 12637 * < 0 - not fall-through to 'else' branch, return error 12638 */ 12639 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 12640 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 12641 const struct btf_type *ptr_type, struct btf *desc_btf) 12642 { 12643 const struct btf_type *ret_t; 12644 int err = 0; 12645 12646 if (meta->btf != btf_vmlinux) 12647 return 0; 12648 12649 if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12650 struct btf_struct_meta *struct_meta; 12651 struct btf *ret_btf; 12652 u32 ret_btf_id; 12653 12654 if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set) 12655 return -ENOMEM; 12656 12657 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 12658 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12659 return -EINVAL; 12660 } 12661 12662 ret_btf = env->prog->aux->btf; 12663 ret_btf_id = meta->arg_constant.value; 12664 12665 /* This may be NULL due to user not supplying a BTF */ 12666 if (!ret_btf) { 12667 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12668 return -EINVAL; 12669 } 12670 12671 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12672 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12673 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12674 return -EINVAL; 12675 } 12676 12677 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12678 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12679 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12680 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12681 return -EINVAL; 12682 } 12683 12684 if (!bpf_global_percpu_ma_set) { 12685 mutex_lock(&bpf_percpu_ma_lock); 12686 if (!bpf_global_percpu_ma_set) { 12687 /* Charge memory allocated with bpf_global_percpu_ma to 12688 * root memcg. The obj_cgroup for root memcg is NULL. 12689 */ 12690 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12691 if (!err) 12692 bpf_global_percpu_ma_set = true; 12693 } 12694 mutex_unlock(&bpf_percpu_ma_lock); 12695 if (err) 12696 return err; 12697 } 12698 12699 mutex_lock(&bpf_percpu_ma_lock); 12700 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12701 mutex_unlock(&bpf_percpu_ma_lock); 12702 if (err) 12703 return err; 12704 } 12705 12706 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12707 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12708 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12709 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12710 return -EINVAL; 12711 } 12712 12713 if (struct_meta) { 12714 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12715 return -EINVAL; 12716 } 12717 } 12718 12719 mark_reg_known_zero(env, regs, BPF_REG_0); 12720 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12721 regs[BPF_REG_0].btf = ret_btf; 12722 regs[BPF_REG_0].btf_id = ret_btf_id; 12723 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) 12724 regs[BPF_REG_0].type |= MEM_PERCPU; 12725 12726 insn_aux->obj_new_size = ret_t->size; 12727 insn_aux->kptr_struct_meta = struct_meta; 12728 } else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) { 12729 mark_reg_known_zero(env, regs, BPF_REG_0); 12730 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12731 regs[BPF_REG_0].btf = meta->arg_btf; 12732 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 12733 12734 insn_aux->kptr_struct_meta = 12735 btf_find_struct_meta(meta->arg_btf, 12736 meta->arg_btf_id); 12737 } else if (is_list_node_type(ptr_type)) { 12738 struct btf_field *field = meta->arg_list_head.field; 12739 12740 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12741 } else if (is_rbtree_node_type(ptr_type)) { 12742 struct btf_field *field = meta->arg_rbtree_root.field; 12743 12744 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12745 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12746 mark_reg_known_zero(env, regs, BPF_REG_0); 12747 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12748 regs[BPF_REG_0].btf = desc_btf; 12749 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 12750 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12751 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 12752 if (!ret_t) { 12753 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n", 12754 meta->arg_constant.value); 12755 return -EINVAL; 12756 } else if (btf_type_is_struct(ret_t)) { 12757 mark_reg_known_zero(env, regs, BPF_REG_0); 12758 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12759 regs[BPF_REG_0].btf = desc_btf; 12760 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 12761 } else if (btf_type_is_void(ret_t)) { 12762 mark_reg_known_zero(env, regs, BPF_REG_0); 12763 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED; 12764 regs[BPF_REG_0].mem_size = 0; 12765 } else { 12766 verbose(env, 12767 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n"); 12768 return -EINVAL; 12769 } 12770 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12771 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12772 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->dynptr.type); 12773 12774 mark_reg_known_zero(env, regs, BPF_REG_0); 12775 12776 if (!meta->arg_constant.found) { 12777 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size"); 12778 return -EFAULT; 12779 } 12780 12781 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 12782 12783 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12784 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12785 12786 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12787 regs[BPF_REG_0].type |= MEM_RDONLY; 12788 } else { 12789 /* this will set env->seen_direct_write to true */ 12790 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12791 verbose(env, "the prog does not allow writes to packet data\n"); 12792 return -EINVAL; 12793 } 12794 } 12795 12796 if (!meta->dynptr.id) { 12797 verifier_bug(env, "no dynptr id"); 12798 return -EFAULT; 12799 } 12800 regs[BPF_REG_0].parent_id = meta->dynptr.id; 12801 } else { 12802 return 0; 12803 } 12804 12805 return 1; 12806 } 12807 12808 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12809 12810 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12811 int *insn_idx_p) 12812 { 12813 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12814 struct bpf_reg_state *regs = cur_regs(env); 12815 const char *func_name, *ptr_type_name; 12816 const struct btf_type *t, *ptr_type; 12817 struct bpf_kfunc_call_arg_meta meta; 12818 struct bpf_insn_aux_data *insn_aux; 12819 int err, insn_idx = *insn_idx_p; 12820 const struct btf_param *args; 12821 u32 i, nargs, ptr_type_id; 12822 struct btf *desc_btf; 12823 int id; 12824 12825 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12826 if (!insn->imm) 12827 return 0; 12828 12829 err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta); 12830 if (err == -EACCES && meta.func_name) 12831 verbose(env, "calling kernel function %s is not allowed\n", meta.func_name); 12832 if (err) 12833 return err; 12834 desc_btf = meta.btf; 12835 func_name = meta.func_name; 12836 insn_aux = &env->insn_aux_data[insn_idx]; 12837 12838 insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta); 12839 12840 if (!insn->off && 12841 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 12842 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 12843 struct bpf_verifier_state *branch; 12844 struct bpf_reg_state *regs; 12845 12846 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 12847 if (IS_ERR(branch)) { 12848 verbose(env, "failed to push state for failed lock acquisition\n"); 12849 return PTR_ERR(branch); 12850 } 12851 12852 regs = branch->frame[branch->curframe]->regs; 12853 12854 /* Clear r0-r5 registers in forked state */ 12855 for (i = 0; i < CALLER_SAVED_REGS; i++) 12856 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 12857 12858 mark_reg_unknown(env, regs, BPF_REG_0); 12859 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 12860 if (err) { 12861 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 12862 return err; 12863 } 12864 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32)); 12865 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 12866 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 12867 return -EFAULT; 12868 } 12869 12870 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12871 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12872 return -EACCES; 12873 } 12874 12875 sleepable = bpf_is_kfunc_sleepable(&meta); 12876 if (sleepable && !in_sleepable(env)) { 12877 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12878 return -EACCES; 12879 } 12880 12881 /* Track non-sleepable context for kfuncs, same as for helpers. */ 12882 if (!in_sleepable_context(env)) 12883 insn_aux->non_sleepable = true; 12884 12885 /* Check the arguments */ 12886 err = check_kfunc_args(env, &meta, insn_idx); 12887 if (err < 0) 12888 return err; 12889 12890 if (is_bpf_rbtree_add_kfunc(meta.func_id)) { 12891 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12892 set_rbtree_add_callback_state); 12893 if (err) { 12894 verbose(env, "kfunc %s#%d failed callback verification\n", 12895 func_name, meta.func_id); 12896 return err; 12897 } 12898 } 12899 12900 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 12901 meta.r0_size = sizeof(u64); 12902 meta.r0_rdonly = false; 12903 } 12904 12905 if (is_bpf_wq_set_callback_kfunc(meta.func_id)) { 12906 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12907 set_timer_callback_state); 12908 if (err) { 12909 verbose(env, "kfunc %s#%d failed callback verification\n", 12910 func_name, meta.func_id); 12911 return err; 12912 } 12913 } 12914 12915 if (is_task_work_add_kfunc(meta.func_id)) { 12916 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12917 set_task_work_schedule_callback_state); 12918 if (err) { 12919 verbose(env, "kfunc %s#%d failed callback verification\n", 12920 func_name, meta.func_id); 12921 return err; 12922 } 12923 } 12924 12925 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12926 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12927 12928 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 12929 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 12930 12931 if (rcu_lock) { 12932 env->cur_state->active_rcu_locks++; 12933 } else if (rcu_unlock) { 12934 if (env->cur_state->active_rcu_locks == 0) { 12935 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12936 return -EINVAL; 12937 } 12938 if (--env->cur_state->active_rcu_locks == 0) 12939 invalidate_rcu_protected_refs(env); 12940 } else if (preempt_disable) { 12941 env->cur_state->active_preempt_locks++; 12942 } else if (preempt_enable) { 12943 if (env->cur_state->active_preempt_locks == 0) { 12944 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 12945 return -EINVAL; 12946 } 12947 env->cur_state->active_preempt_locks--; 12948 } 12949 12950 if (sleepable && !in_sleepable_context(env)) { 12951 verbose(env, "kernel func %s is sleepable within %s\n", 12952 func_name, non_sleepable_context_description(env)); 12953 return -EACCES; 12954 } 12955 12956 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12957 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12958 return -EACCES; 12959 } 12960 12961 if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) { 12962 verbose(env, "kernel func %s requires RCU critical section protection\n", func_name); 12963 return -EACCES; 12964 } 12965 12966 /* In case of release function, we get register number of refcounted 12967 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12968 */ 12969 if (meta.release_regno) { 12970 err = release_reg(env, ®s[meta.release_regno], false, !!meta.dynptr.id); 12971 if (err) 12972 return err; 12973 } 12974 12975 if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) { 12976 id = regs[BPF_REG_2].id; 12977 insn_aux->insert_off = regs[BPF_REG_2].var_off.value; 12978 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12979 ref_convert_owning_non_owning(env, id); 12980 } 12981 12982 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12983 if (!bpf_jit_supports_exceptions()) { 12984 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12985 func_name, meta.func_id); 12986 return -ENOTSUPP; 12987 } 12988 env->seen_exception = true; 12989 12990 /* In the case of the default callback, the cookie value passed 12991 * to bpf_throw becomes the return value of the program. 12992 */ 12993 if (!env->exception_callback_subprog) { 12994 err = check_return_code(env, BPF_REG_1, "R1"); 12995 if (err < 0) 12996 return err; 12997 } 12998 } 12999 13000 for (i = 0; i < CALLER_SAVED_REGS; i++) { 13001 u32 regno = caller_saved[i]; 13002 13003 bpf_mark_reg_not_init(env, ®s[regno]); 13004 regs[regno].subreg_def = DEF_NOT_SUBREG; 13005 } 13006 invalidate_outgoing_stack_args(env, cur_func(env)); 13007 13008 /* Check return type */ 13009 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13010 13011 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13012 if (meta.btf != btf_vmlinux || 13013 (!is_bpf_obj_new_kfunc(meta.func_id) && 13014 !is_bpf_percpu_obj_new_kfunc(meta.func_id) && 13015 !is_bpf_refcount_acquire_kfunc(meta.func_id))) { 13016 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13017 return -EINVAL; 13018 } 13019 } 13020 13021 if (btf_type_is_scalar(t)) { 13022 mark_reg_unknown(env, regs, BPF_REG_0); 13023 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13024 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13025 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 13026 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 13027 } else if (btf_type_is_ptr(t)) { 13028 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 13029 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 13030 if (err) { 13031 if (err < 0) 13032 return err; 13033 } else if (btf_type_is_void(ptr_type)) { 13034 /* kfunc returning 'void *' is equivalent to returning scalar */ 13035 mark_reg_unknown(env, regs, BPF_REG_0); 13036 } else if (!__btf_type_is_struct(ptr_type)) { 13037 if (!meta.r0_size) { 13038 __u32 sz; 13039 13040 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 13041 meta.r0_size = sz; 13042 meta.r0_rdonly = true; 13043 } 13044 } 13045 if (!meta.r0_size) { 13046 ptr_type_name = btf_name_by_offset(desc_btf, 13047 ptr_type->name_off); 13048 verbose(env, 13049 "kernel function %s returns pointer type %s %s is not supported\n", 13050 func_name, 13051 btf_type_str(ptr_type), 13052 ptr_type_name); 13053 return -EINVAL; 13054 } 13055 13056 mark_reg_known_zero(env, regs, BPF_REG_0); 13057 regs[BPF_REG_0].type = PTR_TO_MEM; 13058 regs[BPF_REG_0].mem_size = meta.r0_size; 13059 13060 if (meta.r0_rdonly) 13061 regs[BPF_REG_0].type |= MEM_RDONLY; 13062 13063 /* Ensures we don't access the memory after a release_reference() */ 13064 if (meta.ref_obj.id) { 13065 err = validate_ref_obj(env, &meta.ref_obj); 13066 if (err) 13067 return err; 13068 regs[BPF_REG_0].parent_id = meta.ref_obj.id; 13069 } 13070 13071 if (is_kfunc_rcu_protected(&meta)) 13072 regs[BPF_REG_0].type |= MEM_RCU; 13073 } else { 13074 enum bpf_reg_type type = PTR_TO_BTF_ID; 13075 13076 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 13077 type |= PTR_UNTRUSTED; 13078 else if (is_kfunc_rcu_protected(&meta) || 13079 (bpf_is_iter_next_kfunc(&meta) && 13080 (get_iter_from_state(env->cur_state, &meta) 13081 ->type & MEM_RCU))) { 13082 /* 13083 * If the iterator's constructor (the _new 13084 * function e.g., bpf_iter_task_new) has been 13085 * annotated with BPF kfunc flag 13086 * KF_RCU_PROTECTED and was called within a RCU 13087 * read-side critical section, also propagate 13088 * the MEM_RCU flag to the pointer returned from 13089 * the iterator's next function (e.g., 13090 * bpf_iter_task_next). 13091 */ 13092 type |= MEM_RCU; 13093 } else { 13094 /* 13095 * Any PTR_TO_BTF_ID that is returned from a BPF 13096 * kfunc should by default be treated as 13097 * implicitly trusted. 13098 */ 13099 type |= PTR_TRUSTED; 13100 } 13101 13102 mark_reg_known_zero(env, regs, BPF_REG_0); 13103 regs[BPF_REG_0].btf = desc_btf; 13104 regs[BPF_REG_0].type = type; 13105 regs[BPF_REG_0].btf_id = ptr_type_id; 13106 } 13107 13108 if (is_kfunc_ret_null(&meta)) { 13109 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 13110 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 13111 regs[BPF_REG_0].id = ++env->id_gen; 13112 } 13113 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 13114 if (is_kfunc_acquire(&meta)) { 13115 id = acquire_reference(env, insn_idx, 0); 13116 if (id < 0) 13117 return id; 13118 regs[BPF_REG_0].id = id; 13119 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 13120 ref_set_non_owning(env, ®s[BPF_REG_0]); 13121 } 13122 13123 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 13124 regs[BPF_REG_0].id = ++env->id_gen; 13125 } else if (btf_type_is_void(t)) { 13126 if (meta.btf == btf_vmlinux) { 13127 if (is_bpf_obj_drop_kfunc(meta.func_id) || 13128 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) { 13129 insn_aux->kptr_struct_meta = 13130 btf_find_struct_meta(meta.arg_btf, 13131 meta.arg_btf_id); 13132 } 13133 } 13134 } 13135 13136 if (bpf_is_kfunc_pkt_changing(&meta)) 13137 clear_all_pkt_pointers(env); 13138 13139 nargs = btf_type_vlen(meta.func_proto); 13140 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 13141 struct bpf_func_state *caller = cur_func(env); 13142 struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno]; 13143 u16 out_stack_arg_cnt = nargs - MAX_BPF_FUNC_REG_ARGS; 13144 u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt; 13145 13146 if (stack_arg_cnt > caller_info->stack_arg_cnt) 13147 caller_info->stack_arg_cnt = stack_arg_cnt; 13148 } 13149 13150 args = (const struct btf_param *)(meta.func_proto + 1); 13151 for (i = 0; i < min_t(int, nargs, MAX_BPF_FUNC_REG_ARGS); i++) { 13152 u32 regno = i + 1; 13153 13154 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 13155 if (btf_type_is_ptr(t)) 13156 mark_btf_func_reg_size(env, regno, sizeof(void *)); 13157 else 13158 /* scalar. ensured by check_kfunc_args() */ 13159 mark_btf_func_reg_size(env, regno, t->size); 13160 } 13161 13162 if (bpf_is_iter_next_kfunc(&meta)) { 13163 err = process_iter_next_call(env, insn_idx, &meta); 13164 if (err) 13165 return err; 13166 } 13167 13168 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 13169 env->prog->call_session_cookie = true; 13170 13171 if (bpf_is_throw_kfunc(insn)) 13172 return process_bpf_exit_full(env, NULL, true); 13173 13174 return 0; 13175 } 13176 13177 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env, 13178 const struct bpf_reg_state *reg, 13179 enum bpf_reg_type type) 13180 { 13181 bool known = tnum_is_const(reg->var_off); 13182 s64 val = reg->var_off.value; 13183 s64 smin = reg_smin(reg); 13184 13185 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13186 verbose(env, "math between %s pointer and %lld is not allowed\n", 13187 reg_type_str(env, type), val); 13188 return false; 13189 } 13190 13191 if (smin == S64_MIN) { 13192 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 13193 reg_type_str(env, type)); 13194 return false; 13195 } 13196 13197 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13198 verbose(env, "value %lld makes %s pointer be out of bounds\n", 13199 smin, reg_type_str(env, type)); 13200 return false; 13201 } 13202 13203 return true; 13204 } 13205 13206 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env, 13207 const struct bpf_reg_state *reg, 13208 enum bpf_reg_type type) 13209 { 13210 bool known = tnum_is_const(reg->var_off); 13211 s64 val = reg->var_off.value; 13212 s64 smin = reg_smin(reg); 13213 13214 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13215 verbose(env, "%s pointer offset %lld is not allowed\n", 13216 reg_type_str(env, type), val); 13217 return false; 13218 } 13219 13220 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13221 verbose(env, "%s pointer offset %lld is not allowed\n", 13222 reg_type_str(env, type), smin); 13223 return false; 13224 } 13225 13226 return true; 13227 } 13228 13229 enum { 13230 REASON_BOUNDS = -1, 13231 REASON_TYPE = -2, 13232 REASON_PATHS = -3, 13233 REASON_LIMIT = -4, 13234 REASON_STACK = -5, 13235 }; 13236 13237 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 13238 u32 *alu_limit, bool mask_to_left) 13239 { 13240 u32 max = 0, ptr_limit = 0; 13241 13242 switch (ptr_reg->type) { 13243 case PTR_TO_STACK: 13244 /* Offset 0 is out-of-bounds, but acceptable start for the 13245 * left direction, see BPF_REG_FP. Also, unknown scalar 13246 * offset where we would need to deal with min/max bounds is 13247 * currently prohibited for unprivileged. 13248 */ 13249 max = MAX_BPF_STACK + mask_to_left; 13250 ptr_limit = -ptr_reg->var_off.value; 13251 break; 13252 case PTR_TO_MAP_VALUE: 13253 max = ptr_reg->map_ptr->value_size; 13254 ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg); 13255 break; 13256 default: 13257 return REASON_TYPE; 13258 } 13259 13260 if (ptr_limit >= max) 13261 return REASON_LIMIT; 13262 *alu_limit = ptr_limit; 13263 return 0; 13264 } 13265 13266 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 13267 const struct bpf_insn *insn) 13268 { 13269 return env->bypass_spec_v1 || 13270 BPF_SRC(insn->code) == BPF_K || 13271 cur_aux(env)->nospec; 13272 } 13273 13274 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 13275 u32 alu_state, u32 alu_limit) 13276 { 13277 /* If we arrived here from different branches with different 13278 * state or limits to sanitize, then this won't work. 13279 */ 13280 if (aux->alu_state && 13281 (aux->alu_state != alu_state || 13282 aux->alu_limit != alu_limit)) 13283 return REASON_PATHS; 13284 13285 /* Corresponding fixup done in do_misc_fixups(). */ 13286 aux->alu_state = alu_state; 13287 aux->alu_limit = alu_limit; 13288 return 0; 13289 } 13290 13291 static int sanitize_val_alu(struct bpf_verifier_env *env, 13292 struct bpf_insn *insn) 13293 { 13294 struct bpf_insn_aux_data *aux = cur_aux(env); 13295 13296 if (can_skip_alu_sanitation(env, insn)) 13297 return 0; 13298 13299 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13300 } 13301 13302 static bool sanitize_needed(u8 opcode) 13303 { 13304 return opcode == BPF_ADD || opcode == BPF_SUB; 13305 } 13306 13307 struct bpf_sanitize_info { 13308 struct bpf_insn_aux_data aux; 13309 bool mask_to_left; 13310 }; 13311 13312 static int sanitize_speculative_path(struct bpf_verifier_env *env, 13313 const struct bpf_insn *insn, 13314 u32 next_idx, u32 curr_idx) 13315 { 13316 struct bpf_verifier_state *branch; 13317 struct bpf_reg_state *regs; 13318 13319 branch = push_stack(env, next_idx, curr_idx, true); 13320 if (!IS_ERR(branch) && insn) { 13321 regs = branch->frame[branch->curframe]->regs; 13322 if (BPF_SRC(insn->code) == BPF_K) { 13323 mark_reg_unknown(env, regs, insn->dst_reg); 13324 } else if (BPF_SRC(insn->code) == BPF_X) { 13325 mark_reg_unknown(env, regs, insn->dst_reg); 13326 mark_reg_unknown(env, regs, insn->src_reg); 13327 } 13328 } 13329 return PTR_ERR_OR_ZERO(branch); 13330 } 13331 13332 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13333 struct bpf_insn *insn, 13334 const struct bpf_reg_state *ptr_reg, 13335 const struct bpf_reg_state *off_reg, 13336 struct bpf_reg_state *dst_reg, 13337 struct bpf_sanitize_info *info, 13338 const bool commit_window) 13339 { 13340 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13341 struct bpf_verifier_state *vstate = env->cur_state; 13342 bool off_is_imm = tnum_is_const(off_reg->var_off); 13343 bool off_is_neg = reg_smin(off_reg) < 0; 13344 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13345 u8 opcode = BPF_OP(insn->code); 13346 u32 alu_state, alu_limit; 13347 struct bpf_reg_state tmp; 13348 int err; 13349 13350 if (can_skip_alu_sanitation(env, insn)) 13351 return 0; 13352 13353 /* We already marked aux for masking from non-speculative 13354 * paths, thus we got here in the first place. We only care 13355 * to explore bad access from here. 13356 */ 13357 if (vstate->speculative) 13358 goto do_sim; 13359 13360 if (!commit_window) { 13361 if (!tnum_is_const(off_reg->var_off) && 13362 (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0)) 13363 return REASON_BOUNDS; 13364 13365 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13366 (opcode == BPF_SUB && !off_is_neg); 13367 } 13368 13369 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13370 if (err < 0) 13371 return err; 13372 13373 if (commit_window) { 13374 /* In commit phase we narrow the masking window based on 13375 * the observed pointer move after the simulated operation. 13376 */ 13377 alu_state = info->aux.alu_state; 13378 alu_limit = abs(info->aux.alu_limit - alu_limit); 13379 } else { 13380 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13381 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13382 alu_state |= ptr_is_dst_reg ? 13383 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13384 13385 /* Limit pruning on unknown scalars to enable deep search for 13386 * potential masking differences from other program paths. 13387 */ 13388 if (!off_is_imm) 13389 env->explore_alu_limits = true; 13390 } 13391 13392 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13393 if (err < 0) 13394 return err; 13395 do_sim: 13396 /* If we're in commit phase, we're done here given we already 13397 * pushed the truncated dst_reg into the speculative verification 13398 * stack. 13399 * 13400 * Also, when register is a known constant, we rewrite register-based 13401 * operation to immediate-based, and thus do not need masking (and as 13402 * a consequence, do not need to simulate the zero-truncation either). 13403 */ 13404 if (commit_window || off_is_imm) 13405 return 0; 13406 13407 /* Simulate and find potential out-of-bounds access under 13408 * speculative execution from truncation as a result of 13409 * masking when off was not within expected range. If off 13410 * sits in dst, then we temporarily need to move ptr there 13411 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13412 * for cases where we use K-based arithmetic in one direction 13413 * and truncated reg-based in the other in order to explore 13414 * bad access. 13415 */ 13416 if (!ptr_is_dst_reg) { 13417 tmp = *dst_reg; 13418 *dst_reg = *ptr_reg; 13419 } 13420 err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx); 13421 if (err < 0) 13422 return REASON_STACK; 13423 if (!ptr_is_dst_reg) 13424 *dst_reg = tmp; 13425 return 0; 13426 } 13427 13428 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13429 { 13430 struct bpf_verifier_state *vstate = env->cur_state; 13431 13432 /* If we simulate paths under speculation, we don't update the 13433 * insn as 'seen' such that when we verify unreachable paths in 13434 * the non-speculative domain, sanitize_dead_code() can still 13435 * rewrite/sanitize them. 13436 */ 13437 if (!vstate->speculative) 13438 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13439 } 13440 13441 static int sanitize_err(struct bpf_verifier_env *env, 13442 const struct bpf_insn *insn, int reason, 13443 const struct bpf_reg_state *off_reg, 13444 const struct bpf_reg_state *dst_reg) 13445 { 13446 static const char *err = "pointer arithmetic with it prohibited for !root"; 13447 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13448 u32 dst = insn->dst_reg, src = insn->src_reg; 13449 13450 switch (reason) { 13451 case REASON_BOUNDS: 13452 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13453 off_reg == dst_reg ? dst : src, err); 13454 break; 13455 case REASON_TYPE: 13456 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13457 off_reg == dst_reg ? src : dst, err); 13458 break; 13459 case REASON_PATHS: 13460 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13461 dst, op, err); 13462 break; 13463 case REASON_LIMIT: 13464 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13465 dst, op, err); 13466 break; 13467 case REASON_STACK: 13468 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13469 dst, err); 13470 return -ENOMEM; 13471 default: 13472 verifier_bug(env, "unknown reason (%d)", reason); 13473 break; 13474 } 13475 13476 return -EACCES; 13477 } 13478 13479 /* check that stack access falls within stack limits and that 'reg' doesn't 13480 * have a variable offset. 13481 * 13482 * Variable offset is prohibited for unprivileged mode for simplicity since it 13483 * requires corresponding support in Spectre masking for stack ALU. See also 13484 * retrieve_ptr_limit(). 13485 */ 13486 static int check_stack_access_for_ptr_arithmetic( 13487 struct bpf_verifier_env *env, 13488 int regno, 13489 const struct bpf_reg_state *reg, 13490 int off) 13491 { 13492 if (!tnum_is_const(reg->var_off)) { 13493 char tn_buf[48]; 13494 13495 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13496 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13497 regno, tn_buf, off); 13498 return -EACCES; 13499 } 13500 13501 if (off >= 0 || off < -MAX_BPF_STACK) { 13502 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13503 "prohibited for !root; off=%d\n", regno, off); 13504 return -EACCES; 13505 } 13506 13507 return 0; 13508 } 13509 13510 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13511 const struct bpf_insn *insn, 13512 struct bpf_reg_state *dst_reg) 13513 { 13514 u32 dst = insn->dst_reg; 13515 13516 /* For unprivileged we require that resulting offset must be in bounds 13517 * in order to be able to sanitize access later on. 13518 */ 13519 if (env->bypass_spec_v1) 13520 return 0; 13521 13522 switch (dst_reg->type) { 13523 case PTR_TO_STACK: 13524 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13525 dst_reg->var_off.value)) 13526 return -EACCES; 13527 break; 13528 case PTR_TO_MAP_VALUE: 13529 if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) { 13530 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13531 "prohibited for !root\n", dst); 13532 return -EACCES; 13533 } 13534 break; 13535 default: 13536 return -EOPNOTSUPP; 13537 } 13538 13539 return 0; 13540 } 13541 13542 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13543 * Caller should also handle BPF_MOV case separately. 13544 * If we return -EACCES, caller may want to try again treating pointer as a 13545 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13546 */ 13547 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13548 struct bpf_insn *insn, 13549 const struct bpf_reg_state *ptr_reg, 13550 const struct bpf_reg_state *off_reg) 13551 { 13552 struct bpf_verifier_state *vstate = env->cur_state; 13553 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13554 struct bpf_reg_state *regs = state->regs, *dst_reg; 13555 bool known = tnum_is_const(off_reg->var_off); 13556 s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg); 13557 u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg); 13558 struct bpf_sanitize_info info = {}; 13559 u8 opcode = BPF_OP(insn->code); 13560 u32 dst = insn->dst_reg; 13561 int ret, bounds_ret; 13562 13563 dst_reg = ®s[dst]; 13564 13565 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13566 smin_val > smax_val || umin_val > umax_val) { 13567 /* Taint dst register if offset had invalid bounds derived from 13568 * e.g. dead branches. 13569 */ 13570 __mark_reg_unknown(env, dst_reg); 13571 return 0; 13572 } 13573 13574 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13575 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13576 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13577 __mark_reg_unknown(env, dst_reg); 13578 return 0; 13579 } 13580 13581 verbose(env, 13582 "R%d 32-bit pointer arithmetic prohibited\n", 13583 dst); 13584 return -EACCES; 13585 } 13586 13587 if (ptr_reg->type & PTR_MAYBE_NULL) { 13588 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13589 dst, reg_type_str(env, ptr_reg->type)); 13590 return -EACCES; 13591 } 13592 13593 /* 13594 * Accesses to untrusted PTR_TO_MEM are done through probe 13595 * instructions, hence no need to track offsets. 13596 */ 13597 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 13598 return 0; 13599 13600 switch (base_type(ptr_reg->type)) { 13601 case PTR_TO_CTX: 13602 case PTR_TO_MAP_VALUE: 13603 case PTR_TO_MAP_KEY: 13604 case PTR_TO_STACK: 13605 case PTR_TO_PACKET_META: 13606 case PTR_TO_PACKET: 13607 case PTR_TO_TP_BUFFER: 13608 case PTR_TO_BTF_ID: 13609 case PTR_TO_MEM: 13610 case PTR_TO_BUF: 13611 case PTR_TO_FUNC: 13612 case CONST_PTR_TO_DYNPTR: 13613 break; 13614 case PTR_TO_FLOW_KEYS: 13615 if (known) 13616 break; 13617 fallthrough; 13618 case CONST_PTR_TO_MAP: 13619 /* smin_val represents the known value */ 13620 if (known && smin_val == 0 && opcode == BPF_ADD) 13621 break; 13622 fallthrough; 13623 default: 13624 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13625 dst, reg_type_str(env, ptr_reg->type)); 13626 return -EACCES; 13627 } 13628 13629 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13630 * The id may be overwritten later if we create a new variable offset. 13631 */ 13632 dst_reg->type = ptr_reg->type; 13633 dst_reg->id = ptr_reg->id; 13634 13635 if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type) || 13636 !check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) 13637 return -EINVAL; 13638 13639 /* pointer types do not carry 32-bit bounds at the moment. */ 13640 __mark_reg32_unbounded(dst_reg); 13641 13642 if (sanitize_needed(opcode)) { 13643 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13644 &info, false); 13645 if (ret < 0) 13646 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13647 } 13648 13649 switch (opcode) { 13650 case BPF_ADD: 13651 /* 13652 * dst_reg gets the pointer type and since some positive 13653 * integer value was added to the pointer, give it a new 'id' 13654 * if it's a PTR_TO_PACKET. 13655 * this creates a new 'base' pointer, off_reg (variable) gets 13656 * added into the variable offset, and we copy the fixed offset 13657 * from ptr_reg. 13658 */ 13659 dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64); 13660 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13661 dst_reg->raw = ptr_reg->raw; 13662 if (reg_is_pkt_pointer(ptr_reg)) { 13663 if (!known) 13664 dst_reg->id = ++env->id_gen; 13665 /* 13666 * Clear range for unknown addends since we can't know 13667 * where the pkt pointer ended up. Also clear AT_PKT_END / 13668 * BEYOND_PKT_END from prior comparison as any pointer 13669 * arithmetic invalidates them. 13670 */ 13671 if (!known || dst_reg->range < 0) 13672 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13673 } 13674 break; 13675 case BPF_SUB: 13676 if (dst_reg == off_reg) { 13677 /* scalar -= pointer. Creates an unknown scalar */ 13678 verbose(env, "R%d tried to subtract pointer from scalar\n", 13679 dst); 13680 return -EACCES; 13681 } 13682 /* We don't allow subtraction from FP, because (according to 13683 * test_verifier.c test "invalid fp arithmetic", JITs might not 13684 * be able to deal with it. 13685 */ 13686 if (ptr_reg->type == PTR_TO_STACK) { 13687 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13688 dst); 13689 return -EACCES; 13690 } 13691 dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64)); 13692 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13693 dst_reg->raw = ptr_reg->raw; 13694 if (reg_is_pkt_pointer(ptr_reg)) { 13695 if (!known) 13696 dst_reg->id = ++env->id_gen; 13697 /* 13698 * Clear range if the subtrahend may be negative since 13699 * pkt pointer could move past its bounds. A positive 13700 * subtrahend moves it backwards keeping positive range 13701 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from 13702 * prior comparison as arithmetic invalidates them. 13703 */ 13704 if ((!known && smin_val < 0) || dst_reg->range < 0) 13705 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13706 } 13707 break; 13708 case BPF_AND: 13709 case BPF_OR: 13710 case BPF_XOR: 13711 /* bitwise ops on pointers are troublesome, prohibit. */ 13712 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13713 dst, bpf_alu_string[opcode >> 4]); 13714 return -EACCES; 13715 default: 13716 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13717 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13718 dst, bpf_alu_string[opcode >> 4]); 13719 return -EACCES; 13720 } 13721 13722 if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) 13723 return -EINVAL; 13724 reg_bounds_sync(dst_reg); 13725 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 13726 if (bounds_ret == -EACCES) 13727 return bounds_ret; 13728 if (sanitize_needed(opcode)) { 13729 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13730 &info, true); 13731 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 13732 && !env->cur_state->speculative 13733 && bounds_ret 13734 && !ret, 13735 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 13736 return -EFAULT; 13737 } 13738 if (ret < 0) 13739 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13740 } 13741 13742 return 0; 13743 } 13744 13745 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13746 struct bpf_reg_state *src_reg) 13747 { 13748 dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32); 13749 } 13750 13751 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13752 struct bpf_reg_state *src_reg) 13753 { 13754 dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64); 13755 } 13756 13757 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13758 struct bpf_reg_state *src_reg) 13759 { 13760 dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32)); 13761 } 13762 13763 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13764 struct bpf_reg_state *src_reg) 13765 { 13766 dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64)); 13767 } 13768 13769 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13770 struct bpf_reg_state *src_reg) 13771 { 13772 s32 smin = reg_s32_min(dst_reg); 13773 s32 smax = reg_s32_max(dst_reg); 13774 u32 umin = reg_u32_min(dst_reg); 13775 u32 umax = reg_u32_max(dst_reg); 13776 s32 tmp_prod[4]; 13777 13778 if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) || 13779 check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) { 13780 /* Overflow possible, we know nothing */ 13781 umin = 0; 13782 umax = U32_MAX; 13783 } 13784 if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) || 13785 check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) || 13786 check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) || 13787 check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) { 13788 /* Overflow possible, we know nothing */ 13789 smin = S32_MIN; 13790 smax = S32_MAX; 13791 } else { 13792 smin = min_array(tmp_prod, 4); 13793 smax = max_array(tmp_prod, 4); 13794 } 13795 13796 dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax), 13797 cnum32_from_srange(smin, smax)); 13798 } 13799 13800 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13801 struct bpf_reg_state *src_reg) 13802 { 13803 s64 smin = reg_smin(dst_reg); 13804 s64 smax = reg_smax(dst_reg); 13805 u64 umin = reg_umin(dst_reg); 13806 u64 umax = reg_umax(dst_reg); 13807 s64 tmp_prod[4]; 13808 13809 if (check_mul_overflow(umax, reg_umax(src_reg), &umax) || 13810 check_mul_overflow(umin, reg_umin(src_reg), &umin)) { 13811 /* Overflow possible, we know nothing */ 13812 umin = 0; 13813 umax = U64_MAX; 13814 } 13815 if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) || 13816 check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) || 13817 check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) || 13818 check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) { 13819 /* Overflow possible, we know nothing */ 13820 smin = S64_MIN; 13821 smax = S64_MAX; 13822 } else { 13823 smin = min_array(tmp_prod, 4); 13824 smax = max_array(tmp_prod, 4); 13825 } 13826 13827 dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax), 13828 cnum64_from_srange(smin, smax)); 13829 } 13830 13831 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg, 13832 struct bpf_reg_state *src_reg) 13833 { 13834 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 13835 13836 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val, 13837 reg_u32_max(dst_reg) / src_val); 13838 13839 /* Reset other ranges/tnum to unbounded/unknown. */ 13840 reset_reg64_and_tnum(dst_reg); 13841 } 13842 13843 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg, 13844 struct bpf_reg_state *src_reg) 13845 { 13846 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 13847 13848 reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val), 13849 div64_u64(reg_umax(dst_reg), src_val)); 13850 13851 /* Reset other ranges/tnum to unbounded/unknown. */ 13852 reset_reg32_and_tnum(dst_reg); 13853 } 13854 13855 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg, 13856 struct bpf_reg_state *src_reg) 13857 { 13858 s32 smin = reg_s32_min(dst_reg); 13859 s32 smax = reg_s32_max(dst_reg); 13860 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 13861 s32 res1, res2; 13862 13863 /* BPF div specification: S32_MIN / -1 = S32_MIN */ 13864 if (smin == S32_MIN && src_val == -1) { 13865 /* 13866 * If the dividend range contains more than just S32_MIN, 13867 * we cannot precisely track the result, so it becomes unbounded. 13868 * e.g., [S32_MIN, S32_MIN+10]/(-1), 13869 * = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)] 13870 * = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX] 13871 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN. 13872 */ 13873 if (smax != S32_MIN) { 13874 smin = S32_MIN; 13875 smax = S32_MAX; 13876 } 13877 goto reset; 13878 } 13879 13880 res1 = smin / src_val; 13881 res2 = smax / src_val; 13882 smin = min(res1, res2); 13883 smax = max(res1, res2); 13884 13885 reset: 13886 reg_set_srange32(dst_reg, smin, smax); 13887 /* Reset other ranges/tnum to unbounded/unknown. */ 13888 reset_reg64_and_tnum(dst_reg); 13889 } 13890 13891 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg, 13892 struct bpf_reg_state *src_reg) 13893 { 13894 s64 smin = reg_smin(dst_reg); 13895 s64 smax = reg_smax(dst_reg); 13896 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 13897 s64 res1, res2; 13898 13899 /* BPF div specification: S64_MIN / -1 = S64_MIN */ 13900 if (smin == S64_MIN && src_val == -1) { 13901 /* 13902 * If the dividend range contains more than just S64_MIN, 13903 * we cannot precisely track the result, so it becomes unbounded. 13904 * e.g., [S64_MIN, S64_MIN+10]/(-1), 13905 * = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)] 13906 * = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX] 13907 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN. 13908 */ 13909 if (smax != S64_MIN) { 13910 smin = S64_MIN; 13911 smax = S64_MAX; 13912 } 13913 goto reset; 13914 } 13915 13916 res1 = div64_s64(smin, src_val); 13917 res2 = div64_s64(smax, src_val); 13918 smin = min(res1, res2); 13919 smax = max(res1, res2); 13920 13921 reset: 13922 reg_set_srange64(dst_reg, smin, smax); 13923 /* Reset other ranges/tnum to unbounded/unknown. */ 13924 reset_reg32_and_tnum(dst_reg); 13925 } 13926 13927 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg, 13928 struct bpf_reg_state *src_reg) 13929 { 13930 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 13931 u32 res_max = src_val - 1; 13932 13933 /* 13934 * If dst_umax <= res_max, the result remains unchanged. 13935 * e.g., [2, 5] % 10 = [2, 5]. 13936 */ 13937 if (reg_u32_max(dst_reg) <= res_max) 13938 return; 13939 13940 reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max)); 13941 13942 /* Reset other ranges/tnum to unbounded/unknown. */ 13943 reset_reg64_and_tnum(dst_reg); 13944 } 13945 13946 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg, 13947 struct bpf_reg_state *src_reg) 13948 { 13949 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 13950 u64 res_max = src_val - 1; 13951 13952 /* 13953 * If dst_umax <= res_max, the result remains unchanged. 13954 * e.g., [2, 5] % 10 = [2, 5]. 13955 */ 13956 if (reg_umax(dst_reg) <= res_max) 13957 return; 13958 13959 reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max)); 13960 13961 /* Reset other ranges/tnum to unbounded/unknown. */ 13962 reset_reg32_and_tnum(dst_reg); 13963 } 13964 13965 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg, 13966 struct bpf_reg_state *src_reg) 13967 { 13968 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 13969 13970 /* 13971 * Safe absolute value calculation: 13972 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648. 13973 * Here use unsigned integer to avoid overflow. 13974 */ 13975 u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val; 13976 13977 /* 13978 * Calculate the maximum possible absolute value of the result. 13979 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives 13980 * 2147483647 (S32_MAX), which fits perfectly in s32. 13981 */ 13982 s32 res_max_abs = src_abs - 1; 13983 13984 /* 13985 * If the dividend is already within the result range, 13986 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 13987 */ 13988 if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs) 13989 return; 13990 13991 /* General case: result has the same sign as the dividend. */ 13992 if (reg_s32_min(dst_reg) >= 0) { 13993 reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs)); 13994 } else if (reg_s32_max(dst_reg) <= 0) { 13995 reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0); 13996 } else { 13997 reg_set_srange32(dst_reg, -res_max_abs, res_max_abs); 13998 } 13999 14000 /* Reset other ranges/tnum to unbounded/unknown. */ 14001 reset_reg64_and_tnum(dst_reg); 14002 } 14003 14004 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg, 14005 struct bpf_reg_state *src_reg) 14006 { 14007 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14008 14009 /* 14010 * Safe absolute value calculation: 14011 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63. 14012 * Here use unsigned integer to avoid overflow. 14013 */ 14014 u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val; 14015 14016 /* 14017 * Calculate the maximum possible absolute value of the result. 14018 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives 14019 * 2^63 - 1 (S64_MAX), which fits perfectly in s64. 14020 */ 14021 s64 res_max_abs = src_abs - 1; 14022 14023 /* 14024 * If the dividend is already within the result range, 14025 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14026 */ 14027 if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs) 14028 return; 14029 14030 /* General case: result has the same sign as the dividend. */ 14031 if (reg_smin(dst_reg) >= 0) { 14032 reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs)); 14033 } else if (reg_smax(dst_reg) <= 0) { 14034 reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0); 14035 } else { 14036 reg_set_srange64(dst_reg, -res_max_abs, res_max_abs); 14037 } 14038 14039 /* Reset other ranges/tnum to unbounded/unknown. */ 14040 reset_reg32_and_tnum(dst_reg); 14041 } 14042 14043 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14044 struct bpf_reg_state *src_reg) 14045 { 14046 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14047 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14048 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14049 u32 umax_val = reg_u32_max(src_reg); 14050 14051 if (src_known && dst_known) { 14052 __mark_reg32_known(dst_reg, var32_off.value); 14053 return; 14054 } 14055 14056 /* We get our minimum from the var_off, since that's inherently 14057 * bitwise. Our maximum is the minimum of the operands' maxima. 14058 */ 14059 reg_set_urange32(dst_reg, 14060 var32_off.value, 14061 min(reg_u32_max(dst_reg), umax_val)); 14062 } 14063 14064 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14065 struct bpf_reg_state *src_reg) 14066 { 14067 bool src_known = tnum_is_const(src_reg->var_off); 14068 bool dst_known = tnum_is_const(dst_reg->var_off); 14069 u64 umax_val = reg_umax(src_reg); 14070 14071 if (src_known && dst_known) { 14072 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14073 return; 14074 } 14075 14076 /* We get our minimum from the var_off, since that's inherently 14077 * bitwise. Our maximum is the minimum of the operands' maxima. 14078 */ 14079 reg_set_urange64(dst_reg, 14080 dst_reg->var_off.value, 14081 min(reg_umax(dst_reg), umax_val)); 14082 14083 /* We may learn something more from the var_off */ 14084 __update_reg_bounds(dst_reg); 14085 } 14086 14087 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14088 struct bpf_reg_state *src_reg) 14089 { 14090 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14091 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14092 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14093 u32 umin_val = reg_u32_min(src_reg); 14094 14095 if (src_known && dst_known) { 14096 __mark_reg32_known(dst_reg, var32_off.value); 14097 return; 14098 } 14099 14100 /* We get our maximum from the var_off, and our minimum is the 14101 * maximum of the operands' minima 14102 */ 14103 reg_set_urange32(dst_reg, 14104 max(reg_u32_min(dst_reg), umin_val), 14105 var32_off.value | var32_off.mask); 14106 } 14107 14108 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14109 struct bpf_reg_state *src_reg) 14110 { 14111 bool src_known = tnum_is_const(src_reg->var_off); 14112 bool dst_known = tnum_is_const(dst_reg->var_off); 14113 u64 umin_val = reg_umin(src_reg); 14114 14115 if (src_known && dst_known) { 14116 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14117 return; 14118 } 14119 14120 /* We get our maximum from the var_off, and our minimum is the 14121 * maximum of the operands' minima 14122 */ 14123 reg_set_urange64(dst_reg, 14124 max(reg_umin(dst_reg), umin_val), 14125 dst_reg->var_off.value | dst_reg->var_off.mask); 14126 14127 /* We may learn something more from the var_off */ 14128 __update_reg_bounds(dst_reg); 14129 } 14130 14131 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 14132 struct bpf_reg_state *src_reg) 14133 { 14134 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14135 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14136 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14137 14138 if (src_known && dst_known) { 14139 __mark_reg32_known(dst_reg, var32_off.value); 14140 return; 14141 } 14142 14143 /* We get both minimum and maximum from the var32_off. */ 14144 reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask); 14145 } 14146 14147 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 14148 struct bpf_reg_state *src_reg) 14149 { 14150 bool src_known = tnum_is_const(src_reg->var_off); 14151 bool dst_known = tnum_is_const(dst_reg->var_off); 14152 14153 if (src_known && dst_known) { 14154 /* dst_reg->var_off.value has been updated earlier */ 14155 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14156 return; 14157 } 14158 14159 /* We get both minimum and maximum from the var_off. */ 14160 reg_set_urange64(dst_reg, 14161 dst_reg->var_off.value, 14162 dst_reg->var_off.value | dst_reg->var_off.mask); 14163 } 14164 14165 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14166 u64 umin_val, u64 umax_val) 14167 { 14168 /* If we might shift our top bit out, then we know nothing */ 14169 if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val)) 14170 reg_set_urange32(dst_reg, 0, U32_MAX); 14171 else 14172 /* We lose all sign bit information (except what we can pick 14173 * up from var_off) 14174 */ 14175 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val, 14176 reg_u32_max(dst_reg) << umax_val); 14177 } 14178 14179 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14180 struct bpf_reg_state *src_reg) 14181 { 14182 u32 umax_val = reg_u32_max(src_reg); 14183 u32 umin_val = reg_u32_min(src_reg); 14184 /* u32 alu operation will zext upper bits */ 14185 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14186 14187 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14188 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 14189 /* Not required but being careful mark reg64 bounds as unknown so 14190 * that we are forced to pick them up from tnum and zext later and 14191 * if some path skips this step we are still safe. 14192 */ 14193 __mark_reg64_unbounded(dst_reg); 14194 __update_reg32_bounds(dst_reg); 14195 } 14196 14197 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 14198 u64 umin_val, u64 umax_val) 14199 { 14200 struct cnum64 u, s; 14201 14202 /* Special case <<32 because it is a common compiler pattern to sign 14203 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct 14204 * because s32 bounds don't flip sign when shifting to the left by 14205 * 32bits. 14206 */ 14207 if (umin_val == 32 && umax_val == 32) 14208 s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32, 14209 (s64)reg_s32_max(dst_reg) << 32); 14210 else 14211 s = CNUM64_UNBOUNDED; 14212 14213 /* If we might shift our top bit out, then we know nothing */ 14214 if (reg_umax(dst_reg) > 1ULL << (63 - umax_val)) 14215 u = CNUM64_UNBOUNDED; 14216 else 14217 u = cnum64_from_urange(reg_umin(dst_reg) << umin_val, 14218 reg_umax(dst_reg) << umax_val); 14219 14220 dst_reg->r64 = cnum64_intersect(u, s); 14221 } 14222 14223 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 14224 struct bpf_reg_state *src_reg) 14225 { 14226 u64 umax_val = reg_umax(src_reg); 14227 u64 umin_val = reg_umin(src_reg); 14228 14229 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 14230 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 14231 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14232 14233 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 14234 /* We may learn something more from the var_off */ 14235 __update_reg_bounds(dst_reg); 14236 } 14237 14238 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 14239 struct bpf_reg_state *src_reg) 14240 { 14241 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14242 u32 umax_val = reg_u32_max(src_reg); 14243 u32 umin_val = reg_u32_min(src_reg); 14244 14245 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14246 * be negative, then either: 14247 * 1) src_reg might be zero, so the sign bit of the result is 14248 * unknown, so we lose our signed bounds 14249 * 2) it's known negative, thus the unsigned bounds capture the 14250 * signed bounds 14251 * 3) the signed bounds cross zero, so they tell us nothing 14252 * about the result 14253 * If the value in dst_reg is known nonnegative, then again the 14254 * unsigned bounds capture the signed bounds. 14255 * Thus, in all cases it suffices to blow away our signed bounds 14256 * and rely on inferring new ones from the unsigned bounds and 14257 * var_off of the result. 14258 */ 14259 14260 dst_reg->var_off = tnum_rshift(subreg, umin_val); 14261 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val, 14262 reg_u32_max(dst_reg) >> umin_val); 14263 14264 __mark_reg64_unbounded(dst_reg); 14265 __update_reg32_bounds(dst_reg); 14266 } 14267 14268 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 14269 struct bpf_reg_state *src_reg) 14270 { 14271 u64 umax_val = reg_umax(src_reg); 14272 u64 umin_val = reg_umin(src_reg); 14273 14274 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14275 * be negative, then either: 14276 * 1) src_reg might be zero, so the sign bit of the result is 14277 * unknown, so we lose our signed bounds 14278 * 2) it's known negative, thus the unsigned bounds capture the 14279 * signed bounds 14280 * 3) the signed bounds cross zero, so they tell us nothing 14281 * about the result 14282 * If the value in dst_reg is known nonnegative, then again the 14283 * unsigned bounds capture the signed bounds. 14284 * Thus, in all cases it suffices to blow away our signed bounds 14285 * and rely on inferring new ones from the unsigned bounds and 14286 * var_off of the result. 14287 */ 14288 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 14289 reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val, 14290 reg_umax(dst_reg) >> umin_val); 14291 14292 /* Its not easy to operate on alu32 bounds here because it depends 14293 * on bits being shifted in. Take easy way out and mark unbounded 14294 * so we can recalculate later from tnum. 14295 */ 14296 __mark_reg32_unbounded(dst_reg); 14297 __update_reg_bounds(dst_reg); 14298 } 14299 14300 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 14301 struct bpf_reg_state *src_reg) 14302 { 14303 u64 umin_val = reg_u32_min(src_reg); 14304 14305 /* Upon reaching here, src_known is true and 14306 * umax_val is equal to umin_val. 14307 * Blow away the dst_reg umin_value/umax_value and rely on 14308 * dst_reg var_off to refine the result. 14309 */ 14310 reg_set_srange32(dst_reg, 14311 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val), 14312 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val)); 14313 14314 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 14315 14316 __mark_reg64_unbounded(dst_reg); 14317 __update_reg32_bounds(dst_reg); 14318 } 14319 14320 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 14321 struct bpf_reg_state *src_reg) 14322 { 14323 u64 umin_val = reg_umin(src_reg); 14324 14325 /* Upon reaching here, src_known is true and umax_val is equal 14326 * to umin_val. 14327 */ 14328 reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val, 14329 reg_smax(dst_reg) >> umin_val); 14330 14331 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14332 14333 /* Its not easy to operate on alu32 bounds here because it depends 14334 * on bits being shifted in from upper 32-bits. Take easy way out 14335 * and mark unbounded so we can recalculate later from tnum. 14336 */ 14337 __mark_reg32_unbounded(dst_reg); 14338 __update_reg_bounds(dst_reg); 14339 } 14340 14341 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn) 14342 { 14343 /* 14344 * Byte swap operation - update var_off using tnum_bswap. 14345 * Three cases: 14346 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE) 14347 * unconditional swap 14348 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE) 14349 * swap on big-endian, truncation or no-op on little-endian 14350 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE) 14351 * swap on little-endian, truncation or no-op on big-endian 14352 */ 14353 14354 bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64; 14355 bool to_le = BPF_SRC(insn->code) == BPF_TO_LE; 14356 bool is_big_endian; 14357 #ifdef CONFIG_CPU_BIG_ENDIAN 14358 is_big_endian = true; 14359 #else 14360 is_big_endian = false; 14361 #endif 14362 /* Apply bswap if alu64 or switch between big-endian and little-endian machines */ 14363 bool need_bswap = alu64 || (to_le == is_big_endian); 14364 14365 /* 14366 * If the register is mutated, manually reset its scalar ID to break 14367 * any existing ties and avoid incorrect bounds propagation. 14368 */ 14369 if (need_bswap || insn->imm == 16 || insn->imm == 32) 14370 clear_scalar_id(dst_reg); 14371 14372 if (need_bswap) { 14373 if (insn->imm == 16) 14374 dst_reg->var_off = tnum_bswap16(dst_reg->var_off); 14375 else if (insn->imm == 32) 14376 dst_reg->var_off = tnum_bswap32(dst_reg->var_off); 14377 else if (insn->imm == 64) 14378 dst_reg->var_off = tnum_bswap64(dst_reg->var_off); 14379 /* 14380 * Byteswap scrambles the range, so we must reset bounds. 14381 * Bounds will be re-derived from the new tnum later. 14382 */ 14383 __mark_reg_unbounded(dst_reg); 14384 } 14385 /* For bswap16/32, truncate dst register to match the swapped size */ 14386 if (insn->imm == 16 || insn->imm == 32) 14387 coerce_reg_to_size(dst_reg, insn->imm / 8); 14388 } 14389 14390 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14391 const struct bpf_reg_state *src_reg) 14392 { 14393 bool src_is_const = false; 14394 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14395 14396 if (insn_bitness == 32) { 14397 if (tnum_subreg_is_const(src_reg->var_off) 14398 && reg_s32_min(src_reg) == reg_s32_max(src_reg) 14399 && reg_u32_min(src_reg) == reg_u32_max(src_reg)) 14400 src_is_const = true; 14401 } else { 14402 if (tnum_is_const(src_reg->var_off) 14403 && reg_smin(src_reg) == reg_smax(src_reg) 14404 && reg_umin(src_reg) == reg_umax(src_reg)) 14405 src_is_const = true; 14406 } 14407 14408 switch (BPF_OP(insn->code)) { 14409 case BPF_ADD: 14410 case BPF_SUB: 14411 case BPF_NEG: 14412 case BPF_AND: 14413 case BPF_XOR: 14414 case BPF_OR: 14415 case BPF_MUL: 14416 case BPF_END: 14417 return true; 14418 14419 /* 14420 * Division and modulo operators range is only safe to compute when the 14421 * divisor is a constant. 14422 */ 14423 case BPF_DIV: 14424 case BPF_MOD: 14425 return src_is_const; 14426 14427 /* Shift operators range is only computable if shift dimension operand 14428 * is a constant. Shifts greater than 31 or 63 are undefined. This 14429 * includes shifts by a negative number. 14430 */ 14431 case BPF_LSH: 14432 case BPF_RSH: 14433 case BPF_ARSH: 14434 return (src_is_const && reg_umax(src_reg) < insn_bitness); 14435 default: 14436 return false; 14437 } 14438 } 14439 14440 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn, 14441 struct bpf_reg_state *dst_reg) 14442 { 14443 struct bpf_verifier_state *branch; 14444 struct bpf_reg_state *regs; 14445 bool alu32; 14446 14447 if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0) 14448 alu32 = false; 14449 else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0) 14450 alu32 = true; 14451 else 14452 return 0; 14453 14454 branch = push_stack(env, env->insn_idx, env->insn_idx, false); 14455 if (IS_ERR(branch)) 14456 return PTR_ERR(branch); 14457 14458 regs = branch->frame[branch->curframe]->regs; 14459 if (alu32) { 14460 __mark_reg32_known(®s[insn->dst_reg], 0); 14461 __mark_reg32_known(dst_reg, -1ull); 14462 } else { 14463 __mark_reg_known(®s[insn->dst_reg], 0); 14464 __mark_reg_known(dst_reg, -1ull); 14465 } 14466 return 0; 14467 } 14468 14469 /* WARNING: This function does calculations on 64-bit values, but the actual 14470 * execution may occur on 32-bit values. Therefore, things like bitshifts 14471 * need extra checks in the 32-bit case. 14472 */ 14473 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14474 struct bpf_insn *insn, 14475 struct bpf_reg_state *dst_reg, 14476 struct bpf_reg_state src_reg) 14477 { 14478 u8 opcode = BPF_OP(insn->code); 14479 s16 off = insn->off; 14480 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14481 int ret; 14482 14483 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14484 __mark_reg_unknown(env, dst_reg); 14485 return 0; 14486 } 14487 14488 if (sanitize_needed(opcode)) { 14489 ret = sanitize_val_alu(env, insn); 14490 if (ret < 0) 14491 return sanitize_err(env, insn, ret, NULL, NULL); 14492 } 14493 14494 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14495 * There are two classes of instructions: The first class we track both 14496 * alu32 and alu64 sign/unsigned bounds independently this provides the 14497 * greatest amount of precision when alu operations are mixed with jmp32 14498 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14499 * and BPF_OR. This is possible because these ops have fairly easy to 14500 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14501 * See alu32 verifier tests for examples. The second class of 14502 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14503 * with regards to tracking sign/unsigned bounds because the bits may 14504 * cross subreg boundaries in the alu64 case. When this happens we mark 14505 * the reg unbounded in the subreg bound space and use the resulting 14506 * tnum to calculate an approximation of the sign/unsigned bounds. 14507 */ 14508 switch (opcode) { 14509 case BPF_ADD: 14510 scalar32_min_max_add(dst_reg, &src_reg); 14511 scalar_min_max_add(dst_reg, &src_reg); 14512 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14513 break; 14514 case BPF_SUB: 14515 scalar32_min_max_sub(dst_reg, &src_reg); 14516 scalar_min_max_sub(dst_reg, &src_reg); 14517 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14518 break; 14519 case BPF_NEG: 14520 env->fake_reg[0] = *dst_reg; 14521 __mark_reg_known(dst_reg, 0); 14522 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 14523 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 14524 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 14525 break; 14526 case BPF_MUL: 14527 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14528 scalar32_min_max_mul(dst_reg, &src_reg); 14529 scalar_min_max_mul(dst_reg, &src_reg); 14530 break; 14531 case BPF_DIV: 14532 /* BPF div specification: x / 0 = 0 */ 14533 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) { 14534 ___mark_reg_known(dst_reg, 0); 14535 break; 14536 } 14537 if (alu32) 14538 if (off == 1) 14539 scalar32_min_max_sdiv(dst_reg, &src_reg); 14540 else 14541 scalar32_min_max_udiv(dst_reg, &src_reg); 14542 else 14543 if (off == 1) 14544 scalar_min_max_sdiv(dst_reg, &src_reg); 14545 else 14546 scalar_min_max_udiv(dst_reg, &src_reg); 14547 break; 14548 case BPF_MOD: 14549 /* BPF mod specification: x % 0 = x */ 14550 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) 14551 break; 14552 if (alu32) 14553 if (off == 1) 14554 scalar32_min_max_smod(dst_reg, &src_reg); 14555 else 14556 scalar32_min_max_umod(dst_reg, &src_reg); 14557 else 14558 if (off == 1) 14559 scalar_min_max_smod(dst_reg, &src_reg); 14560 else 14561 scalar_min_max_umod(dst_reg, &src_reg); 14562 break; 14563 case BPF_AND: 14564 if (tnum_is_const(src_reg.var_off)) { 14565 ret = maybe_fork_scalars(env, insn, dst_reg); 14566 if (ret) 14567 return ret; 14568 } 14569 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14570 scalar32_min_max_and(dst_reg, &src_reg); 14571 scalar_min_max_and(dst_reg, &src_reg); 14572 break; 14573 case BPF_OR: 14574 if (tnum_is_const(src_reg.var_off)) { 14575 ret = maybe_fork_scalars(env, insn, dst_reg); 14576 if (ret) 14577 return ret; 14578 } 14579 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14580 scalar32_min_max_or(dst_reg, &src_reg); 14581 scalar_min_max_or(dst_reg, &src_reg); 14582 break; 14583 case BPF_XOR: 14584 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14585 scalar32_min_max_xor(dst_reg, &src_reg); 14586 scalar_min_max_xor(dst_reg, &src_reg); 14587 break; 14588 case BPF_LSH: 14589 if (alu32) 14590 scalar32_min_max_lsh(dst_reg, &src_reg); 14591 else 14592 scalar_min_max_lsh(dst_reg, &src_reg); 14593 break; 14594 case BPF_RSH: 14595 if (alu32) 14596 scalar32_min_max_rsh(dst_reg, &src_reg); 14597 else 14598 scalar_min_max_rsh(dst_reg, &src_reg); 14599 break; 14600 case BPF_ARSH: 14601 if (alu32) 14602 scalar32_min_max_arsh(dst_reg, &src_reg); 14603 else 14604 scalar_min_max_arsh(dst_reg, &src_reg); 14605 break; 14606 case BPF_END: 14607 scalar_byte_swap(dst_reg, insn); 14608 break; 14609 default: 14610 break; 14611 } 14612 14613 /* 14614 * ALU32 ops are zero extended into 64bit register. 14615 * 14616 * BPF_END is already handled inside the helper (truncation), 14617 * so skip zext here to avoid unexpected zero extension. 14618 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40 14619 * This is a 64bit byte swap operation with alu32==true, 14620 * but we should not zero extend the result. 14621 */ 14622 if (alu32 && opcode != BPF_END) 14623 zext_32_to_64(dst_reg); 14624 reg_bounds_sync(dst_reg); 14625 return 0; 14626 } 14627 14628 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14629 * and var_off. 14630 */ 14631 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14632 struct bpf_insn *insn) 14633 { 14634 struct bpf_verifier_state *vstate = env->cur_state; 14635 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14636 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14637 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14638 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14639 u8 opcode = BPF_OP(insn->code); 14640 int err; 14641 14642 dst_reg = ®s[insn->dst_reg]; 14643 if (BPF_SRC(insn->code) == BPF_X) 14644 src_reg = ®s[insn->src_reg]; 14645 else 14646 src_reg = NULL; 14647 14648 /* Case where at least one operand is an arena. */ 14649 if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) { 14650 struct bpf_insn_aux_data *aux = cur_aux(env); 14651 14652 if (dst_reg->type != PTR_TO_ARENA) 14653 *dst_reg = *src_reg; 14654 14655 dst_reg->subreg_def = env->insn_idx + 1; 14656 14657 if (BPF_CLASS(insn->code) == BPF_ALU64) 14658 /* 14659 * 32-bit operations zero upper bits automatically. 14660 * 64-bit operations need to be converted to 32. 14661 */ 14662 aux->needs_zext = true; 14663 14664 /* Any arithmetic operations are allowed on arena pointers */ 14665 return 0; 14666 } 14667 14668 if (dst_reg->type != SCALAR_VALUE) 14669 ptr_reg = dst_reg; 14670 14671 if (BPF_SRC(insn->code) == BPF_X) { 14672 if (src_reg->type != SCALAR_VALUE) { 14673 if (dst_reg->type != SCALAR_VALUE) { 14674 /* Combining two pointers by any ALU op yields 14675 * an arbitrary scalar. Disallow all math except 14676 * pointer subtraction 14677 */ 14678 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14679 mark_reg_unknown(env, regs, insn->dst_reg); 14680 return 0; 14681 } 14682 verbose(env, "R%d pointer %s pointer prohibited\n", 14683 insn->dst_reg, 14684 bpf_alu_string[opcode >> 4]); 14685 return -EACCES; 14686 } else { 14687 /* scalar += pointer 14688 * This is legal, but we have to reverse our 14689 * src/dest handling in computing the range 14690 */ 14691 err = mark_chain_precision(env, insn->dst_reg); 14692 if (err) 14693 return err; 14694 return adjust_ptr_min_max_vals(env, insn, 14695 src_reg, dst_reg); 14696 } 14697 } else if (ptr_reg) { 14698 /* pointer += scalar */ 14699 err = mark_chain_precision(env, insn->src_reg); 14700 if (err) 14701 return err; 14702 return adjust_ptr_min_max_vals(env, insn, 14703 dst_reg, src_reg); 14704 } else if (dst_reg->precise) { 14705 /* if dst_reg is precise, src_reg should be precise as well */ 14706 err = mark_chain_precision(env, insn->src_reg); 14707 if (err) 14708 return err; 14709 } 14710 } else { 14711 /* Pretend the src is a reg with a known value, since we only 14712 * need to be able to read from this state. 14713 */ 14714 off_reg.type = SCALAR_VALUE; 14715 __mark_reg_known(&off_reg, insn->imm); 14716 src_reg = &off_reg; 14717 if (ptr_reg) /* pointer += K */ 14718 return adjust_ptr_min_max_vals(env, insn, 14719 ptr_reg, src_reg); 14720 } 14721 14722 /* Got here implies adding two SCALAR_VALUEs */ 14723 if (WARN_ON_ONCE(ptr_reg)) { 14724 print_verifier_state(env, vstate, vstate->curframe, true); 14725 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14726 return -EFAULT; 14727 } 14728 if (WARN_ON(!src_reg)) { 14729 print_verifier_state(env, vstate, vstate->curframe, true); 14730 verbose(env, "verifier internal error: no src_reg\n"); 14731 return -EFAULT; 14732 } 14733 /* 14734 * For alu32 linked register tracking, we need to check dst_reg's 14735 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(), 14736 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX. 14737 */ 14738 u64 dst_umax = reg_umax(dst_reg); 14739 14740 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14741 if (err) 14742 return err; 14743 /* 14744 * Compilers can generate the code 14745 * r1 = r2 14746 * r1 += 0x1 14747 * if r2 < 1000 goto ... 14748 * use r1 in memory access 14749 * So remember constant delta between r2 and r1 and update r1 after 14750 * 'if' condition. 14751 */ 14752 if (env->bpf_capable && 14753 (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) && 14754 dst_reg->id && is_reg_const(src_reg, alu32) && 14755 !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) { 14756 u64 val = reg_const_value(src_reg, alu32); 14757 s32 off; 14758 14759 if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX)) 14760 goto clear_id; 14761 14762 if (alu32 && (dst_umax > U32_MAX)) 14763 goto clear_id; 14764 14765 off = (s32)val; 14766 14767 if (BPF_OP(insn->code) == BPF_SUB) { 14768 /* Negating S32_MIN would overflow */ 14769 if (off == S32_MIN) 14770 goto clear_id; 14771 off = -off; 14772 } 14773 14774 if (dst_reg->id & BPF_ADD_CONST) { 14775 /* 14776 * If the register already went through rX += val 14777 * we cannot accumulate another val into rx->off. 14778 */ 14779 clear_id: 14780 clear_scalar_id(dst_reg); 14781 } else { 14782 if (alu32) 14783 dst_reg->id |= BPF_ADD_CONST32; 14784 else 14785 dst_reg->id |= BPF_ADD_CONST64; 14786 dst_reg->delta = off; 14787 } 14788 } else { 14789 /* 14790 * Make sure ID is cleared otherwise dst_reg min/max could be 14791 * incorrectly propagated into other registers by sync_linked_regs() 14792 */ 14793 clear_scalar_id(dst_reg); 14794 } 14795 return 0; 14796 } 14797 14798 /* check validity of 32-bit and 64-bit arithmetic operations */ 14799 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14800 { 14801 struct bpf_reg_state *regs = cur_regs(env); 14802 u8 opcode = BPF_OP(insn->code); 14803 int err; 14804 14805 if (opcode == BPF_END || opcode == BPF_NEG) { 14806 /* check src operand */ 14807 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14808 if (err) 14809 return err; 14810 14811 if (is_pointer_value(env, insn->dst_reg)) { 14812 verbose(env, "R%d pointer arithmetic prohibited\n", 14813 insn->dst_reg); 14814 return -EACCES; 14815 } 14816 14817 /* check dest operand */ 14818 if (regs[insn->dst_reg].type == SCALAR_VALUE) { 14819 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14820 err = err ?: adjust_scalar_min_max_vals(env, insn, 14821 ®s[insn->dst_reg], 14822 regs[insn->dst_reg]); 14823 } else { 14824 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14825 } 14826 if (err) 14827 return err; 14828 14829 } else if (opcode == BPF_MOV) { 14830 14831 if (BPF_SRC(insn->code) == BPF_X) { 14832 if (insn->off == BPF_ADDR_SPACE_CAST) { 14833 if (!env->prog->aux->arena) { 14834 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14835 return -EINVAL; 14836 } 14837 } 14838 14839 /* check src operand */ 14840 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14841 if (err) 14842 return err; 14843 } 14844 14845 /* check dest operand, mark as required later */ 14846 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14847 if (err) 14848 return err; 14849 14850 if (BPF_SRC(insn->code) == BPF_X) { 14851 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14852 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14853 14854 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14855 if (insn->imm) { 14856 /* off == BPF_ADDR_SPACE_CAST */ 14857 mark_reg_unknown(env, regs, insn->dst_reg); 14858 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14859 dst_reg->type = PTR_TO_ARENA; 14860 /* PTR_TO_ARENA is 32-bit */ 14861 dst_reg->subreg_def = env->insn_idx + 1; 14862 } 14863 } else if (insn->off == 0) { 14864 /* case: R1 = R2 14865 * copy register state to dest reg 14866 */ 14867 assign_scalar_id_before_mov(env, src_reg); 14868 *dst_reg = *src_reg; 14869 dst_reg->subreg_def = DEF_NOT_SUBREG; 14870 } else { 14871 /* case: R1 = (s8, s16 s32)R2 */ 14872 if (is_pointer_value(env, insn->src_reg)) { 14873 verbose(env, 14874 "R%d sign-extension part of pointer\n", 14875 insn->src_reg); 14876 return -EACCES; 14877 } else if (src_reg->type == SCALAR_VALUE) { 14878 bool no_sext; 14879 14880 no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 14881 if (no_sext) 14882 assign_scalar_id_before_mov(env, src_reg); 14883 *dst_reg = *src_reg; 14884 if (!no_sext) 14885 clear_scalar_id(dst_reg); 14886 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 14887 dst_reg->subreg_def = DEF_NOT_SUBREG; 14888 } else { 14889 mark_reg_unknown(env, regs, insn->dst_reg); 14890 } 14891 } 14892 } else { 14893 /* R1 = (u32) R2 */ 14894 if (is_pointer_value(env, insn->src_reg)) { 14895 verbose(env, 14896 "R%d partial copy of pointer\n", 14897 insn->src_reg); 14898 return -EACCES; 14899 } else if (src_reg->type == SCALAR_VALUE) { 14900 if (insn->off == 0) { 14901 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 14902 14903 if (is_src_reg_u32) 14904 assign_scalar_id_before_mov(env, src_reg); 14905 *dst_reg = *src_reg; 14906 /* Make sure ID is cleared if src_reg is not in u32 14907 * range otherwise dst_reg min/max could be incorrectly 14908 * propagated into src_reg by sync_linked_regs() 14909 */ 14910 if (!is_src_reg_u32) 14911 clear_scalar_id(dst_reg); 14912 dst_reg->subreg_def = env->insn_idx + 1; 14913 } else { 14914 /* case: W1 = (s8, s16)W2 */ 14915 bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 14916 14917 if (no_sext) 14918 assign_scalar_id_before_mov(env, src_reg); 14919 *dst_reg = *src_reg; 14920 if (!no_sext) 14921 clear_scalar_id(dst_reg); 14922 dst_reg->subreg_def = env->insn_idx + 1; 14923 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 14924 } 14925 } else { 14926 mark_reg_unknown(env, regs, 14927 insn->dst_reg); 14928 } 14929 zext_32_to_64(dst_reg); 14930 reg_bounds_sync(dst_reg); 14931 } 14932 } else { 14933 /* case: R = imm 14934 * remember the value we stored into this reg 14935 */ 14936 /* clear any state __mark_reg_known doesn't set */ 14937 mark_reg_unknown(env, regs, insn->dst_reg); 14938 regs[insn->dst_reg].type = SCALAR_VALUE; 14939 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14940 __mark_reg_known(regs + insn->dst_reg, 14941 insn->imm); 14942 } else { 14943 __mark_reg_known(regs + insn->dst_reg, 14944 (u32)insn->imm); 14945 } 14946 } 14947 14948 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14949 14950 if (BPF_SRC(insn->code) == BPF_X) { 14951 /* check src1 operand */ 14952 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14953 if (err) 14954 return err; 14955 } 14956 14957 /* check src2 operand */ 14958 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14959 if (err) 14960 return err; 14961 14962 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14963 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14964 verbose(env, "div by zero\n"); 14965 return -EINVAL; 14966 } 14967 14968 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14969 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14970 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14971 14972 if (insn->imm < 0 || insn->imm >= size) { 14973 verbose(env, "invalid shift %d\n", insn->imm); 14974 return -EINVAL; 14975 } 14976 } 14977 14978 /* check dest operand */ 14979 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14980 err = err ?: adjust_reg_min_max_vals(env, insn); 14981 if (err) 14982 return err; 14983 } 14984 14985 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14986 } 14987 14988 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14989 struct bpf_reg_state *dst_reg, 14990 enum bpf_reg_type type, 14991 bool range_right_open) 14992 { 14993 struct bpf_func_state *state; 14994 struct bpf_reg_state *reg; 14995 int new_range; 14996 14997 if (reg_umax(dst_reg) == 0 && range_right_open) 14998 /* This doesn't give us any range */ 14999 return; 15000 15001 if (reg_umax(dst_reg) > MAX_PACKET_OFF) 15002 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15003 * than pkt_end, but that's because it's also less than pkt. 15004 */ 15005 return; 15006 15007 new_range = reg_umax(dst_reg); 15008 if (range_right_open) 15009 new_range++; 15010 15011 /* Examples for register markings: 15012 * 15013 * pkt_data in dst register: 15014 * 15015 * r2 = r3; 15016 * r2 += 8; 15017 * if (r2 > pkt_end) goto <handle exception> 15018 * <access okay> 15019 * 15020 * r2 = r3; 15021 * r2 += 8; 15022 * if (r2 < pkt_end) goto <access okay> 15023 * <handle exception> 15024 * 15025 * Where: 15026 * r2 == dst_reg, pkt_end == src_reg 15027 * r2=pkt(id=n,off=8,r=0) 15028 * r3=pkt(id=n,off=0,r=0) 15029 * 15030 * pkt_data in src register: 15031 * 15032 * r2 = r3; 15033 * r2 += 8; 15034 * if (pkt_end >= r2) goto <access okay> 15035 * <handle exception> 15036 * 15037 * r2 = r3; 15038 * r2 += 8; 15039 * if (pkt_end <= r2) goto <handle exception> 15040 * <access okay> 15041 * 15042 * Where: 15043 * pkt_end == dst_reg, r2 == src_reg 15044 * r2=pkt(id=n,off=8,r=0) 15045 * r3=pkt(id=n,off=0,r=0) 15046 * 15047 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15048 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15049 * and [r3, r3 + 8-1) respectively is safe to access depending on 15050 * the check. 15051 */ 15052 15053 /* If our ids match, then we must have the same max_value. And we 15054 * don't care about the other reg's fixed offset, since if it's too big 15055 * the range won't allow anything. 15056 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16. 15057 */ 15058 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15059 if (reg->type == type && reg->id == dst_reg->id) 15060 /* keep the maximum range already checked */ 15061 reg->range = max(reg->range, new_range); 15062 })); 15063 } 15064 15065 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15066 u8 opcode, bool is_jmp32); 15067 static u8 rev_opcode(u8 opcode); 15068 15069 /* 15070 * Learn more information about live branches by simulating refinement on both branches. 15071 * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means 15072 * that branch is dead. 15073 */ 15074 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32) 15075 { 15076 /* Fallthrough (FALSE) branch */ 15077 regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32); 15078 reg_bounds_sync(&env->false_reg1); 15079 reg_bounds_sync(&env->false_reg2); 15080 /* 15081 * If there is a range bounds violation in *any* of the abstract values in either 15082 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only 15083 * TRUE branch will be taken. 15084 */ 15085 if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2)) 15086 return 1; 15087 15088 /* Jump (TRUE) branch */ 15089 regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32); 15090 reg_bounds_sync(&env->true_reg1); 15091 reg_bounds_sync(&env->true_reg2); 15092 /* 15093 * If there is a range bounds violation in *any* of the abstract values in either 15094 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead. 15095 * Only FALSE branch will be taken. 15096 */ 15097 if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2)) 15098 return 0; 15099 15100 /* Both branches are possible, we can't determine which one will be taken. */ 15101 return -1; 15102 } 15103 15104 /* 15105 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15106 */ 15107 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15108 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15109 { 15110 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15111 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15112 u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1); 15113 u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1); 15114 s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1); 15115 s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1); 15116 u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2); 15117 u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2); 15118 s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2); 15119 s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2); 15120 15121 if (reg1 == reg2) { 15122 switch (opcode) { 15123 case BPF_JGE: 15124 case BPF_JLE: 15125 case BPF_JSGE: 15126 case BPF_JSLE: 15127 case BPF_JEQ: 15128 return 1; 15129 case BPF_JGT: 15130 case BPF_JLT: 15131 case BPF_JSGT: 15132 case BPF_JSLT: 15133 case BPF_JNE: 15134 return 0; 15135 case BPF_JSET: 15136 if (tnum_is_const(t1)) 15137 return t1.value != 0; 15138 else 15139 return (smin1 <= 0 && smax1 >= 0) ? -1 : 1; 15140 default: 15141 return -1; 15142 } 15143 } 15144 15145 switch (opcode) { 15146 case BPF_JEQ: 15147 /* constants, umin/umax and smin/smax checks would be 15148 * redundant in this case because they all should match 15149 */ 15150 if (tnum_is_const(t1) && tnum_is_const(t2)) 15151 return t1.value == t2.value; 15152 if (!tnum_overlap(t1, t2)) 15153 return 0; 15154 /* non-overlapping ranges */ 15155 if (umin1 > umax2 || umax1 < umin2) 15156 return 0; 15157 if (smin1 > smax2 || smax1 < smin2) 15158 return 0; 15159 if (!is_jmp32) { 15160 /* if 64-bit ranges are inconclusive, see if we can 15161 * utilize 32-bit subrange knowledge to eliminate 15162 * branches that can't be taken a priori 15163 */ 15164 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15165 reg_u32_max(reg1) < reg_u32_min(reg2)) 15166 return 0; 15167 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15168 reg_s32_max(reg1) < reg_s32_min(reg2)) 15169 return 0; 15170 } 15171 break; 15172 case BPF_JNE: 15173 /* constants, umin/umax and smin/smax checks would be 15174 * redundant in this case because they all should match 15175 */ 15176 if (tnum_is_const(t1) && tnum_is_const(t2)) 15177 return t1.value != t2.value; 15178 if (!tnum_overlap(t1, t2)) 15179 return 1; 15180 /* non-overlapping ranges */ 15181 if (umin1 > umax2 || umax1 < umin2) 15182 return 1; 15183 if (smin1 > smax2 || smax1 < smin2) 15184 return 1; 15185 if (!is_jmp32) { 15186 /* if 64-bit ranges are inconclusive, see if we can 15187 * utilize 32-bit subrange knowledge to eliminate 15188 * branches that can't be taken a priori 15189 */ 15190 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15191 reg_u32_max(reg1) < reg_u32_min(reg2)) 15192 return 1; 15193 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15194 reg_s32_max(reg1) < reg_s32_min(reg2)) 15195 return 1; 15196 } 15197 break; 15198 case BPF_JSET: 15199 if (!is_reg_const(reg2, is_jmp32)) { 15200 swap(reg1, reg2); 15201 swap(t1, t2); 15202 } 15203 if (!is_reg_const(reg2, is_jmp32)) 15204 return -1; 15205 if ((~t1.mask & t1.value) & t2.value) 15206 return 1; 15207 if (!((t1.mask | t1.value) & t2.value)) 15208 return 0; 15209 break; 15210 case BPF_JGT: 15211 if (umin1 > umax2) 15212 return 1; 15213 else if (umax1 <= umin2) 15214 return 0; 15215 break; 15216 case BPF_JSGT: 15217 if (smin1 > smax2) 15218 return 1; 15219 else if (smax1 <= smin2) 15220 return 0; 15221 break; 15222 case BPF_JLT: 15223 if (umax1 < umin2) 15224 return 1; 15225 else if (umin1 >= umax2) 15226 return 0; 15227 break; 15228 case BPF_JSLT: 15229 if (smax1 < smin2) 15230 return 1; 15231 else if (smin1 >= smax2) 15232 return 0; 15233 break; 15234 case BPF_JGE: 15235 if (umin1 >= umax2) 15236 return 1; 15237 else if (umax1 < umin2) 15238 return 0; 15239 break; 15240 case BPF_JSGE: 15241 if (smin1 >= smax2) 15242 return 1; 15243 else if (smax1 < smin2) 15244 return 0; 15245 break; 15246 case BPF_JLE: 15247 if (umax1 <= umin2) 15248 return 1; 15249 else if (umin1 > umax2) 15250 return 0; 15251 break; 15252 case BPF_JSLE: 15253 if (smax1 <= smin2) 15254 return 1; 15255 else if (smin1 > smax2) 15256 return 0; 15257 break; 15258 } 15259 15260 return simulate_both_branches_taken(env, opcode, is_jmp32); 15261 } 15262 15263 static int flip_opcode(u32 opcode) 15264 { 15265 /* How can we transform "a <op> b" into "b <op> a"? */ 15266 static const u8 opcode_flip[16] = { 15267 /* these stay the same */ 15268 [BPF_JEQ >> 4] = BPF_JEQ, 15269 [BPF_JNE >> 4] = BPF_JNE, 15270 [BPF_JSET >> 4] = BPF_JSET, 15271 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 15272 [BPF_JGE >> 4] = BPF_JLE, 15273 [BPF_JGT >> 4] = BPF_JLT, 15274 [BPF_JLE >> 4] = BPF_JGE, 15275 [BPF_JLT >> 4] = BPF_JGT, 15276 [BPF_JSGE >> 4] = BPF_JSLE, 15277 [BPF_JSGT >> 4] = BPF_JSLT, 15278 [BPF_JSLE >> 4] = BPF_JSGE, 15279 [BPF_JSLT >> 4] = BPF_JSGT 15280 }; 15281 return opcode_flip[opcode >> 4]; 15282 } 15283 15284 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 15285 struct bpf_reg_state *src_reg, 15286 u8 opcode) 15287 { 15288 struct bpf_reg_state *pkt; 15289 15290 if (src_reg->type == PTR_TO_PACKET_END) { 15291 pkt = dst_reg; 15292 } else if (dst_reg->type == PTR_TO_PACKET_END) { 15293 pkt = src_reg; 15294 opcode = flip_opcode(opcode); 15295 } else { 15296 return -1; 15297 } 15298 15299 if (pkt->range >= 0) 15300 return -1; 15301 15302 switch (opcode) { 15303 case BPF_JLE: 15304 /* pkt <= pkt_end */ 15305 fallthrough; 15306 case BPF_JGT: 15307 /* pkt > pkt_end */ 15308 if (pkt->range == BEYOND_PKT_END) 15309 /* pkt has at last one extra byte beyond pkt_end */ 15310 return opcode == BPF_JGT; 15311 break; 15312 case BPF_JLT: 15313 /* pkt < pkt_end */ 15314 fallthrough; 15315 case BPF_JGE: 15316 /* pkt >= pkt_end */ 15317 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 15318 return opcode == BPF_JGE; 15319 break; 15320 } 15321 return -1; 15322 } 15323 15324 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 15325 * and return: 15326 * 1 - branch will be taken and "goto target" will be executed 15327 * 0 - branch will not be taken and fall-through to next insn 15328 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 15329 * range [0,10] 15330 */ 15331 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15332 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15333 { 15334 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 15335 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 15336 15337 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 15338 u64 val; 15339 15340 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 15341 if (!is_reg_const(reg2, is_jmp32)) { 15342 opcode = flip_opcode(opcode); 15343 swap(reg1, reg2); 15344 } 15345 /* and ensure that reg2 is a constant */ 15346 if (!is_reg_const(reg2, is_jmp32)) 15347 return -1; 15348 15349 if (!reg_not_null(env, reg1)) 15350 return -1; 15351 15352 /* If pointer is valid tests against zero will fail so we can 15353 * use this to direct branch taken. 15354 */ 15355 val = reg_const_value(reg2, is_jmp32); 15356 if (val != 0) 15357 return -1; 15358 15359 switch (opcode) { 15360 case BPF_JEQ: 15361 return 0; 15362 case BPF_JNE: 15363 return 1; 15364 default: 15365 return -1; 15366 } 15367 } 15368 15369 /* now deal with two scalars, but not necessarily constants */ 15370 return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32); 15371 } 15372 15373 /* Opcode that corresponds to a *false* branch condition. 15374 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 15375 */ 15376 static u8 rev_opcode(u8 opcode) 15377 { 15378 switch (opcode) { 15379 case BPF_JEQ: return BPF_JNE; 15380 case BPF_JNE: return BPF_JEQ; 15381 /* JSET doesn't have it's reverse opcode in BPF, so add 15382 * BPF_X flag to denote the reverse of that operation 15383 */ 15384 case BPF_JSET: return BPF_JSET | BPF_X; 15385 case BPF_JSET | BPF_X: return BPF_JSET; 15386 case BPF_JGE: return BPF_JLT; 15387 case BPF_JGT: return BPF_JLE; 15388 case BPF_JLE: return BPF_JGT; 15389 case BPF_JLT: return BPF_JGE; 15390 case BPF_JSGE: return BPF_JSLT; 15391 case BPF_JSGT: return BPF_JSLE; 15392 case BPF_JSLE: return BPF_JSGT; 15393 case BPF_JSLT: return BPF_JSGE; 15394 default: return 0; 15395 } 15396 } 15397 15398 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 15399 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15400 u8 opcode, bool is_jmp32) 15401 { 15402 struct tnum t; 15403 u64 val; 15404 15405 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 15406 switch (opcode) { 15407 case BPF_JGE: 15408 case BPF_JGT: 15409 case BPF_JSGE: 15410 case BPF_JSGT: 15411 opcode = flip_opcode(opcode); 15412 swap(reg1, reg2); 15413 break; 15414 default: 15415 break; 15416 } 15417 15418 switch (opcode) { 15419 case BPF_JEQ: 15420 if (is_jmp32) { 15421 reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32); 15422 reg2->r32 = reg1->r32; 15423 15424 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 15425 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15426 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 15427 } else { 15428 reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64); 15429 reg2->r64 = reg1->r64; 15430 15431 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 15432 reg2->var_off = reg1->var_off; 15433 } 15434 break; 15435 case BPF_JNE: 15436 if (!is_reg_const(reg2, is_jmp32)) 15437 swap(reg1, reg2); 15438 if (!is_reg_const(reg2, is_jmp32)) 15439 break; 15440 15441 /* try to recompute the bound of reg1 if reg2 is a const and 15442 * is exactly the edge of reg1. 15443 */ 15444 val = reg_const_value(reg2, is_jmp32); 15445 if (is_jmp32) { 15446 /* Complement of the range [val, val] as cnum32. */ 15447 cnum32_intersect_with(®1->r32, (struct cnum32){ val + 1, U32_MAX - 1 }); 15448 } else { 15449 /* Complement of the range [val, val] as cnum64. */ 15450 cnum64_intersect_with(®1->r64, (struct cnum64){ val + 1, U64_MAX - 1 }); 15451 } 15452 break; 15453 case BPF_JSET: 15454 if (!is_reg_const(reg2, is_jmp32)) 15455 swap(reg1, reg2); 15456 if (!is_reg_const(reg2, is_jmp32)) 15457 break; 15458 val = reg_const_value(reg2, is_jmp32); 15459 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 15460 * requires single bit to learn something useful. E.g., if we 15461 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 15462 * are actually set? We can learn something definite only if 15463 * it's a single-bit value to begin with. 15464 * 15465 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 15466 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 15467 * bit 1 is set, which we can readily use in adjustments. 15468 */ 15469 if (!is_power_of_2(val)) 15470 break; 15471 if (is_jmp32) { 15472 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 15473 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15474 } else { 15475 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 15476 } 15477 break; 15478 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 15479 if (!is_reg_const(reg2, is_jmp32)) 15480 swap(reg1, reg2); 15481 if (!is_reg_const(reg2, is_jmp32)) 15482 break; 15483 val = reg_const_value(reg2, is_jmp32); 15484 /* Forget the ranges before narrowing tnums, to avoid invariant 15485 * violations if we're on a dead branch. 15486 */ 15487 __mark_reg_unbounded(reg1); 15488 if (is_jmp32) { 15489 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 15490 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15491 } else { 15492 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15493 } 15494 break; 15495 case BPF_JLE: 15496 if (is_jmp32) { 15497 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2)); 15498 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1), U32_MAX); 15499 } else { 15500 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2)); 15501 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1), U64_MAX); 15502 } 15503 break; 15504 case BPF_JLT: 15505 if (is_jmp32) { 15506 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2) - 1); 15507 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1) + 1, U32_MAX); 15508 } else { 15509 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2) - 1); 15510 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1) + 1, U64_MAX); 15511 } 15512 break; 15513 case BPF_JSLE: 15514 if (is_jmp32) { 15515 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2)); 15516 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1), S32_MAX); 15517 } else { 15518 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2)); 15519 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1), S64_MAX); 15520 } 15521 break; 15522 case BPF_JSLT: 15523 if (is_jmp32) { 15524 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2) - 1); 15525 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1) + 1, S32_MAX); 15526 } else { 15527 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2) - 1); 15528 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1) + 1, S64_MAX); 15529 } 15530 break; 15531 default: 15532 return; 15533 } 15534 } 15535 15536 /* Check for invariant violations on the registers for both branches of a condition */ 15537 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env) 15538 { 15539 int err; 15540 15541 err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1"); 15542 err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2"); 15543 err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1"); 15544 err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2"); 15545 return err; 15546 } 15547 15548 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 15549 struct bpf_reg_state *reg, u32 id, 15550 bool is_null) 15551 { 15552 if (type_may_be_null(reg->type) && reg->id == id && 15553 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 15554 /* Old offset should have been known-zero, because we don't 15555 * allow pointer arithmetic on pointers that might be NULL. 15556 * If we see this happening, don't convert the register. 15557 * 15558 * But in some cases, some helpers that return local kptrs 15559 * advance offset for the returned pointer. In those cases, 15560 * it is fine to expect to see reg->var_off. 15561 */ 15562 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 15563 WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0))) 15564 return; 15565 if (is_null) { 15566 /* We don't need id from this point 15567 * onwards anymore, thus we should better reset it, 15568 * so that state pruning has chances to take effect. 15569 */ 15570 __mark_reg_known_zero(reg); 15571 reg->type = SCALAR_VALUE; 15572 15573 return; 15574 } 15575 15576 mark_ptr_not_null_reg(reg); 15577 15578 /* 15579 * reg->id is preserved for object relationship tracking 15580 * and spin_lock lock state tracking 15581 */ 15582 } 15583 } 15584 15585 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15586 * be folded together at some point. 15587 */ 15588 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15589 bool is_null) 15590 { 15591 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15592 struct bpf_reg_state *regs = state->regs, *reg; 15593 u32 id = regs[regno].id; 15594 15595 if (is_null && find_reference_state(vstate, id)) 15596 /* regs[regno] is in the " == NULL" branch. 15597 * No one could have freed the reference state before 15598 * doing the NULL check. 15599 */ 15600 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 15601 15602 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15603 mark_ptr_or_null_reg(state, reg, id, is_null); 15604 })); 15605 } 15606 15607 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15608 struct bpf_reg_state *dst_reg, 15609 struct bpf_reg_state *src_reg, 15610 struct bpf_verifier_state *this_branch, 15611 struct bpf_verifier_state *other_branch) 15612 { 15613 if (BPF_SRC(insn->code) != BPF_X) 15614 return false; 15615 15616 /* Pointers are always 64-bit. */ 15617 if (BPF_CLASS(insn->code) == BPF_JMP32) 15618 return false; 15619 15620 switch (BPF_OP(insn->code)) { 15621 case BPF_JGT: 15622 if ((dst_reg->type == PTR_TO_PACKET && 15623 src_reg->type == PTR_TO_PACKET_END) || 15624 (dst_reg->type == PTR_TO_PACKET_META && 15625 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15626 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15627 find_good_pkt_pointers(this_branch, dst_reg, 15628 dst_reg->type, false); 15629 mark_pkt_end(other_branch, insn->dst_reg, true); 15630 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15631 src_reg->type == PTR_TO_PACKET) || 15632 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15633 src_reg->type == PTR_TO_PACKET_META)) { 15634 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15635 find_good_pkt_pointers(other_branch, src_reg, 15636 src_reg->type, true); 15637 mark_pkt_end(this_branch, insn->src_reg, false); 15638 } else { 15639 return false; 15640 } 15641 break; 15642 case BPF_JLT: 15643 if ((dst_reg->type == PTR_TO_PACKET && 15644 src_reg->type == PTR_TO_PACKET_END) || 15645 (dst_reg->type == PTR_TO_PACKET_META && 15646 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15647 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15648 find_good_pkt_pointers(other_branch, dst_reg, 15649 dst_reg->type, true); 15650 mark_pkt_end(this_branch, insn->dst_reg, false); 15651 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15652 src_reg->type == PTR_TO_PACKET) || 15653 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15654 src_reg->type == PTR_TO_PACKET_META)) { 15655 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15656 find_good_pkt_pointers(this_branch, src_reg, 15657 src_reg->type, false); 15658 mark_pkt_end(other_branch, insn->src_reg, true); 15659 } else { 15660 return false; 15661 } 15662 break; 15663 case BPF_JGE: 15664 if ((dst_reg->type == PTR_TO_PACKET && 15665 src_reg->type == PTR_TO_PACKET_END) || 15666 (dst_reg->type == PTR_TO_PACKET_META && 15667 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15668 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15669 find_good_pkt_pointers(this_branch, dst_reg, 15670 dst_reg->type, true); 15671 mark_pkt_end(other_branch, insn->dst_reg, false); 15672 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15673 src_reg->type == PTR_TO_PACKET) || 15674 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15675 src_reg->type == PTR_TO_PACKET_META)) { 15676 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15677 find_good_pkt_pointers(other_branch, src_reg, 15678 src_reg->type, false); 15679 mark_pkt_end(this_branch, insn->src_reg, true); 15680 } else { 15681 return false; 15682 } 15683 break; 15684 case BPF_JLE: 15685 if ((dst_reg->type == PTR_TO_PACKET && 15686 src_reg->type == PTR_TO_PACKET_END) || 15687 (dst_reg->type == PTR_TO_PACKET_META && 15688 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15689 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15690 find_good_pkt_pointers(other_branch, dst_reg, 15691 dst_reg->type, false); 15692 mark_pkt_end(this_branch, insn->dst_reg, true); 15693 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15694 src_reg->type == PTR_TO_PACKET) || 15695 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15696 src_reg->type == PTR_TO_PACKET_META)) { 15697 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15698 find_good_pkt_pointers(this_branch, src_reg, 15699 src_reg->type, true); 15700 mark_pkt_end(other_branch, insn->src_reg, false); 15701 } else { 15702 return false; 15703 } 15704 break; 15705 default: 15706 return false; 15707 } 15708 15709 return true; 15710 } 15711 15712 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 15713 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 15714 { 15715 struct linked_reg *e; 15716 15717 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 15718 return; 15719 15720 e = linked_regs_push(reg_set); 15721 if (e) { 15722 e->frameno = frameno; 15723 e->is_reg = is_reg; 15724 e->regno = spi_or_reg; 15725 } else { 15726 clear_scalar_id(reg); 15727 } 15728 } 15729 15730 /* For all R being scalar registers or spilled scalar registers 15731 * in verifier state, save R in linked_regs if R->id == id. 15732 * If there are too many Rs sharing same id, reset id for leftover Rs. 15733 */ 15734 static void collect_linked_regs(struct bpf_verifier_env *env, 15735 struct bpf_verifier_state *vstate, 15736 u32 id, 15737 struct linked_regs *linked_regs) 15738 { 15739 struct bpf_insn_aux_data *aux = env->insn_aux_data; 15740 struct bpf_func_state *func; 15741 struct bpf_reg_state *reg; 15742 u16 live_regs; 15743 int i, j; 15744 15745 id = id & ~BPF_ADD_CONST; 15746 for (i = vstate->curframe; i >= 0; i--) { 15747 live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before; 15748 func = vstate->frame[i]; 15749 for (j = 0; j < BPF_REG_FP; j++) { 15750 if (!(live_regs & BIT(j))) 15751 continue; 15752 reg = &func->regs[j]; 15753 __collect_linked_regs(linked_regs, reg, id, i, j, true); 15754 } 15755 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 15756 if (!bpf_is_spilled_reg(&func->stack[j])) 15757 continue; 15758 reg = &func->stack[j].spilled_ptr; 15759 __collect_linked_regs(linked_regs, reg, id, i, j, false); 15760 } 15761 } 15762 } 15763 15764 /* For all R in linked_regs, copy known_reg range into R 15765 * if R->id == known_reg->id. 15766 */ 15767 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate, 15768 struct bpf_reg_state *known_reg, struct linked_regs *linked_regs) 15769 { 15770 struct bpf_reg_state fake_reg; 15771 struct bpf_reg_state *reg; 15772 struct linked_reg *e; 15773 int i; 15774 15775 for (i = 0; i < linked_regs->cnt; ++i) { 15776 e = &linked_regs->entries[i]; 15777 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 15778 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 15779 if (reg->type != SCALAR_VALUE || reg == known_reg) 15780 continue; 15781 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15782 continue; 15783 /* 15784 * Skip mixed 32/64-bit links: the delta relationship doesn't 15785 * hold across different ALU widths. 15786 */ 15787 if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST) 15788 continue; 15789 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15790 reg->delta == known_reg->delta) { 15791 s32 saved_subreg_def = reg->subreg_def; 15792 15793 *reg = *known_reg; 15794 reg->subreg_def = saved_subreg_def; 15795 } else { 15796 s32 saved_subreg_def = reg->subreg_def; 15797 s32 saved_off = reg->delta; 15798 u32 saved_id = reg->id; 15799 15800 fake_reg.type = SCALAR_VALUE; 15801 __mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta); 15802 15803 /* reg = known_reg; reg += delta */ 15804 *reg = *known_reg; 15805 /* 15806 * Must preserve off, id and subreg_def flag, 15807 * otherwise another sync_linked_regs() will be incorrect. 15808 */ 15809 reg->delta = saved_off; 15810 reg->id = saved_id; 15811 reg->subreg_def = saved_subreg_def; 15812 15813 scalar32_min_max_add(reg, &fake_reg); 15814 scalar_min_max_add(reg, &fake_reg); 15815 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15816 if ((reg->id | known_reg->id) & BPF_ADD_CONST32) 15817 zext_32_to_64(reg); 15818 reg_bounds_sync(reg); 15819 } 15820 if (e->is_reg) 15821 mark_reg_scratched(env, e->regno); 15822 else 15823 mark_stack_slot_scratched(env, e->spi); 15824 } 15825 } 15826 15827 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15828 struct bpf_insn *insn, int *insn_idx) 15829 { 15830 struct bpf_verifier_state *this_branch = env->cur_state; 15831 struct bpf_verifier_state *other_branch; 15832 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15833 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15834 struct bpf_reg_state *eq_branch_regs; 15835 struct linked_regs linked_regs = {}; 15836 u8 opcode = BPF_OP(insn->code); 15837 int insn_flags = 0; 15838 bool is_jmp32; 15839 int pred = -1; 15840 int err; 15841 15842 /* Only conditional jumps are expected to reach here. */ 15843 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15844 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15845 return -EINVAL; 15846 } 15847 15848 if (opcode == BPF_JCOND) { 15849 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15850 int idx = *insn_idx; 15851 15852 prev_st = find_prev_entry(env, cur_st->parent, idx); 15853 15854 /* branch out 'fallthrough' insn as a new state to explore */ 15855 queued_st = push_stack(env, idx + 1, idx, false); 15856 if (IS_ERR(queued_st)) 15857 return PTR_ERR(queued_st); 15858 15859 queued_st->may_goto_depth++; 15860 if (prev_st) 15861 widen_imprecise_scalars(env, prev_st, queued_st); 15862 *insn_idx += insn->off; 15863 return 0; 15864 } 15865 15866 /* check src2 operand */ 15867 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15868 if (err) 15869 return err; 15870 15871 dst_reg = ®s[insn->dst_reg]; 15872 if (BPF_SRC(insn->code) == BPF_X) { 15873 /* check src1 operand */ 15874 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15875 if (err) 15876 return err; 15877 15878 src_reg = ®s[insn->src_reg]; 15879 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15880 is_pointer_value(env, insn->src_reg)) { 15881 verbose(env, "R%d pointer comparison prohibited\n", 15882 insn->src_reg); 15883 return -EACCES; 15884 } 15885 15886 if (src_reg->type == PTR_TO_STACK) 15887 insn_flags |= INSN_F_SRC_REG_STACK; 15888 if (dst_reg->type == PTR_TO_STACK) 15889 insn_flags |= INSN_F_DST_REG_STACK; 15890 } else { 15891 src_reg = &env->fake_reg[0]; 15892 memset(src_reg, 0, sizeof(*src_reg)); 15893 src_reg->type = SCALAR_VALUE; 15894 __mark_reg_known(src_reg, insn->imm); 15895 15896 if (dst_reg->type == PTR_TO_STACK) 15897 insn_flags |= INSN_F_DST_REG_STACK; 15898 } 15899 15900 if (insn_flags) { 15901 err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, 0); 15902 if (err) 15903 return err; 15904 } 15905 15906 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 15907 env->false_reg1 = *dst_reg; 15908 env->false_reg2 = *src_reg; 15909 env->true_reg1 = *dst_reg; 15910 env->true_reg2 = *src_reg; 15911 pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32); 15912 if (pred >= 0) { 15913 /* If we get here with a dst_reg pointer type it is because 15914 * above is_branch_taken() special cased the 0 comparison. 15915 */ 15916 if (!__is_pointer_value(false, dst_reg)) 15917 err = mark_chain_precision(env, insn->dst_reg); 15918 if (BPF_SRC(insn->code) == BPF_X && !err && 15919 !__is_pointer_value(false, src_reg)) 15920 err = mark_chain_precision(env, insn->src_reg); 15921 if (err) 15922 return err; 15923 } 15924 15925 if (pred == 1) { 15926 /* Only follow the goto, ignore fall-through. If needed, push 15927 * the fall-through branch for simulation under speculative 15928 * execution. 15929 */ 15930 if (!env->bypass_spec_v1) { 15931 err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx); 15932 if (err < 0) 15933 return err; 15934 } 15935 if (env->log.level & BPF_LOG_LEVEL) 15936 print_insn_state(env, this_branch, this_branch->curframe); 15937 *insn_idx += insn->off; 15938 return 0; 15939 } else if (pred == 0) { 15940 /* Only follow the fall-through branch, since that's where the 15941 * program will go. If needed, push the goto branch for 15942 * simulation under speculative execution. 15943 */ 15944 if (!env->bypass_spec_v1) { 15945 err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1, 15946 *insn_idx); 15947 if (err < 0) 15948 return err; 15949 } 15950 if (env->log.level & BPF_LOG_LEVEL) 15951 print_insn_state(env, this_branch, this_branch->curframe); 15952 return 0; 15953 } 15954 15955 /* Push scalar registers sharing same ID to jump history, 15956 * do this before creating 'other_branch', so that both 15957 * 'this_branch' and 'other_branch' share this history 15958 * if parent state is created. 15959 */ 15960 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 15961 collect_linked_regs(env, this_branch, src_reg->id, &linked_regs); 15962 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 15963 collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs); 15964 if (linked_regs.cnt > 1) { 15965 err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, linked_regs_pack(&linked_regs)); 15966 if (err) 15967 return err; 15968 } 15969 15970 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); 15971 if (IS_ERR(other_branch)) 15972 return PTR_ERR(other_branch); 15973 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 15974 15975 err = regs_bounds_sanity_check_branches(env); 15976 if (err) 15977 return err; 15978 15979 *dst_reg = env->false_reg1; 15980 *src_reg = env->false_reg2; 15981 other_branch_regs[insn->dst_reg] = env->true_reg1; 15982 if (BPF_SRC(insn->code) == BPF_X) 15983 other_branch_regs[insn->src_reg] = env->true_reg2; 15984 15985 if (BPF_SRC(insn->code) == BPF_X && 15986 src_reg->type == SCALAR_VALUE && src_reg->id && 15987 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 15988 sync_linked_regs(env, this_branch, src_reg, &linked_regs); 15989 sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg], 15990 &linked_regs); 15991 } 15992 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 15993 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 15994 sync_linked_regs(env, this_branch, dst_reg, &linked_regs); 15995 sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg], 15996 &linked_regs); 15997 } 15998 15999 /* if one pointer register is compared to another pointer 16000 * register check if PTR_MAYBE_NULL could be lifted. 16001 * E.g. register A - maybe null 16002 * register B - not null 16003 * for JNE A, B, ... - A is not null in the false branch; 16004 * for JEQ A, B, ... - A is not null in the true branch. 16005 * 16006 * Since PTR_TO_BTF_ID points to a kernel struct that does 16007 * not need to be null checked by the BPF program, i.e., 16008 * could be null even without PTR_MAYBE_NULL marking, so 16009 * only propagate nullness when neither reg is that type. 16010 */ 16011 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16012 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16013 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16014 base_type(src_reg->type) != PTR_TO_BTF_ID && 16015 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16016 eq_branch_regs = NULL; 16017 switch (opcode) { 16018 case BPF_JEQ: 16019 eq_branch_regs = other_branch_regs; 16020 break; 16021 case BPF_JNE: 16022 eq_branch_regs = regs; 16023 break; 16024 default: 16025 /* do nothing */ 16026 break; 16027 } 16028 if (eq_branch_regs) { 16029 if (type_may_be_null(src_reg->type)) 16030 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16031 else 16032 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16033 } 16034 } 16035 16036 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16037 * Also does the same detection for a register whose the value is 16038 * known to be 0. 16039 * NOTE: these optimizations below are related with pointer comparison 16040 * which will never be JMP32. 16041 */ 16042 if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16043 type_may_be_null(dst_reg->type) && 16044 ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) || 16045 (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) { 16046 /* Mark all identical registers in each branch as either 16047 * safe or unknown depending R == 0 or R != 0 conditional. 16048 */ 16049 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16050 opcode == BPF_JNE); 16051 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16052 opcode == BPF_JEQ); 16053 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16054 this_branch, other_branch) && 16055 is_pointer_value(env, insn->dst_reg)) { 16056 verbose(env, "R%d pointer comparison prohibited\n", 16057 insn->dst_reg); 16058 return -EACCES; 16059 } 16060 if (env->log.level & BPF_LOG_LEVEL) 16061 print_insn_state(env, this_branch, this_branch->curframe); 16062 return 0; 16063 } 16064 16065 /* verify BPF_LD_IMM64 instruction */ 16066 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16067 { 16068 struct bpf_insn_aux_data *aux = cur_aux(env); 16069 struct bpf_reg_state *regs = cur_regs(env); 16070 struct bpf_reg_state *dst_reg; 16071 struct bpf_map *map; 16072 int err; 16073 16074 if (BPF_SIZE(insn->code) != BPF_DW) { 16075 verbose(env, "invalid BPF_LD_IMM insn\n"); 16076 return -EINVAL; 16077 } 16078 16079 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16080 if (err) 16081 return err; 16082 16083 dst_reg = ®s[insn->dst_reg]; 16084 if (insn->src_reg == 0) { 16085 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16086 16087 dst_reg->type = SCALAR_VALUE; 16088 __mark_reg_known(®s[insn->dst_reg], imm); 16089 return 0; 16090 } 16091 16092 /* All special src_reg cases are listed below. From this point onwards 16093 * we either succeed and assign a corresponding dst_reg->type after 16094 * zeroing the offset, or fail and reject the program. 16095 */ 16096 mark_reg_known_zero(env, regs, insn->dst_reg); 16097 16098 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16099 dst_reg->type = aux->btf_var.reg_type; 16100 switch (base_type(dst_reg->type)) { 16101 case PTR_TO_MEM: 16102 dst_reg->mem_size = aux->btf_var.mem_size; 16103 break; 16104 case PTR_TO_BTF_ID: 16105 dst_reg->btf = aux->btf_var.btf; 16106 dst_reg->btf_id = aux->btf_var.btf_id; 16107 break; 16108 default: 16109 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 16110 return -EFAULT; 16111 } 16112 return 0; 16113 } 16114 16115 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16116 struct bpf_prog_aux *aux = env->prog->aux; 16117 u32 subprogno = bpf_find_subprog(env, 16118 env->insn_idx + insn->imm + 1); 16119 16120 if (!aux->func_info) { 16121 verbose(env, "missing btf func_info\n"); 16122 return -EINVAL; 16123 } 16124 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16125 verbose(env, "callback function not static\n"); 16126 return -EINVAL; 16127 } 16128 16129 dst_reg->type = PTR_TO_FUNC; 16130 dst_reg->subprogno = subprogno; 16131 return 0; 16132 } 16133 16134 map = env->used_maps[aux->map_index]; 16135 16136 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16137 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16138 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16139 __mark_reg_unknown(env, dst_reg); 16140 dst_reg->map_ptr = map; 16141 return 0; 16142 } 16143 __mark_reg_known(dst_reg, aux->map_off); 16144 dst_reg->type = PTR_TO_MAP_VALUE; 16145 dst_reg->map_ptr = map; 16146 WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY && 16147 map->max_entries != 1); 16148 /* We want reg->id to be same (0) as map_value is not distinct */ 16149 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16150 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16151 dst_reg->type = CONST_PTR_TO_MAP; 16152 dst_reg->map_ptr = map; 16153 } else { 16154 verifier_bug(env, "unexpected src reg value for ldimm64"); 16155 return -EFAULT; 16156 } 16157 16158 return 0; 16159 } 16160 16161 static bool may_access_skb(enum bpf_prog_type type) 16162 { 16163 switch (type) { 16164 case BPF_PROG_TYPE_SOCKET_FILTER: 16165 case BPF_PROG_TYPE_SCHED_CLS: 16166 case BPF_PROG_TYPE_SCHED_ACT: 16167 return true; 16168 default: 16169 return false; 16170 } 16171 } 16172 16173 /* verify safety of LD_ABS|LD_IND instructions: 16174 * - they can only appear in the programs where ctx == skb 16175 * - since they are wrappers of function calls, they scratch R1-R5 registers, 16176 * preserve R6-R9, and store return value into R0 16177 * 16178 * Implicit input: 16179 * ctx == skb == R6 == CTX 16180 * 16181 * Explicit input: 16182 * SRC == any register 16183 * IMM == 32-bit immediate 16184 * 16185 * Output: 16186 * R0 - 8/16/32-bit skb data converted to cpu endianness 16187 */ 16188 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 16189 { 16190 struct bpf_reg_state *regs = cur_regs(env); 16191 static const int ctx_reg = BPF_REG_6; 16192 u8 mode = BPF_MODE(insn->code); 16193 int i, err; 16194 16195 if (!may_access_skb(resolve_prog_type(env->prog))) { 16196 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 16197 return -EINVAL; 16198 } 16199 16200 if (!env->ops->gen_ld_abs) { 16201 verifier_bug(env, "gen_ld_abs is null"); 16202 return -EFAULT; 16203 } 16204 16205 /* check whether implicit source operand (register R6) is readable */ 16206 err = check_reg_arg(env, ctx_reg, SRC_OP); 16207 if (err) 16208 return err; 16209 16210 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 16211 * gen_ld_abs() may terminate the program at runtime, leading to 16212 * reference leak. 16213 */ 16214 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 16215 if (err) 16216 return err; 16217 16218 if (regs[ctx_reg].type != PTR_TO_CTX) { 16219 verbose(env, 16220 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 16221 return -EINVAL; 16222 } 16223 16224 if (mode == BPF_IND) { 16225 /* check explicit source operand */ 16226 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16227 if (err) 16228 return err; 16229 } 16230 16231 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 16232 if (err < 0) 16233 return err; 16234 16235 /* reset caller saved regs to unreadable */ 16236 for (i = 0; i < CALLER_SAVED_REGS; i++) { 16237 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 16238 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 16239 } 16240 16241 /* mark destination R0 register as readable, since it contains 16242 * the value fetched from the packet. 16243 * Already marked as written above. 16244 */ 16245 mark_reg_unknown(env, regs, BPF_REG_0); 16246 /* ld_abs load up to 32-bit skb data. */ 16247 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 16248 /* 16249 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0 16250 * which must be explored by the verifier when in a subprog. 16251 */ 16252 if (env->cur_state->curframe) { 16253 struct bpf_verifier_state *branch; 16254 16255 mark_reg_scratched(env, BPF_REG_0); 16256 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 16257 if (IS_ERR(branch)) 16258 return PTR_ERR(branch); 16259 mark_reg_known_zero(env, regs, BPF_REG_0); 16260 err = prepare_func_exit(env, &env->insn_idx); 16261 if (err) 16262 return err; 16263 env->insn_idx--; 16264 } 16265 return 0; 16266 } 16267 16268 16269 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range) 16270 { 16271 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16272 16273 /* Default return value range. */ 16274 *range = retval_range(0, 1); 16275 16276 switch (prog_type) { 16277 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 16278 switch (env->prog->expected_attach_type) { 16279 case BPF_CGROUP_UDP4_RECVMSG: 16280 case BPF_CGROUP_UDP6_RECVMSG: 16281 case BPF_CGROUP_UNIX_RECVMSG: 16282 case BPF_CGROUP_INET4_GETPEERNAME: 16283 case BPF_CGROUP_INET6_GETPEERNAME: 16284 case BPF_CGROUP_UNIX_GETPEERNAME: 16285 case BPF_CGROUP_INET4_GETSOCKNAME: 16286 case BPF_CGROUP_INET6_GETSOCKNAME: 16287 case BPF_CGROUP_UNIX_GETSOCKNAME: 16288 *range = retval_range(1, 1); 16289 break; 16290 case BPF_CGROUP_INET4_BIND: 16291 case BPF_CGROUP_INET6_BIND: 16292 *range = retval_range(0, 3); 16293 break; 16294 default: 16295 break; 16296 } 16297 break; 16298 case BPF_PROG_TYPE_CGROUP_SKB: 16299 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) 16300 *range = retval_range(0, 3); 16301 break; 16302 case BPF_PROG_TYPE_CGROUP_SOCK: 16303 case BPF_PROG_TYPE_SOCK_OPS: 16304 case BPF_PROG_TYPE_CGROUP_DEVICE: 16305 case BPF_PROG_TYPE_CGROUP_SYSCTL: 16306 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 16307 break; 16308 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16309 if (!env->prog->aux->attach_btf_id) 16310 return false; 16311 *range = retval_range(0, 0); 16312 break; 16313 case BPF_PROG_TYPE_TRACING: 16314 switch (env->prog->expected_attach_type) { 16315 case BPF_TRACE_FENTRY: 16316 case BPF_TRACE_FEXIT: 16317 case BPF_TRACE_FSESSION: 16318 *range = retval_range(0, 0); 16319 break; 16320 case BPF_TRACE_RAW_TP: 16321 case BPF_MODIFY_RETURN: 16322 return false; 16323 case BPF_TRACE_ITER: 16324 default: 16325 break; 16326 } 16327 break; 16328 case BPF_PROG_TYPE_KPROBE: 16329 switch (env->prog->expected_attach_type) { 16330 case BPF_TRACE_KPROBE_SESSION: 16331 case BPF_TRACE_UPROBE_SESSION: 16332 break; 16333 default: 16334 return false; 16335 } 16336 break; 16337 case BPF_PROG_TYPE_SK_LOOKUP: 16338 *range = retval_range(SK_DROP, SK_PASS); 16339 break; 16340 16341 case BPF_PROG_TYPE_LSM: 16342 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 16343 /* no range found, any return value is allowed */ 16344 if (!get_func_retval_range(env->prog, range)) 16345 return false; 16346 /* no restricted range, any return value is allowed */ 16347 if (range->minval == S32_MIN && range->maxval == S32_MAX) 16348 return false; 16349 range->return_32bit = true; 16350 } else if (!env->prog->aux->attach_func_proto->type) { 16351 /* Make sure programs that attach to void 16352 * hooks don't try to modify return value. 16353 */ 16354 *range = retval_range(1, 1); 16355 } 16356 break; 16357 16358 case BPF_PROG_TYPE_NETFILTER: 16359 *range = retval_range(NF_DROP, NF_ACCEPT); 16360 break; 16361 case BPF_PROG_TYPE_STRUCT_OPS: 16362 *range = retval_range(0, 0); 16363 break; 16364 case BPF_PROG_TYPE_EXT: 16365 /* freplace program can return anything as its return value 16366 * depends on the to-be-replaced kernel func or bpf program. 16367 */ 16368 default: 16369 return false; 16370 } 16371 16372 /* Continue calculating. */ 16373 16374 return true; 16375 } 16376 16377 static bool program_returns_void(struct bpf_verifier_env *env) 16378 { 16379 const struct bpf_prog *prog = env->prog; 16380 enum bpf_prog_type prog_type = prog->type; 16381 16382 switch (prog_type) { 16383 case BPF_PROG_TYPE_LSM: 16384 /* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */ 16385 if (prog->expected_attach_type != BPF_LSM_CGROUP && 16386 !prog->aux->attach_func_proto->type) 16387 return true; 16388 break; 16389 case BPF_PROG_TYPE_STRUCT_OPS: 16390 if (!prog->aux->attach_func_proto->type) 16391 return true; 16392 break; 16393 case BPF_PROG_TYPE_EXT: 16394 /* 16395 * If the actual program is an extension, let it 16396 * return void - attaching will succeed only if the 16397 * program being replaced also returns void, and since 16398 * it has passed verification its actual type doesn't matter. 16399 */ 16400 if (subprog_returns_void(env, 0)) 16401 return true; 16402 break; 16403 default: 16404 break; 16405 } 16406 return false; 16407 } 16408 16409 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 16410 { 16411 const char *exit_ctx = "At program exit"; 16412 struct tnum enforce_attach_type_range = tnum_unknown; 16413 const struct bpf_prog *prog = env->prog; 16414 struct bpf_reg_state *reg = reg_state(env, regno); 16415 struct bpf_retval_range range = retval_range(0, 1); 16416 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16417 struct bpf_func_state *frame = env->cur_state->frame[0]; 16418 const struct btf_type *reg_type, *ret_type = NULL; 16419 int err; 16420 16421 /* LSM and struct_ops func-ptr's return type could be "void" */ 16422 if (!frame->in_async_callback_fn && program_returns_void(env)) 16423 return 0; 16424 16425 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) { 16426 /* Allow a struct_ops program to return a referenced kptr if it 16427 * matches the operator's return type and is in its unmodified 16428 * form. A scalar zero (i.e., a null pointer) is also allowed. 16429 */ 16430 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 16431 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 16432 prog->aux->attach_func_proto->type, 16433 NULL); 16434 if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg)) 16435 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 16436 } 16437 16438 /* eBPF calling convention is such that R0 is used 16439 * to return the value from eBPF program. 16440 * Make sure that it's readable at this time 16441 * of bpf_exit, which means that program wrote 16442 * something into it earlier 16443 */ 16444 err = check_reg_arg(env, regno, SRC_OP); 16445 if (err) 16446 return err; 16447 16448 if (is_pointer_value(env, regno)) { 16449 verbose(env, "R%d leaks addr as return value\n", regno); 16450 return -EACCES; 16451 } 16452 16453 if (frame->in_async_callback_fn) { 16454 exit_ctx = "At async callback return"; 16455 range = frame->callback_ret_range; 16456 goto enforce_retval; 16457 } 16458 16459 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type) 16460 return 0; 16461 16462 if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)) 16463 enforce_attach_type_range = tnum_range(2, 3); 16464 16465 if (!return_retval_range(env, &range)) 16466 return 0; 16467 16468 enforce_retval: 16469 if (reg->type != SCALAR_VALUE) { 16470 verbose(env, "%s the register R%d is not a known value (%s)\n", 16471 exit_ctx, regno, reg_type_str(env, reg->type)); 16472 return -EINVAL; 16473 } 16474 16475 err = mark_chain_precision(env, regno); 16476 if (err) 16477 return err; 16478 16479 if (!retval_range_within(range, reg)) { 16480 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 16481 if (prog->expected_attach_type == BPF_LSM_CGROUP && 16482 prog_type == BPF_PROG_TYPE_LSM && 16483 !prog->aux->attach_func_proto->type) 16484 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 16485 return -EINVAL; 16486 } 16487 16488 if (!tnum_is_unknown(enforce_attach_type_range) && 16489 tnum_in(enforce_attach_type_range, reg->var_off)) 16490 env->prog->enforce_expected_attach_type = 1; 16491 return 0; 16492 } 16493 16494 static int check_global_subprog_return_code(struct bpf_verifier_env *env) 16495 { 16496 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 16497 struct bpf_func_state *cur_frame = cur_func(env); 16498 int err; 16499 16500 if (subprog_returns_void(env, cur_frame->subprogno)) 16501 return 0; 16502 16503 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 16504 if (err) 16505 return err; 16506 16507 /* Pointers to arena are safe to pass between subprograms. */ 16508 if (is_arena_reg(env, BPF_REG_0)) 16509 return 0; 16510 16511 if (is_pointer_value(env, BPF_REG_0)) { 16512 verbose(env, "R%d leaks addr as return value\n", BPF_REG_0); 16513 return -EACCES; 16514 } 16515 16516 if (reg->type != SCALAR_VALUE) { 16517 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 16518 reg_type_str(env, reg->type)); 16519 return -EINVAL; 16520 } 16521 16522 return 0; 16523 } 16524 16525 /* Bitmask with 1s for all caller saved registers */ 16526 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16527 16528 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16529 * replacement patch is presumed to follow bpf_fastcall contract 16530 * (see mark_fastcall_pattern_for_call() below). 16531 */ 16532 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 16533 { 16534 switch (imm) { 16535 #ifdef CONFIG_X86_64 16536 case BPF_FUNC_get_smp_processor_id: 16537 #ifdef CONFIG_SMP 16538 case BPF_FUNC_get_current_task_btf: 16539 case BPF_FUNC_get_current_task: 16540 #endif 16541 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 16542 #endif 16543 default: 16544 return false; 16545 } 16546 } 16547 16548 /* If @call is a kfunc or helper call, fills @cs and returns true, 16549 * otherwise returns false. 16550 */ 16551 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 16552 struct bpf_call_summary *cs) 16553 { 16554 struct bpf_kfunc_call_arg_meta meta; 16555 const struct bpf_func_proto *fn; 16556 int i; 16557 16558 if (bpf_helper_call(call)) { 16559 16560 if (bpf_get_helper_proto(env, call->imm, &fn) < 0) 16561 /* error would be reported later */ 16562 return false; 16563 cs->fastcall = fn->allow_fastcall && 16564 (bpf_verifier_inlines_helper_call(env, call->imm) || 16565 bpf_jit_inlines_helper_call(call->imm)); 16566 cs->is_void = fn->ret_type == RET_VOID; 16567 cs->num_params = 0; 16568 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 16569 if (fn->arg_type[i] == ARG_DONTCARE) 16570 break; 16571 cs->num_params++; 16572 } 16573 return true; 16574 } 16575 16576 if (bpf_pseudo_kfunc_call(call)) { 16577 int err; 16578 16579 err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta); 16580 if (err < 0) 16581 /* error would be reported later */ 16582 return false; 16583 cs->num_params = btf_type_vlen(meta.func_proto); 16584 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 16585 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 16586 return true; 16587 } 16588 16589 return false; 16590 } 16591 16592 /* LLVM define a bpf_fastcall function attribute. 16593 * This attribute means that function scratches only some of 16594 * the caller saved registers defined by ABI. 16595 * For BPF the set of such registers could be defined as follows: 16596 * - R0 is scratched only if function is non-void; 16597 * - R1-R5 are scratched only if corresponding parameter type is defined 16598 * in the function prototype. 16599 * 16600 * The contract between kernel and clang allows to simultaneously use 16601 * such functions and maintain backwards compatibility with old 16602 * kernels that don't understand bpf_fastcall calls: 16603 * 16604 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 16605 * registers are not scratched by the call; 16606 * 16607 * - as a post-processing step, clang visits each bpf_fastcall call and adds 16608 * spill/fill for every live r0-r5; 16609 * 16610 * - stack offsets used for the spill/fill are allocated as lowest 16611 * stack offsets in whole function and are not used for any other 16612 * purposes; 16613 * 16614 * - when kernel loads a program, it looks for such patterns 16615 * (bpf_fastcall function surrounded by spills/fills) and checks if 16616 * spill/fill stack offsets are used exclusively in fastcall patterns; 16617 * 16618 * - if so, and if verifier or current JIT inlines the call to the 16619 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 16620 * spill/fill pairs; 16621 * 16622 * - when old kernel loads a program, presence of spill/fill pairs 16623 * keeps BPF program valid, albeit slightly less efficient. 16624 * 16625 * For example: 16626 * 16627 * r1 = 1; 16628 * r2 = 2; 16629 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16630 * *(u64 *)(r10 - 16) = r2; r2 = 2; 16631 * call %[to_be_inlined] --> call %[to_be_inlined] 16632 * r2 = *(u64 *)(r10 - 16); r0 = r1; 16633 * r1 = *(u64 *)(r10 - 8); r0 += r2; 16634 * r0 = r1; exit; 16635 * r0 += r2; 16636 * exit; 16637 * 16638 * The purpose of mark_fastcall_pattern_for_call is to: 16639 * - look for such patterns; 16640 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 16641 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 16642 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 16643 * at which bpf_fastcall spill/fill stack slots start; 16644 * - update env->subprog_info[*]->keep_fastcall_stack. 16645 * 16646 * The .fastcall_pattern and .fastcall_stack_off are used by 16647 * check_fastcall_stack_contract() to check if every stack access to 16648 * fastcall spill/fill stack slot originates from spill/fill 16649 * instructions, members of fastcall patterns. 16650 * 16651 * If such condition holds true for a subprogram, fastcall patterns could 16652 * be rewritten by remove_fastcall_spills_fills(). 16653 * Otherwise bpf_fastcall patterns are not changed in the subprogram 16654 * (code, presumably, generated by an older clang version). 16655 * 16656 * For example, it is *not* safe to remove spill/fill below: 16657 * 16658 * r1 = 1; 16659 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16660 * call %[to_be_inlined] --> call %[to_be_inlined] 16661 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 16662 * r0 = *(u64 *)(r10 - 8); r0 += r1; 16663 * r0 += r1; exit; 16664 * exit; 16665 */ 16666 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 16667 struct bpf_subprog_info *subprog, 16668 int insn_idx, s16 lowest_off) 16669 { 16670 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 16671 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 16672 u32 clobbered_regs_mask; 16673 struct bpf_call_summary cs; 16674 u32 expected_regs_mask; 16675 s16 off; 16676 int i; 16677 16678 if (!bpf_get_call_summary(env, call, &cs)) 16679 return; 16680 16681 /* A bitmask specifying which caller saved registers are clobbered 16682 * by a call to a helper/kfunc *as if* this helper/kfunc follows 16683 * bpf_fastcall contract: 16684 * - includes R0 if function is non-void; 16685 * - includes R1-R5 if corresponding parameter has is described 16686 * in the function prototype. 16687 */ 16688 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 16689 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 16690 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 16691 16692 /* match pairs of form: 16693 * 16694 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 16695 * ... 16696 * call %[to_be_inlined] 16697 * ... 16698 * rX = *(u64 *)(r10 - Y) 16699 */ 16700 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 16701 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 16702 break; 16703 stx = &insns[insn_idx - i]; 16704 ldx = &insns[insn_idx + i]; 16705 /* must be a stack spill/fill pair */ 16706 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 16707 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 16708 stx->dst_reg != BPF_REG_10 || 16709 ldx->src_reg != BPF_REG_10) 16710 break; 16711 /* must be a spill/fill for the same reg */ 16712 if (stx->src_reg != ldx->dst_reg) 16713 break; 16714 /* must be one of the previously unseen registers */ 16715 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 16716 break; 16717 /* must be a spill/fill for the same expected offset, 16718 * no need to check offset alignment, BPF_DW stack access 16719 * is always 8-byte aligned. 16720 */ 16721 if (stx->off != off || ldx->off != off) 16722 break; 16723 expected_regs_mask &= ~BIT(stx->src_reg); 16724 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 16725 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 16726 } 16727 if (i == 1) 16728 return; 16729 16730 /* Conditionally set 'fastcall_spills_num' to allow forward 16731 * compatibility when more helper functions are marked as 16732 * bpf_fastcall at compile time than current kernel supports, e.g: 16733 * 16734 * 1: *(u64 *)(r10 - 8) = r1 16735 * 2: call A ;; assume A is bpf_fastcall for current kernel 16736 * 3: r1 = *(u64 *)(r10 - 8) 16737 * 4: *(u64 *)(r10 - 8) = r1 16738 * 5: call B ;; assume B is not bpf_fastcall for current kernel 16739 * 6: r1 = *(u64 *)(r10 - 8) 16740 * 16741 * There is no need to block bpf_fastcall rewrite for such program. 16742 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 16743 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 16744 * does not remove spill/fill pair {4,6}. 16745 */ 16746 if (cs.fastcall) 16747 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 16748 else 16749 subprog->keep_fastcall_stack = 1; 16750 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 16751 } 16752 16753 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 16754 { 16755 struct bpf_subprog_info *subprog = env->subprog_info; 16756 struct bpf_insn *insn; 16757 s16 lowest_off; 16758 int s, i; 16759 16760 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 16761 /* find lowest stack spill offset used in this subprog */ 16762 lowest_off = 0; 16763 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16764 insn = env->prog->insnsi + i; 16765 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 16766 insn->dst_reg != BPF_REG_10) 16767 continue; 16768 lowest_off = min(lowest_off, insn->off); 16769 } 16770 /* use this offset to find fastcall patterns */ 16771 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16772 insn = env->prog->insnsi + i; 16773 if (insn->code != (BPF_JMP | BPF_CALL)) 16774 continue; 16775 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 16776 } 16777 } 16778 return 0; 16779 } 16780 16781 static void adjust_btf_func(struct bpf_verifier_env *env) 16782 { 16783 struct bpf_prog_aux *aux = env->prog->aux; 16784 int i; 16785 16786 if (!aux->func_info) 16787 return; 16788 16789 /* func_info is not available for hidden subprogs */ 16790 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16791 aux->func_info[i].insn_off = env->subprog_info[i].start; 16792 } 16793 16794 /* Find id in idset and increment its count, or add new entry */ 16795 static void idset_cnt_inc(struct bpf_idset *idset, u32 id) 16796 { 16797 u32 i; 16798 16799 for (i = 0; i < idset->num_ids; i++) { 16800 if (idset->entries[i].id == id) { 16801 idset->entries[i].cnt++; 16802 return; 16803 } 16804 } 16805 /* New id */ 16806 if (idset->num_ids < BPF_ID_MAP_SIZE) { 16807 idset->entries[idset->num_ids].id = id; 16808 idset->entries[idset->num_ids].cnt = 1; 16809 idset->num_ids++; 16810 } 16811 } 16812 16813 /* Find id in idset and return its count, or 0 if not found */ 16814 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id) 16815 { 16816 u32 i; 16817 16818 for (i = 0; i < idset->num_ids; i++) { 16819 if (idset->entries[i].id == id) 16820 return idset->entries[i].cnt; 16821 } 16822 return 0; 16823 } 16824 16825 /* 16826 * Clear singular scalar ids in a state. 16827 * A register with a non-zero id is called singular if no other register shares 16828 * the same base id. Such registers can be treated as independent (id=0). 16829 */ 16830 void bpf_clear_singular_ids(struct bpf_verifier_env *env, 16831 struct bpf_verifier_state *st) 16832 { 16833 struct bpf_idset *idset = &env->idset_scratch; 16834 struct bpf_func_state *func; 16835 struct bpf_reg_state *reg; 16836 16837 idset->num_ids = 0; 16838 16839 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16840 if (reg->type != SCALAR_VALUE) 16841 continue; 16842 if (!reg->id) 16843 continue; 16844 idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST); 16845 })); 16846 16847 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16848 if (reg->type != SCALAR_VALUE) 16849 continue; 16850 if (!reg->id) 16851 continue; 16852 if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1) 16853 clear_scalar_id(reg); 16854 })); 16855 } 16856 16857 /* Return true if it's OK to have the same insn return a different type. */ 16858 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16859 { 16860 switch (base_type(type)) { 16861 case PTR_TO_CTX: 16862 case PTR_TO_SOCKET: 16863 case PTR_TO_SOCK_COMMON: 16864 case PTR_TO_TCP_SOCK: 16865 case PTR_TO_XDP_SOCK: 16866 case PTR_TO_BTF_ID: 16867 case PTR_TO_ARENA: 16868 return false; 16869 default: 16870 return true; 16871 } 16872 } 16873 16874 /* If an instruction was previously used with particular pointer types, then we 16875 * need to be careful to avoid cases such as the below, where it may be ok 16876 * for one branch accessing the pointer, but not ok for the other branch: 16877 * 16878 * R1 = sock_ptr 16879 * goto X; 16880 * ... 16881 * R1 = some_other_valid_ptr; 16882 * goto X; 16883 * ... 16884 * R2 = *(u32 *)(R1 + 0); 16885 */ 16886 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 16887 { 16888 return src != prev && (!reg_type_mismatch_ok(src) || 16889 !reg_type_mismatch_ok(prev)); 16890 } 16891 16892 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type) 16893 { 16894 switch (base_type(type)) { 16895 case PTR_TO_MEM: 16896 case PTR_TO_BTF_ID: 16897 return true; 16898 default: 16899 return false; 16900 } 16901 } 16902 16903 static bool is_ptr_to_mem(enum bpf_reg_type type) 16904 { 16905 return base_type(type) == PTR_TO_MEM; 16906 } 16907 16908 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 16909 bool allow_trust_mismatch) 16910 { 16911 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 16912 enum bpf_reg_type merged_type; 16913 16914 if (*prev_type == NOT_INIT) { 16915 /* Saw a valid insn 16916 * dst_reg = *(u32 *)(src_reg + off) 16917 * save type to validate intersecting paths 16918 */ 16919 *prev_type = type; 16920 } else if (reg_type_mismatch(type, *prev_type)) { 16921 /* Abuser program is trying to use the same insn 16922 * dst_reg = *(u32*) (src_reg + off) 16923 * with different pointer types: 16924 * src_reg == ctx in one branch and 16925 * src_reg == stack|map in some other branch. 16926 * Reject it. 16927 */ 16928 if (allow_trust_mismatch && 16929 is_ptr_to_mem_or_btf_id(type) && 16930 is_ptr_to_mem_or_btf_id(*prev_type)) { 16931 /* 16932 * Have to support a use case when one path through 16933 * the program yields TRUSTED pointer while another 16934 * is UNTRUSTED. Fallback to UNTRUSTED to generate 16935 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 16936 * Same behavior of MEM_RDONLY flag. 16937 */ 16938 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type)) 16939 merged_type = PTR_TO_MEM; 16940 else 16941 merged_type = PTR_TO_BTF_ID; 16942 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED)) 16943 merged_type |= PTR_UNTRUSTED; 16944 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY)) 16945 merged_type |= MEM_RDONLY; 16946 *prev_type = merged_type; 16947 } else { 16948 verbose(env, "same insn cannot be used with different pointers\n"); 16949 return -EINVAL; 16950 } 16951 } 16952 16953 return 0; 16954 } 16955 16956 enum { 16957 PROCESS_BPF_EXIT = 1, 16958 INSN_IDX_UPDATED = 2, 16959 }; 16960 16961 static int process_bpf_exit_full(struct bpf_verifier_env *env, 16962 bool *do_print_state, 16963 bool exception_exit) 16964 { 16965 struct bpf_func_state *cur_frame = cur_func(env); 16966 16967 /* We must do check_reference_leak here before 16968 * prepare_func_exit to handle the case when 16969 * state->curframe > 0, it may be a callback function, 16970 * for which reference_state must match caller reference 16971 * state when it exits. 16972 */ 16973 int err = check_resource_leak(env, exception_exit, 16974 exception_exit || !env->cur_state->curframe, 16975 exception_exit ? "bpf_throw" : 16976 "BPF_EXIT instruction in main prog"); 16977 if (err) 16978 return err; 16979 16980 /* The side effect of the prepare_func_exit which is 16981 * being skipped is that it frees bpf_func_state. 16982 * Typically, process_bpf_exit will only be hit with 16983 * outermost exit. copy_verifier_state in pop_stack will 16984 * handle freeing of any extra bpf_func_state left over 16985 * from not processing all nested function exits. We 16986 * also skip return code checks as they are not needed 16987 * for exceptional exits. 16988 */ 16989 if (exception_exit) 16990 return PROCESS_BPF_EXIT; 16991 16992 if (env->cur_state->curframe) { 16993 /* exit from nested function */ 16994 err = prepare_func_exit(env, &env->insn_idx); 16995 if (err) 16996 return err; 16997 *do_print_state = true; 16998 return INSN_IDX_UPDATED; 16999 } 17000 17001 /* 17002 * Return from a regular global subprogram differs from return 17003 * from the main program or async/exception callback. 17004 * Main program exit implies return code restrictions 17005 * that depend on program type. 17006 * Exit from exception callback is equivalent to main program exit. 17007 * Exit from async callback implies return code restrictions 17008 * that depend on async scheduling mechanism. 17009 */ 17010 if (cur_frame->subprogno && 17011 !cur_frame->in_async_callback_fn && 17012 !cur_frame->in_exception_callback_fn) 17013 err = check_global_subprog_return_code(env); 17014 else 17015 err = check_return_code(env, BPF_REG_0, "R0"); 17016 if (err) 17017 return err; 17018 return PROCESS_BPF_EXIT; 17019 } 17020 17021 static int indirect_jump_min_max_index(struct bpf_verifier_env *env, 17022 int regno, 17023 struct bpf_map *map, 17024 u32 *pmin_index, u32 *pmax_index) 17025 { 17026 struct bpf_reg_state *reg = reg_state(env, regno); 17027 u64 min_index = reg_umin(reg); 17028 u64 max_index = reg_umax(reg); 17029 const u32 size = 8; 17030 17031 if (min_index > (u64) U32_MAX * size) { 17032 verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg)); 17033 return -ERANGE; 17034 } 17035 if (max_index > (u64) U32_MAX * size) { 17036 verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg)); 17037 return -ERANGE; 17038 } 17039 17040 min_index /= size; 17041 max_index /= size; 17042 17043 if (max_index >= map->max_entries) { 17044 verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n", 17045 regno, min_index, max_index, map->max_entries); 17046 return -EINVAL; 17047 } 17048 17049 *pmin_index = min_index; 17050 *pmax_index = max_index; 17051 return 0; 17052 } 17053 17054 /* gotox *dst_reg */ 17055 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn) 17056 { 17057 struct bpf_verifier_state *other_branch; 17058 struct bpf_reg_state *dst_reg; 17059 struct bpf_map *map; 17060 u32 min_index, max_index; 17061 int err = 0; 17062 int n; 17063 int i; 17064 17065 dst_reg = reg_state(env, insn->dst_reg); 17066 if (dst_reg->type != PTR_TO_INSN) { 17067 verbose(env, "R%d has type %s, expected PTR_TO_INSN\n", 17068 insn->dst_reg, reg_type_str(env, dst_reg->type)); 17069 return -EINVAL; 17070 } 17071 17072 map = dst_reg->map_ptr; 17073 if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg)) 17074 return -EFAULT; 17075 17076 if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env, 17077 "R%d has incorrect map type %d", insn->dst_reg, map->map_type)) 17078 return -EFAULT; 17079 17080 err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index); 17081 if (err) 17082 return err; 17083 17084 /* Ensure that the buffer is large enough */ 17085 if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) { 17086 env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf, 17087 max_index - min_index + 1); 17088 if (!env->gotox_tmp_buf) 17089 return -ENOMEM; 17090 } 17091 17092 n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items); 17093 if (n < 0) 17094 return n; 17095 if (n == 0) { 17096 verbose(env, "register R%d doesn't point to any offset in map id=%d\n", 17097 insn->dst_reg, map->id); 17098 return -EINVAL; 17099 } 17100 17101 for (i = 0; i < n - 1; i++) { 17102 mark_indirect_target(env, env->gotox_tmp_buf->items[i]); 17103 other_branch = push_stack(env, env->gotox_tmp_buf->items[i], 17104 env->insn_idx, env->cur_state->speculative); 17105 if (IS_ERR(other_branch)) 17106 return PTR_ERR(other_branch); 17107 } 17108 env->insn_idx = env->gotox_tmp_buf->items[n-1]; 17109 mark_indirect_target(env, env->insn_idx); 17110 return INSN_IDX_UPDATED; 17111 } 17112 17113 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 17114 { 17115 int err; 17116 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 17117 u8 class = BPF_CLASS(insn->code); 17118 17119 switch (class) { 17120 case BPF_ALU: 17121 case BPF_ALU64: 17122 return check_alu_op(env, insn); 17123 17124 case BPF_LDX: 17125 return check_load_mem(env, insn, false, 17126 BPF_MODE(insn->code) == BPF_MEMSX, 17127 true, "ldx"); 17128 17129 case BPF_STX: 17130 if (BPF_MODE(insn->code) == BPF_ATOMIC) 17131 return check_atomic(env, insn); 17132 return check_store_reg(env, insn, false); 17133 17134 case BPF_ST: { 17135 /* Handle stack arg write (store immediate) */ 17136 if (is_stack_arg_st(insn)) { 17137 struct bpf_verifier_state *vstate = env->cur_state; 17138 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 17139 17140 return check_stack_arg_write(env, state, insn->off, NULL); 17141 } 17142 17143 enum bpf_reg_type dst_reg_type; 17144 17145 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17146 if (err) 17147 return err; 17148 17149 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 17150 17151 err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg, argno_from_reg(insn->dst_reg), 17152 insn->off, BPF_SIZE(insn->code), 17153 BPF_WRITE, -1, false, false); 17154 if (err) 17155 return err; 17156 17157 return save_aux_ptr_type(env, dst_reg_type, false); 17158 } 17159 case BPF_JMP: 17160 case BPF_JMP32: { 17161 u8 opcode = BPF_OP(insn->code); 17162 17163 env->jmps_processed++; 17164 if (opcode == BPF_CALL) { 17165 if (env->cur_state->active_locks) { 17166 if ((insn->src_reg == BPF_REG_0 && 17167 insn->imm != BPF_FUNC_spin_unlock && 17168 insn->imm != BPF_FUNC_kptr_xchg) || 17169 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17170 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) { 17171 verbose(env, 17172 "function calls are not allowed while holding a lock\n"); 17173 return -EINVAL; 17174 } 17175 } 17176 mark_reg_scratched(env, BPF_REG_0); 17177 if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno])) 17178 cur_func(env)->no_stack_arg_load = true; 17179 if (insn->src_reg == BPF_PSEUDO_CALL) 17180 return check_func_call(env, insn, &env->insn_idx); 17181 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17182 return check_kfunc_call(env, insn, &env->insn_idx); 17183 return check_helper_call(env, insn, &env->insn_idx); 17184 } else if (opcode == BPF_JA) { 17185 if (BPF_SRC(insn->code) == BPF_X) 17186 return check_indirect_jump(env, insn); 17187 17188 if (class == BPF_JMP) 17189 env->insn_idx += insn->off + 1; 17190 else 17191 env->insn_idx += insn->imm + 1; 17192 return INSN_IDX_UPDATED; 17193 } else if (opcode == BPF_EXIT) { 17194 return process_bpf_exit_full(env, do_print_state, false); 17195 } 17196 return check_cond_jmp_op(env, insn, &env->insn_idx); 17197 } 17198 case BPF_LD: { 17199 u8 mode = BPF_MODE(insn->code); 17200 17201 if (mode == BPF_ABS || mode == BPF_IND) 17202 return check_ld_abs(env, insn); 17203 17204 if (mode == BPF_IMM) { 17205 err = check_ld_imm(env, insn); 17206 if (err) 17207 return err; 17208 17209 env->insn_idx++; 17210 sanitize_mark_insn_seen(env); 17211 } 17212 return 0; 17213 } 17214 } 17215 /* all class values are handled above. silence compiler warning */ 17216 return -EFAULT; 17217 } 17218 17219 static int do_check(struct bpf_verifier_env *env) 17220 { 17221 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17222 struct bpf_verifier_state *state = env->cur_state; 17223 struct bpf_insn *insns = env->prog->insnsi; 17224 int insn_cnt = env->prog->len; 17225 bool do_print_state = false; 17226 int prev_insn_idx = -1; 17227 17228 for (;;) { 17229 struct bpf_insn *insn; 17230 struct bpf_insn_aux_data *insn_aux; 17231 int err; 17232 17233 /* reset current history entry on each new instruction */ 17234 env->cur_hist_ent = NULL; 17235 17236 env->prev_insn_idx = prev_insn_idx; 17237 if (env->insn_idx >= insn_cnt) { 17238 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17239 env->insn_idx, insn_cnt); 17240 return -EFAULT; 17241 } 17242 17243 insn = &insns[env->insn_idx]; 17244 insn_aux = &env->insn_aux_data[env->insn_idx]; 17245 17246 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17247 verbose(env, 17248 "BPF program is too large. Processed %d insn\n", 17249 env->insn_processed); 17250 return -E2BIG; 17251 } 17252 17253 state->last_insn_idx = env->prev_insn_idx; 17254 state->insn_idx = env->insn_idx; 17255 17256 if (bpf_is_prune_point(env, env->insn_idx)) { 17257 err = bpf_is_state_visited(env, env->insn_idx); 17258 if (err < 0) 17259 return err; 17260 if (err == 1) { 17261 /* found equivalent state, can prune the search */ 17262 if (env->log.level & BPF_LOG_LEVEL) { 17263 if (do_print_state) 17264 verbose(env, "\nfrom %d to %d%s: safe\n", 17265 env->prev_insn_idx, env->insn_idx, 17266 env->cur_state->speculative ? 17267 " (speculative execution)" : ""); 17268 else 17269 verbose(env, "%d: safe\n", env->insn_idx); 17270 } 17271 goto process_bpf_exit; 17272 } 17273 } 17274 17275 if (bpf_is_jmp_point(env, env->insn_idx)) { 17276 err = bpf_push_jmp_history(env, state, 0, 0, 0, 0); 17277 if (err) 17278 return err; 17279 } 17280 17281 if (signal_pending(current)) 17282 return -EAGAIN; 17283 17284 if (need_resched()) 17285 cond_resched(); 17286 17287 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17288 verbose(env, "\nfrom %d to %d%s:", 17289 env->prev_insn_idx, env->insn_idx, 17290 env->cur_state->speculative ? 17291 " (speculative execution)" : ""); 17292 print_verifier_state(env, state, state->curframe, true); 17293 do_print_state = false; 17294 } 17295 17296 if (env->log.level & BPF_LOG_LEVEL) { 17297 if (verifier_state_scratched(env)) 17298 print_insn_state(env, state, state->curframe); 17299 17300 verbose_linfo(env, env->insn_idx, "; "); 17301 env->prev_log_pos = env->log.end_pos; 17302 verbose(env, "%d: ", env->insn_idx); 17303 bpf_verbose_insn(env, insn); 17304 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17305 env->prev_log_pos = env->log.end_pos; 17306 } 17307 17308 if (bpf_prog_is_offloaded(env->prog->aux)) { 17309 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17310 env->prev_insn_idx); 17311 if (err) 17312 return err; 17313 } 17314 17315 sanitize_mark_insn_seen(env); 17316 prev_insn_idx = env->insn_idx; 17317 17318 /* Sanity check: precomputed constants must match verifier state */ 17319 if (!state->speculative && insn_aux->const_reg_mask) { 17320 struct bpf_reg_state *regs = cur_regs(env); 17321 u16 mask = insn_aux->const_reg_mask; 17322 17323 for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) { 17324 u32 cval = insn_aux->const_reg_vals[r]; 17325 17326 if (!(mask & BIT(r))) 17327 continue; 17328 if (regs[r].type != SCALAR_VALUE) 17329 continue; 17330 if (!tnum_is_const(regs[r].var_off)) 17331 continue; 17332 if (verifier_bug_if((u32)regs[r].var_off.value != cval, 17333 env, "const R%d: %u != %llu", 17334 r, cval, regs[r].var_off.value)) 17335 return -EFAULT; 17336 } 17337 } 17338 17339 /* Reduce verification complexity by stopping speculative path 17340 * verification when a nospec is encountered. 17341 */ 17342 if (state->speculative && insn_aux->nospec) 17343 goto process_bpf_exit; 17344 17345 err = do_check_insn(env, &do_print_state); 17346 if (error_recoverable_with_nospec(err) && state->speculative) { 17347 /* Prevent this speculative path from ever reaching the 17348 * insn that would have been unsafe to execute. 17349 */ 17350 insn_aux->nospec = true; 17351 /* If it was an ADD/SUB insn, potentially remove any 17352 * markings for alu sanitization. 17353 */ 17354 insn_aux->alu_state = 0; 17355 goto process_bpf_exit; 17356 } else if (err < 0) { 17357 return err; 17358 } else if (err == PROCESS_BPF_EXIT) { 17359 goto process_bpf_exit; 17360 } else if (err == INSN_IDX_UPDATED) { 17361 } else if (err == 0) { 17362 env->insn_idx++; 17363 } 17364 17365 if (state->speculative && insn_aux->nospec_result) { 17366 /* If we are on a path that performed a jump-op, this 17367 * may skip a nospec patched-in after the jump. This can 17368 * currently never happen because nospec_result is only 17369 * used for the write-ops 17370 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper 17371 * calls. These must never skip the following insn 17372 * (i.e., bpf_insn_successors()'s opcode_info.can_jump 17373 * is false). Still, add a warning to document this in 17374 * case nospec_result is used elsewhere in the future. 17375 * 17376 * All non-branch instructions have a single 17377 * fall-through edge. For these, nospec_result should 17378 * already work. 17379 */ 17380 if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP || 17381 BPF_CLASS(insn->code) == BPF_JMP32) && 17382 BPF_OP(insn->code) != BPF_CALL, env, 17383 "speculation barrier after jump instruction may not have the desired effect")) 17384 return -EFAULT; 17385 process_bpf_exit: 17386 mark_verifier_state_scratched(env); 17387 err = bpf_update_branch_counts(env, env->cur_state); 17388 if (err) 17389 return err; 17390 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 17391 pop_log); 17392 if (err < 0) { 17393 if (err != -ENOENT) 17394 return err; 17395 break; 17396 } else { 17397 do_print_state = true; 17398 continue; 17399 } 17400 } 17401 } 17402 17403 return 0; 17404 } 17405 17406 static int find_btf_percpu_datasec(struct btf *btf) 17407 { 17408 const struct btf_type *t; 17409 const char *tname; 17410 int i, n; 17411 17412 /* 17413 * Both vmlinux and module each have their own ".data..percpu" 17414 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17415 * types to look at only module's own BTF types. 17416 */ 17417 n = btf_nr_types(btf); 17418 for (i = btf_named_start_id(btf, true); i < n; i++) { 17419 t = btf_type_by_id(btf, i); 17420 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17421 continue; 17422 17423 tname = btf_name_by_offset(btf, t->name_off); 17424 if (!strcmp(tname, ".data..percpu")) 17425 return i; 17426 } 17427 17428 return -ENOENT; 17429 } 17430 17431 /* 17432 * Add btf to the env->used_btfs array. If needed, refcount the 17433 * corresponding kernel module. To simplify caller's logic 17434 * in case of error or if btf was added before the function 17435 * decreases the btf refcount. 17436 */ 17437 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 17438 { 17439 struct btf_mod_pair *btf_mod; 17440 int ret = 0; 17441 int i; 17442 17443 /* check whether we recorded this BTF (and maybe module) already */ 17444 for (i = 0; i < env->used_btf_cnt; i++) 17445 if (env->used_btfs[i].btf == btf) 17446 goto ret_put; 17447 17448 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17449 verbose(env, "The total number of btfs per program has reached the limit of %u\n", 17450 MAX_USED_BTFS); 17451 ret = -E2BIG; 17452 goto ret_put; 17453 } 17454 17455 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17456 btf_mod->btf = btf; 17457 btf_mod->module = NULL; 17458 17459 /* if we reference variables from kernel module, bump its refcount */ 17460 if (btf_is_module(btf)) { 17461 btf_mod->module = btf_try_get_module(btf); 17462 if (!btf_mod->module) { 17463 ret = -ENXIO; 17464 goto ret_put; 17465 } 17466 } 17467 17468 env->used_btf_cnt++; 17469 return 0; 17470 17471 ret_put: 17472 /* Either error or this BTF was already added */ 17473 btf_put(btf); 17474 return ret; 17475 } 17476 17477 /* replace pseudo btf_id with kernel symbol address */ 17478 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 17479 struct bpf_insn *insn, 17480 struct bpf_insn_aux_data *aux, 17481 struct btf *btf) 17482 { 17483 const struct btf_var_secinfo *vsi; 17484 const struct btf_type *datasec; 17485 const struct btf_type *t; 17486 const char *sym_name; 17487 bool percpu = false; 17488 u32 type, id = insn->imm; 17489 s32 datasec_id; 17490 u64 addr; 17491 int i; 17492 17493 t = btf_type_by_id(btf, id); 17494 if (!t) { 17495 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17496 return -ENOENT; 17497 } 17498 17499 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17500 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17501 return -EINVAL; 17502 } 17503 17504 sym_name = btf_name_by_offset(btf, t->name_off); 17505 addr = kallsyms_lookup_name(sym_name); 17506 if (!addr) { 17507 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17508 sym_name); 17509 return -ENOENT; 17510 } 17511 insn[0].imm = (u32)addr; 17512 insn[1].imm = addr >> 32; 17513 17514 if (btf_type_is_func(t)) { 17515 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17516 aux->btf_var.mem_size = 0; 17517 return 0; 17518 } 17519 17520 datasec_id = find_btf_percpu_datasec(btf); 17521 if (datasec_id > 0) { 17522 datasec = btf_type_by_id(btf, datasec_id); 17523 for_each_vsi(i, datasec, vsi) { 17524 if (vsi->type == id) { 17525 percpu = true; 17526 break; 17527 } 17528 } 17529 } 17530 17531 type = t->type; 17532 t = btf_type_skip_modifiers(btf, type, NULL); 17533 if (percpu) { 17534 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17535 aux->btf_var.btf = btf; 17536 aux->btf_var.btf_id = type; 17537 } else if (!btf_type_is_struct(t)) { 17538 const struct btf_type *ret; 17539 const char *tname; 17540 u32 tsize; 17541 17542 /* resolve the type size of ksym. */ 17543 ret = btf_resolve_size(btf, t, &tsize); 17544 if (IS_ERR(ret)) { 17545 tname = btf_name_by_offset(btf, t->name_off); 17546 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17547 tname, PTR_ERR(ret)); 17548 return -EINVAL; 17549 } 17550 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17551 aux->btf_var.mem_size = tsize; 17552 } else { 17553 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17554 aux->btf_var.btf = btf; 17555 aux->btf_var.btf_id = type; 17556 } 17557 17558 return 0; 17559 } 17560 17561 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17562 struct bpf_insn *insn, 17563 struct bpf_insn_aux_data *aux) 17564 { 17565 struct btf *btf; 17566 int btf_fd; 17567 int err; 17568 17569 btf_fd = insn[1].imm; 17570 if (btf_fd) { 17571 btf = btf_get_by_fd(btf_fd); 17572 if (IS_ERR(btf)) { 17573 verbose(env, "invalid module BTF object FD specified.\n"); 17574 return -EINVAL; 17575 } 17576 } else { 17577 if (!btf_vmlinux) { 17578 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17579 return -EINVAL; 17580 } 17581 btf_get(btf_vmlinux); 17582 btf = btf_vmlinux; 17583 } 17584 17585 err = __check_pseudo_btf_id(env, insn, aux, btf); 17586 if (err) { 17587 btf_put(btf); 17588 return err; 17589 } 17590 17591 return __add_used_btf(env, btf); 17592 } 17593 17594 static bool is_tracing_prog_type(enum bpf_prog_type type) 17595 { 17596 switch (type) { 17597 case BPF_PROG_TYPE_KPROBE: 17598 case BPF_PROG_TYPE_TRACEPOINT: 17599 case BPF_PROG_TYPE_PERF_EVENT: 17600 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17601 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17602 return true; 17603 default: 17604 return false; 17605 } 17606 } 17607 17608 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17609 { 17610 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17611 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17612 } 17613 17614 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17615 struct bpf_map *map, 17616 struct bpf_prog *prog) 17617 17618 { 17619 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17620 17621 if (map->excl_prog_sha && 17622 memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) { 17623 verbose(env, "program's hash doesn't match map's excl_prog_hash\n"); 17624 return -EACCES; 17625 } 17626 17627 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17628 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17629 if (is_tracing_prog_type(prog_type)) { 17630 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17631 return -EINVAL; 17632 } 17633 } 17634 17635 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 17636 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17637 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17638 return -EINVAL; 17639 } 17640 17641 if (is_tracing_prog_type(prog_type)) { 17642 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17643 return -EINVAL; 17644 } 17645 } 17646 17647 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17648 !bpf_offload_prog_map_match(prog, map)) { 17649 verbose(env, "offload device mismatch between prog and map\n"); 17650 return -EINVAL; 17651 } 17652 17653 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17654 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17655 return -EINVAL; 17656 } 17657 17658 if (prog->sleepable) 17659 switch (map->map_type) { 17660 case BPF_MAP_TYPE_HASH: 17661 case BPF_MAP_TYPE_RHASH: 17662 case BPF_MAP_TYPE_LRU_HASH: 17663 case BPF_MAP_TYPE_ARRAY: 17664 case BPF_MAP_TYPE_PERCPU_HASH: 17665 case BPF_MAP_TYPE_PERCPU_ARRAY: 17666 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17667 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17668 case BPF_MAP_TYPE_HASH_OF_MAPS: 17669 case BPF_MAP_TYPE_RINGBUF: 17670 case BPF_MAP_TYPE_USER_RINGBUF: 17671 case BPF_MAP_TYPE_INODE_STORAGE: 17672 case BPF_MAP_TYPE_SK_STORAGE: 17673 case BPF_MAP_TYPE_TASK_STORAGE: 17674 case BPF_MAP_TYPE_CGRP_STORAGE: 17675 case BPF_MAP_TYPE_QUEUE: 17676 case BPF_MAP_TYPE_STACK: 17677 case BPF_MAP_TYPE_ARENA: 17678 case BPF_MAP_TYPE_INSN_ARRAY: 17679 case BPF_MAP_TYPE_PROG_ARRAY: 17680 break; 17681 default: 17682 verbose(env, 17683 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17684 return -EINVAL; 17685 } 17686 17687 if (bpf_map_is_cgroup_storage(map) && 17688 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17689 verbose(env, "only one cgroup storage of each type is allowed\n"); 17690 return -EBUSY; 17691 } 17692 17693 if (map->map_type == BPF_MAP_TYPE_ARENA) { 17694 if (env->prog->aux->arena) { 17695 verbose(env, "Only one arena per program\n"); 17696 return -EBUSY; 17697 } 17698 if (!env->allow_ptr_leaks || !env->bpf_capable) { 17699 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 17700 return -EPERM; 17701 } 17702 if (!env->prog->jit_requested) { 17703 verbose(env, "JIT is required to use arena\n"); 17704 return -EOPNOTSUPP; 17705 } 17706 if (!bpf_jit_supports_arena()) { 17707 verbose(env, "JIT doesn't support arena\n"); 17708 return -EOPNOTSUPP; 17709 } 17710 env->prog->aux->arena = (void *)map; 17711 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 17712 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 17713 return -EINVAL; 17714 } 17715 } 17716 17717 return 0; 17718 } 17719 17720 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 17721 { 17722 int i, err; 17723 17724 /* check whether we recorded this map already */ 17725 for (i = 0; i < env->used_map_cnt; i++) 17726 if (env->used_maps[i] == map) 17727 return i; 17728 17729 if (env->used_map_cnt >= MAX_USED_MAPS) { 17730 verbose(env, "The total number of maps per program has reached the limit of %u\n", 17731 MAX_USED_MAPS); 17732 return -E2BIG; 17733 } 17734 17735 err = check_map_prog_compatibility(env, map, env->prog); 17736 if (err) 17737 return err; 17738 17739 if (env->prog->sleepable) 17740 atomic64_inc(&map->sleepable_refcnt); 17741 17742 /* hold the map. If the program is rejected by verifier, 17743 * the map will be released by release_maps() or it 17744 * will be used by the valid program until it's unloaded 17745 * and all maps are released in bpf_free_used_maps() 17746 */ 17747 bpf_map_inc(map); 17748 17749 env->used_maps[env->used_map_cnt++] = map; 17750 17751 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 17752 err = bpf_insn_array_init(map, env->prog); 17753 if (err) { 17754 verbose(env, "Failed to properly initialize insn array\n"); 17755 return err; 17756 } 17757 env->insn_array_maps[env->insn_array_map_cnt++] = map; 17758 } 17759 17760 return env->used_map_cnt - 1; 17761 } 17762 17763 /* Add map behind fd to used maps list, if it's not already there, and return 17764 * its index. 17765 * Returns <0 on error, or >= 0 index, on success. 17766 */ 17767 static int add_used_map(struct bpf_verifier_env *env, int fd) 17768 { 17769 struct bpf_map *map; 17770 CLASS(fd, f)(fd); 17771 17772 map = __bpf_map_get(f); 17773 if (IS_ERR(map)) { 17774 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 17775 return PTR_ERR(map); 17776 } 17777 17778 return __add_used_map(env, map); 17779 } 17780 17781 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17782 { 17783 u8 class = BPF_CLASS(insn->code); 17784 u8 opcode = BPF_OP(insn->code); 17785 17786 switch (opcode) { 17787 case BPF_NEG: 17788 if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 || 17789 insn->off != 0 || insn->imm != 0) { 17790 verbose(env, "BPF_NEG uses reserved fields\n"); 17791 return -EINVAL; 17792 } 17793 return 0; 17794 case BPF_END: 17795 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 17796 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 17797 (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) { 17798 verbose(env, "BPF_END uses reserved fields\n"); 17799 return -EINVAL; 17800 } 17801 return 0; 17802 case BPF_MOV: 17803 if (BPF_SRC(insn->code) == BPF_X) { 17804 if (class == BPF_ALU) { 17805 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 17806 insn->imm) { 17807 verbose(env, "BPF_MOV uses reserved fields\n"); 17808 return -EINVAL; 17809 } 17810 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 17811 if (insn->imm != 1 && insn->imm != 1u << 16) { 17812 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 17813 return -EINVAL; 17814 } 17815 } else if ((insn->off != 0 && insn->off != 8 && 17816 insn->off != 16 && insn->off != 32) || insn->imm) { 17817 verbose(env, "BPF_MOV uses reserved fields\n"); 17818 return -EINVAL; 17819 } 17820 } else if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 17821 verbose(env, "BPF_MOV uses reserved fields\n"); 17822 return -EINVAL; 17823 } 17824 return 0; 17825 case BPF_ADD: 17826 case BPF_SUB: 17827 case BPF_AND: 17828 case BPF_OR: 17829 case BPF_XOR: 17830 case BPF_LSH: 17831 case BPF_RSH: 17832 case BPF_ARSH: 17833 case BPF_MUL: 17834 case BPF_DIV: 17835 case BPF_MOD: 17836 if (BPF_SRC(insn->code) == BPF_X) { 17837 if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) || 17838 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 17839 verbose(env, "BPF_ALU uses reserved fields\n"); 17840 return -EINVAL; 17841 } 17842 } else if (insn->src_reg != BPF_REG_0 || 17843 (insn->off != 0 && insn->off != 1) || 17844 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 17845 verbose(env, "BPF_ALU uses reserved fields\n"); 17846 return -EINVAL; 17847 } 17848 return 0; 17849 default: 17850 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 17851 return -EINVAL; 17852 } 17853 } 17854 17855 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17856 { 17857 u8 class = BPF_CLASS(insn->code); 17858 u8 opcode = BPF_OP(insn->code); 17859 17860 switch (opcode) { 17861 case BPF_CALL: 17862 if (BPF_SRC(insn->code) != BPF_K || 17863 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) || 17864 (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL && 17865 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17866 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 17867 verbose(env, "BPF_CALL uses reserved fields\n"); 17868 return -EINVAL; 17869 } 17870 return 0; 17871 case BPF_JA: 17872 if (BPF_SRC(insn->code) == BPF_X) { 17873 if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) { 17874 verbose(env, "BPF_JA|BPF_X uses reserved fields\n"); 17875 return -EINVAL; 17876 } 17877 } else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 17878 (class == BPF_JMP && insn->imm != 0) || 17879 (class == BPF_JMP32 && insn->off != 0)) { 17880 verbose(env, "BPF_JA uses reserved fields\n"); 17881 return -EINVAL; 17882 } 17883 return 0; 17884 case BPF_EXIT: 17885 if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || 17886 insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 17887 class == BPF_JMP32) { 17888 verbose(env, "BPF_EXIT uses reserved fields\n"); 17889 return -EINVAL; 17890 } 17891 return 0; 17892 case BPF_JCOND: 17893 if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO || 17894 insn->dst_reg || insn->imm) { 17895 verbose(env, "invalid may_goto imm %d\n", insn->imm); 17896 return -EINVAL; 17897 } 17898 return 0; 17899 default: 17900 if (BPF_SRC(insn->code) == BPF_X) { 17901 if (insn->imm != 0) { 17902 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 17903 return -EINVAL; 17904 } 17905 } else if (insn->src_reg != BPF_REG_0) { 17906 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 17907 return -EINVAL; 17908 } 17909 return 0; 17910 } 17911 } 17912 17913 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17914 { 17915 switch (BPF_CLASS(insn->code)) { 17916 case BPF_ALU: 17917 case BPF_ALU64: 17918 return check_alu_fields(env, insn); 17919 case BPF_LDX: 17920 if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17921 insn->imm != 0) { 17922 verbose(env, "BPF_LDX uses reserved fields\n"); 17923 return -EINVAL; 17924 } 17925 return 0; 17926 case BPF_STX: 17927 if (BPF_MODE(insn->code) == BPF_ATOMIC) 17928 return 0; 17929 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17930 verbose(env, "BPF_STX uses reserved fields\n"); 17931 return -EINVAL; 17932 } 17933 return 0; 17934 case BPF_ST: 17935 if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { 17936 verbose(env, "BPF_ST uses reserved fields\n"); 17937 return -EINVAL; 17938 } 17939 return 0; 17940 case BPF_JMP: 17941 case BPF_JMP32: 17942 return check_jmp_fields(env, insn); 17943 case BPF_LD: { 17944 u8 mode = BPF_MODE(insn->code); 17945 17946 if (mode == BPF_ABS || mode == BPF_IND) { 17947 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 17948 BPF_SIZE(insn->code) == BPF_DW || 17949 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 17950 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 17951 return -EINVAL; 17952 } 17953 } else if (mode != BPF_IMM) { 17954 verbose(env, "invalid BPF_LD mode\n"); 17955 return -EINVAL; 17956 } 17957 return 0; 17958 } 17959 default: 17960 verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code)); 17961 return -EINVAL; 17962 } 17963 } 17964 17965 /* 17966 * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions: 17967 * 17968 * 1. if it accesses map FD, replace it with actual map pointer. 17969 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17970 * 17971 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17972 */ 17973 static int check_and_resolve_insns(struct bpf_verifier_env *env) 17974 { 17975 struct bpf_insn *insn = env->prog->insnsi; 17976 int insn_cnt = env->prog->len; 17977 int i, err; 17978 17979 err = bpf_prog_calc_tag(env->prog); 17980 if (err) 17981 return err; 17982 17983 for (i = 0; i < insn_cnt; i++, insn++) { 17984 if (insn->dst_reg >= MAX_BPF_REG && 17985 !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) { 17986 verbose(env, "R%d is invalid\n", insn->dst_reg); 17987 return -EINVAL; 17988 } 17989 if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) { 17990 verbose(env, "R%d is invalid\n", insn->src_reg); 17991 return -EINVAL; 17992 } 17993 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17994 struct bpf_insn_aux_data *aux; 17995 struct bpf_map *map; 17996 int map_idx; 17997 u64 addr; 17998 u32 fd; 17999 18000 if (i == insn_cnt - 1 || insn[1].code != 0 || 18001 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18002 insn[1].off != 0) { 18003 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18004 return -EINVAL; 18005 } 18006 18007 if (insn[0].off != 0) { 18008 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 18009 return -EINVAL; 18010 } 18011 18012 if (insn[0].src_reg == 0) 18013 /* valid generic load 64-bit imm */ 18014 goto next_insn; 18015 18016 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18017 aux = &env->insn_aux_data[i]; 18018 err = check_pseudo_btf_id(env, insn, aux); 18019 if (err) 18020 return err; 18021 goto next_insn; 18022 } 18023 18024 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18025 aux = &env->insn_aux_data[i]; 18026 aux->ptr_type = PTR_TO_FUNC; 18027 goto next_insn; 18028 } 18029 18030 /* In final convert_pseudo_ld_imm64() step, this is 18031 * converted into regular 64-bit imm load insn. 18032 */ 18033 switch (insn[0].src_reg) { 18034 case BPF_PSEUDO_MAP_VALUE: 18035 case BPF_PSEUDO_MAP_IDX_VALUE: 18036 break; 18037 case BPF_PSEUDO_MAP_FD: 18038 case BPF_PSEUDO_MAP_IDX: 18039 if (insn[1].imm == 0) 18040 break; 18041 fallthrough; 18042 default: 18043 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18044 return -EINVAL; 18045 } 18046 18047 switch (insn[0].src_reg) { 18048 case BPF_PSEUDO_MAP_IDX_VALUE: 18049 case BPF_PSEUDO_MAP_IDX: 18050 if (bpfptr_is_null(env->fd_array)) { 18051 verbose(env, "fd_idx without fd_array is invalid\n"); 18052 return -EPROTO; 18053 } 18054 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18055 insn[0].imm * sizeof(fd), 18056 sizeof(fd))) 18057 return -EFAULT; 18058 break; 18059 default: 18060 fd = insn[0].imm; 18061 break; 18062 } 18063 18064 map_idx = add_used_map(env, fd); 18065 if (map_idx < 0) 18066 return map_idx; 18067 map = env->used_maps[map_idx]; 18068 18069 aux = &env->insn_aux_data[i]; 18070 aux->map_index = map_idx; 18071 18072 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18073 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18074 addr = (unsigned long)map; 18075 } else { 18076 u32 off = insn[1].imm; 18077 18078 if (!map->ops->map_direct_value_addr) { 18079 verbose(env, "no direct value access support for this map type\n"); 18080 return -EINVAL; 18081 } 18082 18083 err = map->ops->map_direct_value_addr(map, &addr, off); 18084 if (err) { 18085 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18086 map->value_size, off); 18087 return err; 18088 } 18089 18090 aux->map_off = off; 18091 addr += off; 18092 } 18093 18094 insn[0].imm = (u32)addr; 18095 insn[1].imm = addr >> 32; 18096 18097 next_insn: 18098 insn++; 18099 i++; 18100 continue; 18101 } 18102 18103 /* Basic sanity check before we invest more work here. */ 18104 if (!bpf_opcode_in_insntable(insn->code)) { 18105 verbose(env, "unknown opcode %02x\n", insn->code); 18106 return -EINVAL; 18107 } 18108 18109 err = check_insn_fields(env, insn); 18110 if (err) 18111 return err; 18112 } 18113 18114 /* now all pseudo BPF_LD_IMM64 instructions load valid 18115 * 'struct bpf_map *' into a register instead of user map_fd. 18116 * These pointers will be used later by verifier to validate map access. 18117 */ 18118 return 0; 18119 } 18120 18121 /* drop refcnt of maps used by the rejected program */ 18122 static void release_maps(struct bpf_verifier_env *env) 18123 { 18124 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18125 env->used_map_cnt); 18126 } 18127 18128 /* drop refcnt of maps used by the rejected program */ 18129 static void release_btfs(struct bpf_verifier_env *env) 18130 { 18131 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 18132 } 18133 18134 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18135 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18136 { 18137 struct bpf_insn *insn = env->prog->insnsi; 18138 int insn_cnt = env->prog->len; 18139 int i; 18140 18141 for (i = 0; i < insn_cnt; i++, insn++) { 18142 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18143 continue; 18144 if (insn->src_reg == BPF_PSEUDO_FUNC) 18145 continue; 18146 insn->src_reg = 0; 18147 } 18148 } 18149 18150 static void release_insn_arrays(struct bpf_verifier_env *env) 18151 { 18152 int i; 18153 18154 for (i = 0; i < env->insn_array_map_cnt; i++) 18155 bpf_insn_array_release(env->insn_array_maps[i]); 18156 } 18157 18158 18159 18160 /* The verifier does more data flow analysis than llvm and will not 18161 * explore branches that are dead at run time. Malicious programs can 18162 * have dead code too. Therefore replace all dead at-run-time code 18163 * with 'ja -1'. 18164 * 18165 * Just nops are not optimal, e.g. if they would sit at the end of the 18166 * program and through another bug we would manage to jump there, then 18167 * we'd execute beyond program memory otherwise. Returning exception 18168 * code also wouldn't work since we can have subprogs where the dead 18169 * code could be located. 18170 */ 18171 static void sanitize_dead_code(struct bpf_verifier_env *env) 18172 { 18173 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18174 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18175 struct bpf_insn *insn = env->prog->insnsi; 18176 const int insn_cnt = env->prog->len; 18177 int i; 18178 18179 for (i = 0; i < insn_cnt; i++) { 18180 if (aux_data[i].seen) 18181 continue; 18182 memcpy(insn + i, &trap, sizeof(trap)); 18183 aux_data[i].zext_dst = false; 18184 } 18185 } 18186 18187 18188 18189 static void free_states(struct bpf_verifier_env *env) 18190 { 18191 struct bpf_verifier_state_list *sl; 18192 struct list_head *head, *pos, *tmp; 18193 struct bpf_scc_info *info; 18194 int i, j; 18195 18196 bpf_free_verifier_state(env->cur_state, true); 18197 env->cur_state = NULL; 18198 while (!pop_stack(env, NULL, NULL, false)); 18199 18200 list_for_each_safe(pos, tmp, &env->free_list) { 18201 sl = container_of(pos, struct bpf_verifier_state_list, node); 18202 bpf_free_verifier_state(&sl->state, false); 18203 kfree(sl); 18204 } 18205 INIT_LIST_HEAD(&env->free_list); 18206 18207 for (i = 0; i < env->scc_cnt; ++i) { 18208 info = env->scc_info[i]; 18209 if (!info) 18210 continue; 18211 for (j = 0; j < info->num_visits; j++) 18212 bpf_free_backedges(&info->visits[j]); 18213 kvfree(info); 18214 env->scc_info[i] = NULL; 18215 } 18216 18217 if (!env->explored_states) 18218 return; 18219 18220 for (i = 0; i < state_htab_size(env); i++) { 18221 head = &env->explored_states[i]; 18222 18223 list_for_each_safe(pos, tmp, head) { 18224 sl = container_of(pos, struct bpf_verifier_state_list, node); 18225 bpf_free_verifier_state(&sl->state, false); 18226 kfree(sl); 18227 } 18228 INIT_LIST_HEAD(&env->explored_states[i]); 18229 } 18230 } 18231 18232 static int do_check_common(struct bpf_verifier_env *env, int subprog) 18233 { 18234 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18235 struct bpf_subprog_info *sub = subprog_info(env, subprog); 18236 struct bpf_prog_aux *aux = env->prog->aux; 18237 struct bpf_verifier_state *state; 18238 struct bpf_reg_state *regs; 18239 int ret, i; 18240 18241 env->prev_linfo = NULL; 18242 env->pass_cnt++; 18243 18244 state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT); 18245 if (!state) 18246 return -ENOMEM; 18247 state->curframe = 0; 18248 state->speculative = false; 18249 state->branches = 1; 18250 state->in_sleepable = env->prog->sleepable; 18251 state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT); 18252 if (!state->frame[0]) { 18253 kfree(state); 18254 return -ENOMEM; 18255 } 18256 env->cur_state = state; 18257 init_func_state(env, state->frame[0], 18258 BPF_MAIN_FUNC /* callsite */, 18259 0 /* frameno */, 18260 subprog); 18261 state->first_insn_idx = env->subprog_info[subprog].start; 18262 state->last_insn_idx = -1; 18263 18264 regs = state->frame[state->curframe]->regs; 18265 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 18266 const char *sub_name = subprog_name(env, subprog); 18267 struct bpf_subprog_arg_info *arg; 18268 struct bpf_reg_state *reg; 18269 18270 if (env->log.level & BPF_LOG_LEVEL) 18271 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 18272 ret = btf_prepare_func_args(env, subprog); 18273 if (ret) 18274 goto out; 18275 18276 if (subprog_is_exc_cb(env, subprog)) { 18277 state->frame[0]->in_exception_callback_fn = true; 18278 18279 /* 18280 * Global functions are scalar or void, make sure 18281 * we return a scalar. 18282 */ 18283 if (subprog_returns_void(env, subprog)) { 18284 verbose(env, "exception cb cannot return void\n"); 18285 ret = -EINVAL; 18286 goto out; 18287 } 18288 18289 /* Also ensure the callback only has a single scalar argument. */ 18290 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 18291 verbose(env, "exception cb only supports single integer argument\n"); 18292 ret = -EINVAL; 18293 goto out; 18294 } 18295 } 18296 for (i = BPF_REG_1; i <= min_t(u32, sub->arg_cnt, MAX_BPF_FUNC_REG_ARGS); i++) { 18297 arg = &sub->args[i - BPF_REG_1]; 18298 reg = ®s[i]; 18299 18300 if (arg->arg_type == ARG_PTR_TO_CTX) { 18301 reg->type = PTR_TO_CTX; 18302 mark_reg_known_zero(env, regs, i); 18303 } else if (arg->arg_type == ARG_ANYTHING) { 18304 reg->type = SCALAR_VALUE; 18305 mark_reg_unknown(env, regs, i); 18306 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 18307 /* assume unspecial LOCAL dynptr type */ 18308 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen, 0); 18309 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 18310 reg->type = PTR_TO_MEM; 18311 reg->type |= arg->arg_type & 18312 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 18313 mark_reg_known_zero(env, regs, i); 18314 reg->mem_size = arg->mem_size; 18315 if (arg->arg_type & PTR_MAYBE_NULL) 18316 reg->id = ++env->id_gen; 18317 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 18318 reg->type = PTR_TO_BTF_ID; 18319 if (arg->arg_type & PTR_MAYBE_NULL) 18320 reg->type |= PTR_MAYBE_NULL; 18321 if (arg->arg_type & PTR_UNTRUSTED) 18322 reg->type |= PTR_UNTRUSTED; 18323 if (arg->arg_type & PTR_TRUSTED) 18324 reg->type |= PTR_TRUSTED; 18325 mark_reg_known_zero(env, regs, i); 18326 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 18327 reg->btf_id = arg->btf_id; 18328 reg->id = ++env->id_gen; 18329 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 18330 /* caller can pass either PTR_TO_ARENA or SCALAR */ 18331 mark_reg_unknown(env, regs, i); 18332 } else { 18333 verifier_bug(env, "unhandled arg#%d type %d", 18334 i - BPF_REG_1 + 1, arg->arg_type); 18335 ret = -EFAULT; 18336 goto out; 18337 } 18338 } 18339 if (env->prog->type == BPF_PROG_TYPE_EXT && sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS) { 18340 verbose(env, "freplace programs with >%d args not supported yet\n", 18341 MAX_BPF_FUNC_REG_ARGS); 18342 ret = -EINVAL; 18343 goto out; 18344 } 18345 } else { 18346 /* if main BPF program has associated BTF info, validate that 18347 * it's matching expected signature, and otherwise mark BTF 18348 * info for main program as unreliable 18349 */ 18350 if (env->prog->aux->func_info_aux) { 18351 ret = btf_prepare_func_args(env, 0); 18352 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) { 18353 env->prog->aux->func_info_aux[0].unreliable = true; 18354 sub->arg_cnt = 1; 18355 sub->stack_arg_cnt = 0; 18356 } 18357 } 18358 18359 /* 1st arg to a function */ 18360 regs[BPF_REG_1].type = PTR_TO_CTX; 18361 mark_reg_known_zero(env, regs, BPF_REG_1); 18362 } 18363 18364 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 18365 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 18366 for (i = 0; i < aux->ctx_arg_info_size; i++) { 18367 ret = aux->ctx_arg_info[i].refcounted ? acquire_reference(env, 0, 0) : 0; 18368 if (ret < 0) 18369 goto out; 18370 18371 aux->ctx_arg_info[i].ref_id = ret; 18372 } 18373 } 18374 18375 ret = do_check(env); 18376 out: 18377 if (!ret && pop_log) 18378 bpf_vlog_reset(&env->log, 0); 18379 free_states(env); 18380 return ret; 18381 } 18382 18383 /* Lazily verify all global functions based on their BTF, if they are called 18384 * from main BPF program or any of subprograms transitively. 18385 * BPF global subprogs called from dead code are not validated. 18386 * All callable global functions must pass verification. 18387 * Otherwise the whole program is rejected. 18388 * Consider: 18389 * int bar(int); 18390 * int foo(int f) 18391 * { 18392 * return bar(f); 18393 * } 18394 * int bar(int b) 18395 * { 18396 * ... 18397 * } 18398 * foo() will be verified first for R1=any_scalar_value. During verification it 18399 * will be assumed that bar() already verified successfully and call to bar() 18400 * from foo() will be checked for type match only. Later bar() will be verified 18401 * independently to check that it's safe for R1=any_scalar_value. 18402 */ 18403 static int do_check_subprogs(struct bpf_verifier_env *env) 18404 { 18405 struct bpf_prog_aux *aux = env->prog->aux; 18406 struct bpf_func_info_aux *sub_aux; 18407 int i, ret, new_cnt; 18408 u32 insn_processed; 18409 18410 if (!aux->func_info) 18411 return 0; 18412 18413 /* exception callback is presumed to be always called */ 18414 if (env->exception_callback_subprog) 18415 subprog_aux(env, env->exception_callback_subprog)->called = true; 18416 18417 again: 18418 new_cnt = 0; 18419 for (i = 1; i < env->subprog_cnt; i++) { 18420 if (!bpf_subprog_is_global(env, i)) 18421 continue; 18422 18423 insn_processed = env->insn_processed; 18424 18425 sub_aux = subprog_aux(env, i); 18426 if (!sub_aux->called || sub_aux->verified) 18427 continue; 18428 18429 env->insn_idx = env->subprog_info[i].start; 18430 WARN_ON_ONCE(env->insn_idx == 0); 18431 ret = do_check_common(env, i); 18432 env->subprog_info[i].insn_processed = env->insn_processed - insn_processed; 18433 if (ret) { 18434 return ret; 18435 } else if (env->log.level & BPF_LOG_LEVEL) { 18436 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 18437 i, subprog_name(env, i)); 18438 } 18439 18440 /* We verified new global subprog, it might have called some 18441 * more global subprogs that we haven't verified yet, so we 18442 * need to do another pass over subprogs to verify those. 18443 */ 18444 sub_aux->verified = true; 18445 new_cnt++; 18446 } 18447 18448 /* We can't loop forever as we verify at least one global subprog on 18449 * each pass. 18450 */ 18451 if (new_cnt) 18452 goto again; 18453 18454 return 0; 18455 } 18456 18457 static int do_check_main(struct bpf_verifier_env *env) 18458 { 18459 u32 insn_processed = env->insn_processed; 18460 int ret; 18461 18462 env->insn_idx = 0; 18463 ret = do_check_common(env, 0); 18464 env->subprog_info[0].insn_processed = env->insn_processed - insn_processed; 18465 if (!ret) 18466 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18467 return ret; 18468 } 18469 18470 18471 static void print_verification_stats(struct bpf_verifier_env *env) 18472 { 18473 /* Skip over hidden subprogs which are not verified. */ 18474 int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18475 18476 if (env->log.level & BPF_LOG_STATS) { 18477 verbose(env, "verification time %lld usec\n", 18478 div_u64(env->verification_time, 1000)); 18479 verbose(env, "stack depth %d", env->subprog_info[0].stack_depth); 18480 for (i = 1; i < subprog_cnt; i++) 18481 verbose(env, "+%d", env->subprog_info[i].stack_depth); 18482 verbose(env, " max %d\n", env->max_stack_depth); 18483 verbose(env, "insns processed %d", env->subprog_info[0].insn_processed); 18484 for (i = 1; i < subprog_cnt; i++) 18485 if (bpf_subprog_is_global(env, i)) 18486 verbose(env, "+%d", env->subprog_info[i].insn_processed); 18487 verbose(env, "\n"); 18488 } 18489 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 18490 "total_states %d peak_states %d mark_read %d\n", 18491 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 18492 env->max_states_per_insn, env->total_states, 18493 env->peak_states, env->longest_mark_read_walk); 18494 } 18495 18496 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 18497 const struct bpf_ctx_arg_aux *info, u32 cnt) 18498 { 18499 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 18500 prog->aux->ctx_arg_info_size = cnt; 18501 18502 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 18503 } 18504 18505 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 18506 { 18507 const struct btf_type *t, *func_proto; 18508 const struct bpf_struct_ops_desc *st_ops_desc; 18509 const struct bpf_struct_ops *st_ops; 18510 const struct btf_member *member; 18511 struct bpf_prog *prog = env->prog; 18512 bool has_refcounted_arg = false; 18513 u32 btf_id, member_idx, member_off; 18514 struct btf *btf; 18515 const char *mname; 18516 int i, err; 18517 18518 if (!prog->gpl_compatible) { 18519 verbose(env, "struct ops programs must have a GPL compatible license\n"); 18520 return -EINVAL; 18521 } 18522 18523 if (!prog->aux->attach_btf_id) 18524 return -ENOTSUPP; 18525 18526 btf = prog->aux->attach_btf; 18527 if (btf_is_module(btf)) { 18528 /* Make sure st_ops is valid through the lifetime of env */ 18529 env->attach_btf_mod = btf_try_get_module(btf); 18530 if (!env->attach_btf_mod) { 18531 verbose(env, "struct_ops module %s is not found\n", 18532 btf_get_name(btf)); 18533 return -ENOTSUPP; 18534 } 18535 } 18536 18537 btf_id = prog->aux->attach_btf_id; 18538 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 18539 if (!st_ops_desc) { 18540 verbose(env, "attach_btf_id %u is not a supported struct\n", 18541 btf_id); 18542 return -ENOTSUPP; 18543 } 18544 st_ops = st_ops_desc->st_ops; 18545 18546 t = st_ops_desc->type; 18547 member_idx = prog->expected_attach_type; 18548 if (member_idx >= btf_type_vlen(t)) { 18549 verbose(env, "attach to invalid member idx %u of struct %s\n", 18550 member_idx, st_ops->name); 18551 return -EINVAL; 18552 } 18553 18554 member = &btf_type_member(t)[member_idx]; 18555 mname = btf_name_by_offset(btf, member->name_off); 18556 func_proto = btf_type_resolve_func_ptr(btf, member->type, 18557 NULL); 18558 if (!func_proto) { 18559 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 18560 mname, member_idx, st_ops->name); 18561 return -EINVAL; 18562 } 18563 18564 member_off = __btf_member_bit_offset(t, member) / 8; 18565 err = bpf_struct_ops_supported(st_ops, member_off); 18566 if (err) { 18567 verbose(env, "attach to unsupported member %s of struct %s\n", 18568 mname, st_ops->name); 18569 return err; 18570 } 18571 18572 if (st_ops->check_member) { 18573 err = st_ops->check_member(t, member, prog); 18574 18575 if (err) { 18576 verbose(env, "attach to unsupported member %s of struct %s\n", 18577 mname, st_ops->name); 18578 return err; 18579 } 18580 } 18581 18582 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 18583 verbose(env, "Private stack not supported by jit\n"); 18584 return -EACCES; 18585 } 18586 18587 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) { 18588 if (st_ops_desc->arg_info[member_idx].info[i].refcounted) { 18589 has_refcounted_arg = true; 18590 break; 18591 } 18592 } 18593 18594 /* Tail call is not allowed for programs with refcounted arguments since we 18595 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 18596 */ 18597 for (i = 0; i < env->subprog_cnt; i++) { 18598 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 18599 verbose(env, "program with __ref argument cannot tail call\n"); 18600 return -EINVAL; 18601 } 18602 } 18603 18604 prog->aux->st_ops = st_ops; 18605 prog->aux->attach_st_ops_member_off = member_off; 18606 18607 prog->aux->attach_func_proto = func_proto; 18608 prog->aux->attach_func_name = mname; 18609 env->ops = st_ops->verifier_ops; 18610 18611 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info, 18612 st_ops_desc->arg_info[member_idx].cnt); 18613 } 18614 #define SECURITY_PREFIX "security_" 18615 18616 #ifdef CONFIG_FUNCTION_ERROR_INJECTION 18617 18618 /* list of non-sleepable functions that are otherwise on 18619 * ALLOW_ERROR_INJECTION list 18620 */ 18621 BTF_SET_START(btf_non_sleepable_error_inject) 18622 /* Three functions below can be called from sleepable and non-sleepable context. 18623 * Assume non-sleepable from bpf safety point of view. 18624 */ 18625 BTF_ID(func, __filemap_add_folio) 18626 #ifdef CONFIG_FAIL_PAGE_ALLOC 18627 BTF_ID(func, should_fail_alloc_page) 18628 #endif 18629 #ifdef CONFIG_FAILSLAB 18630 BTF_ID(func, should_failslab) 18631 #endif 18632 BTF_SET_END(btf_non_sleepable_error_inject) 18633 18634 static int check_non_sleepable_error_inject(u32 btf_id) 18635 { 18636 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 18637 } 18638 18639 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18640 { 18641 /* fentry/fexit/fmod_ret progs can be sleepable if they are 18642 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 18643 */ 18644 if (!check_non_sleepable_error_inject(btf_id) && 18645 within_error_injection_list(addr)) 18646 return 0; 18647 18648 return -EINVAL; 18649 } 18650 18651 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18652 { 18653 if (within_error_injection_list(addr) || 18654 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18655 return 0; 18656 18657 return -EINVAL; 18658 } 18659 18660 #else 18661 18662 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code 18663 * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name() 18664 * but that just compares two concrete function names. 18665 */ 18666 static bool has_arch_syscall_prefix(const char *func_name) 18667 { 18668 #if defined(__x86_64__) 18669 return !strncmp(func_name, "__x64_", 6); 18670 #elif defined(__i386__) 18671 return !strncmp(func_name, "__ia32_", 7); 18672 #elif defined(__s390x__) 18673 return !strncmp(func_name, "__s390x_", 8); 18674 #elif defined(__aarch64__) 18675 return !strncmp(func_name, "__arm64_", 8); 18676 #elif defined(__riscv) 18677 return !strncmp(func_name, "__riscv_", 8); 18678 #elif defined(__powerpc__) || defined(__powerpc64__) 18679 return !strncmp(func_name, "sys_", 4); 18680 #elif defined(__loongarch__) 18681 return !strncmp(func_name, "sys_", 4); 18682 #else 18683 return false; 18684 #endif 18685 } 18686 18687 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */ 18688 18689 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18690 { 18691 if (has_arch_syscall_prefix(func_name)) 18692 return 0; 18693 18694 return -EINVAL; 18695 } 18696 18697 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18698 { 18699 if (has_arch_syscall_prefix(func_name) || 18700 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18701 return 0; 18702 18703 return -EINVAL; 18704 } 18705 18706 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */ 18707 18708 int bpf_check_attach_target(struct bpf_verifier_log *log, 18709 const struct bpf_prog *prog, 18710 const struct bpf_prog *tgt_prog, 18711 u32 btf_id, 18712 struct bpf_attach_target_info *tgt_info) 18713 { 18714 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 18715 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 18716 char trace_symbol[KSYM_SYMBOL_LEN]; 18717 const char prefix[] = "btf_trace_"; 18718 struct bpf_raw_event_map *btp; 18719 int ret = 0, subprog = -1, i; 18720 const struct btf_type *t; 18721 bool conservative = true; 18722 const char *tname, *fname; 18723 struct btf *btf; 18724 long addr = 0; 18725 struct module *mod = NULL; 18726 18727 if (!btf_id) { 18728 bpf_log(log, "Tracing programs must provide btf_id\n"); 18729 return -EINVAL; 18730 } 18731 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 18732 if (!btf) { 18733 bpf_log(log, 18734 "Tracing program can only be attached to another program annotated with BTF\n"); 18735 return -EINVAL; 18736 } 18737 t = btf_type_by_id(btf, btf_id); 18738 if (!t) { 18739 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 18740 return -EINVAL; 18741 } 18742 tname = btf_name_by_offset(btf, t->name_off); 18743 if (!tname) { 18744 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 18745 return -EINVAL; 18746 } 18747 if (tgt_prog) { 18748 struct bpf_prog_aux *aux = tgt_prog->aux; 18749 bool tgt_changes_pkt_data; 18750 bool tgt_might_sleep; 18751 18752 if (bpf_prog_is_dev_bound(prog->aux) && 18753 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 18754 bpf_log(log, "Target program bound device mismatch"); 18755 return -EINVAL; 18756 } 18757 18758 for (i = 0; i < aux->func_info_cnt; i++) 18759 if (aux->func_info[i].type_id == btf_id) { 18760 subprog = i; 18761 break; 18762 } 18763 if (subprog == -1) { 18764 bpf_log(log, "Subprog %s doesn't exist\n", tname); 18765 return -EINVAL; 18766 } 18767 if (aux->func && aux->func[subprog]->aux->exception_cb) { 18768 bpf_log(log, 18769 "%s programs cannot attach to exception callback\n", 18770 prog_extension ? "Extension" : "Tracing"); 18771 return -EINVAL; 18772 } 18773 conservative = aux->func_info_aux[subprog].unreliable; 18774 if (prog_extension) { 18775 if (conservative) { 18776 bpf_log(log, 18777 "Cannot replace static functions\n"); 18778 return -EINVAL; 18779 } 18780 if (!prog->jit_requested) { 18781 bpf_log(log, 18782 "Extension programs should be JITed\n"); 18783 return -EINVAL; 18784 } 18785 tgt_changes_pkt_data = aux->func 18786 ? aux->func[subprog]->aux->changes_pkt_data 18787 : aux->changes_pkt_data; 18788 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 18789 bpf_log(log, 18790 "Extension program changes packet data, while original does not\n"); 18791 return -EINVAL; 18792 } 18793 18794 tgt_might_sleep = aux->func 18795 ? aux->func[subprog]->aux->might_sleep 18796 : aux->might_sleep; 18797 if (prog->aux->might_sleep && !tgt_might_sleep) { 18798 bpf_log(log, 18799 "Extension program may sleep, while original does not\n"); 18800 return -EINVAL; 18801 } 18802 } 18803 if (!tgt_prog->jited) { 18804 bpf_log(log, "Can attach to only JITed progs\n"); 18805 return -EINVAL; 18806 } 18807 if (prog_tracing) { 18808 if (aux->attach_tracing_prog) { 18809 /* 18810 * Target program is an fentry/fexit which is already attached 18811 * to another tracing program. More levels of nesting 18812 * attachment are not allowed. 18813 */ 18814 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 18815 return -EINVAL; 18816 } 18817 } else if (tgt_prog->type == prog->type) { 18818 /* 18819 * To avoid potential call chain cycles, prevent attaching of a 18820 * program extension to another extension. It's ok to attach 18821 * fentry/fexit to extension program. 18822 */ 18823 bpf_log(log, "Cannot recursively attach\n"); 18824 return -EINVAL; 18825 } 18826 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 18827 prog_extension && 18828 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 18829 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT || 18830 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION)) { 18831 /* Program extensions can extend all program types 18832 * except fentry/fexit. The reason is the following. 18833 * The fentry/fexit programs are used for performance 18834 * analysis, stats and can be attached to any program 18835 * type. When extension program is replacing XDP function 18836 * it is necessary to allow performance analysis of all 18837 * functions. Both original XDP program and its program 18838 * extension. Hence attaching fentry/fexit to 18839 * BPF_PROG_TYPE_EXT is allowed. If extending of 18840 * fentry/fexit was allowed it would be possible to create 18841 * long call chain fentry->extension->fentry->extension 18842 * beyond reasonable stack size. Hence extending fentry 18843 * is not allowed. 18844 */ 18845 bpf_log(log, "Cannot extend fentry/fexit/fsession\n"); 18846 return -EINVAL; 18847 } 18848 } else { 18849 if (prog_extension) { 18850 bpf_log(log, "Cannot replace kernel functions\n"); 18851 return -EINVAL; 18852 } 18853 } 18854 18855 switch (prog->expected_attach_type) { 18856 case BPF_TRACE_RAW_TP: 18857 if (tgt_prog) { 18858 bpf_log(log, 18859 "Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n"); 18860 return -EINVAL; 18861 } 18862 if (!btf_type_is_typedef(t)) { 18863 bpf_log(log, "attach_btf_id %u is not a typedef\n", 18864 btf_id); 18865 return -EINVAL; 18866 } 18867 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 18868 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 18869 btf_id, tname); 18870 return -EINVAL; 18871 } 18872 tname += sizeof(prefix) - 1; 18873 18874 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 18875 * names. Thus using bpf_raw_event_map to get argument names. 18876 */ 18877 btp = bpf_get_raw_tracepoint(tname); 18878 if (!btp) 18879 return -EINVAL; 18880 if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) { 18881 bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n", 18882 tname); 18883 bpf_put_raw_tracepoint(btp); 18884 return -EINVAL; 18885 } 18886 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 18887 trace_symbol); 18888 bpf_put_raw_tracepoint(btp); 18889 18890 if (fname) 18891 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 18892 18893 if (!fname || ret < 0) { 18894 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 18895 prefix, tname); 18896 t = btf_type_by_id(btf, t->type); 18897 if (!btf_type_is_ptr(t)) 18898 /* should never happen in valid vmlinux build */ 18899 return -EINVAL; 18900 } else { 18901 t = btf_type_by_id(btf, ret); 18902 if (!btf_type_is_func(t)) 18903 /* should never happen in valid vmlinux build */ 18904 return -EINVAL; 18905 } 18906 18907 t = btf_type_by_id(btf, t->type); 18908 if (!btf_type_is_func_proto(t)) 18909 /* should never happen in valid vmlinux build */ 18910 return -EINVAL; 18911 18912 break; 18913 case BPF_TRACE_ITER: 18914 if (!btf_type_is_func(t)) { 18915 bpf_log(log, "attach_btf_id %u is not a function\n", 18916 btf_id); 18917 return -EINVAL; 18918 } 18919 t = btf_type_by_id(btf, t->type); 18920 if (!btf_type_is_func_proto(t)) 18921 return -EINVAL; 18922 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 18923 if (ret) 18924 return ret; 18925 break; 18926 default: 18927 if (!prog_extension) 18928 return -EINVAL; 18929 fallthrough; 18930 case BPF_MODIFY_RETURN: 18931 case BPF_LSM_MAC: 18932 case BPF_LSM_CGROUP: 18933 case BPF_TRACE_FENTRY: 18934 case BPF_TRACE_FEXIT: 18935 case BPF_TRACE_FSESSION: 18936 if (prog->expected_attach_type == BPF_TRACE_FSESSION && 18937 !bpf_jit_supports_fsession()) { 18938 bpf_log(log, "JIT does not support fsession\n"); 18939 return -EOPNOTSUPP; 18940 } 18941 if (!btf_type_is_func(t)) { 18942 bpf_log(log, "attach_btf_id %u is not a function\n", 18943 btf_id); 18944 return -EINVAL; 18945 } 18946 if (prog_extension && 18947 btf_check_type_match(log, prog, btf, t)) 18948 return -EINVAL; 18949 t = btf_type_by_id(btf, t->type); 18950 if (!btf_type_is_func_proto(t)) 18951 return -EINVAL; 18952 18953 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 18954 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 18955 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 18956 return -EINVAL; 18957 18958 if (tgt_prog && conservative) 18959 t = NULL; 18960 18961 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 18962 if (ret < 0) 18963 return ret; 18964 18965 if (tgt_prog) { 18966 if (subprog == 0) 18967 addr = (long) tgt_prog->bpf_func; 18968 else 18969 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 18970 } else { 18971 if (btf_is_module(btf)) { 18972 mod = btf_try_get_module(btf); 18973 if (mod) 18974 addr = find_kallsyms_symbol_value(mod, tname); 18975 else 18976 addr = 0; 18977 } else { 18978 addr = kallsyms_lookup_name(tname); 18979 } 18980 if (!addr) { 18981 module_put(mod); 18982 bpf_log(log, 18983 "The address of function %s cannot be found\n", 18984 tname); 18985 return -ENOENT; 18986 } 18987 } 18988 18989 if (prog->sleepable) { 18990 ret = -EINVAL; 18991 switch (prog->type) { 18992 case BPF_PROG_TYPE_TRACING: 18993 if (!check_attach_sleepable(btf_id, addr, tname)) 18994 ret = 0; 18995 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 18996 * in the fmodret id set with the KF_SLEEPABLE flag. 18997 */ 18998 else { 18999 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 19000 prog); 19001 19002 if (flags && (*flags & KF_SLEEPABLE)) 19003 ret = 0; 19004 } 19005 break; 19006 case BPF_PROG_TYPE_LSM: 19007 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 19008 * Only some of them are sleepable. 19009 */ 19010 if (bpf_lsm_is_sleepable_hook(btf_id)) 19011 ret = 0; 19012 break; 19013 default: 19014 break; 19015 } 19016 if (ret) { 19017 module_put(mod); 19018 bpf_log(log, "%s is not sleepable\n", tname); 19019 return ret; 19020 } 19021 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19022 if (tgt_prog) { 19023 module_put(mod); 19024 bpf_log(log, "can't modify return codes of BPF programs\n"); 19025 return -EINVAL; 19026 } 19027 ret = -EINVAL; 19028 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19029 !check_attach_modify_return(addr, tname)) 19030 ret = 0; 19031 if (ret) { 19032 module_put(mod); 19033 bpf_log(log, "%s() is not modifiable\n", tname); 19034 return ret; 19035 } 19036 } 19037 19038 break; 19039 } 19040 tgt_info->tgt_addr = addr; 19041 tgt_info->tgt_name = tname; 19042 tgt_info->tgt_type = t; 19043 tgt_info->tgt_mod = mod; 19044 return 0; 19045 } 19046 19047 BTF_SET_START(btf_id_deny) 19048 BTF_ID_UNUSED 19049 #ifdef CONFIG_SMP 19050 BTF_ID(func, ___migrate_enable) 19051 BTF_ID(func, migrate_disable) 19052 BTF_ID(func, migrate_enable) 19053 #endif 19054 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19055 BTF_ID(func, rcu_read_unlock_strict) 19056 #endif 19057 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19058 BTF_ID(func, preempt_count_add) 19059 BTF_ID(func, preempt_count_sub) 19060 #endif 19061 #ifdef CONFIG_PREEMPT_RCU 19062 BTF_ID(func, __rcu_read_lock) 19063 BTF_ID(func, __rcu_read_unlock) 19064 #endif 19065 BTF_SET_END(btf_id_deny) 19066 19067 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 19068 * Currently, we must manually list all __noreturn functions here. Once a more 19069 * robust solution is implemented, this workaround can be removed. 19070 */ 19071 BTF_SET_START(noreturn_deny) 19072 #ifdef CONFIG_IA32_EMULATION 19073 BTF_ID(func, __ia32_sys_exit) 19074 BTF_ID(func, __ia32_sys_exit_group) 19075 #endif 19076 #ifdef CONFIG_KUNIT 19077 BTF_ID(func, __kunit_abort) 19078 BTF_ID(func, kunit_try_catch_throw) 19079 #endif 19080 #ifdef CONFIG_MODULES 19081 BTF_ID(func, __module_put_and_kthread_exit) 19082 #endif 19083 #ifdef CONFIG_X86_64 19084 BTF_ID(func, __x64_sys_exit) 19085 BTF_ID(func, __x64_sys_exit_group) 19086 #endif 19087 BTF_ID(func, do_exit) 19088 BTF_ID(func, do_group_exit) 19089 BTF_ID(func, kthread_complete_and_exit) 19090 BTF_ID(func, make_task_dead) 19091 BTF_SET_END(noreturn_deny) 19092 19093 static bool can_be_sleepable(struct bpf_prog *prog) 19094 { 19095 if (prog->type == BPF_PROG_TYPE_TRACING) { 19096 switch (prog->expected_attach_type) { 19097 case BPF_TRACE_FENTRY: 19098 case BPF_TRACE_FEXIT: 19099 case BPF_MODIFY_RETURN: 19100 case BPF_TRACE_ITER: 19101 case BPF_TRACE_FSESSION: 19102 case BPF_TRACE_RAW_TP: 19103 return true; 19104 default: 19105 return false; 19106 } 19107 } 19108 return prog->type == BPF_PROG_TYPE_LSM || 19109 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 19110 prog->type == BPF_PROG_TYPE_STRUCT_OPS || 19111 prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT || 19112 prog->type == BPF_PROG_TYPE_TRACEPOINT; 19113 } 19114 19115 static int check_attach_btf_id(struct bpf_verifier_env *env) 19116 { 19117 struct bpf_prog *prog = env->prog; 19118 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 19119 struct bpf_attach_target_info tgt_info = {}; 19120 u32 btf_id = prog->aux->attach_btf_id; 19121 struct bpf_trampoline *tr; 19122 int ret; 19123 u64 key; 19124 19125 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 19126 if (prog->sleepable) 19127 /* attach_btf_id checked to be zero already */ 19128 return 0; 19129 verbose(env, "Syscall programs can only be sleepable\n"); 19130 return -EINVAL; 19131 } 19132 19133 if (prog->sleepable && !can_be_sleepable(prog)) { 19134 verbose(env, "Program of this type cannot be sleepable\n"); 19135 return -EINVAL; 19136 } 19137 19138 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 19139 return check_struct_ops_btf_id(env); 19140 19141 if (prog->type != BPF_PROG_TYPE_TRACING && 19142 prog->type != BPF_PROG_TYPE_LSM && 19143 prog->type != BPF_PROG_TYPE_EXT) 19144 return 0; 19145 19146 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 19147 if (ret) 19148 return ret; 19149 19150 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 19151 /* to make freplace equivalent to their targets, they need to 19152 * inherit env->ops and expected_attach_type for the rest of the 19153 * verification 19154 */ 19155 env->ops = bpf_verifier_ops[tgt_prog->type]; 19156 prog->expected_attach_type = tgt_prog->expected_attach_type; 19157 } 19158 19159 /* store info about the attachment target that will be used later */ 19160 prog->aux->attach_func_proto = tgt_info.tgt_type; 19161 prog->aux->attach_func_name = tgt_info.tgt_name; 19162 prog->aux->mod = tgt_info.tgt_mod; 19163 19164 if (tgt_prog) { 19165 prog->aux->saved_dst_prog_type = tgt_prog->type; 19166 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 19167 } 19168 19169 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 19170 prog->aux->attach_btf_trace = true; 19171 return 0; 19172 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 19173 return bpf_iter_prog_supported(prog); 19174 } 19175 19176 if (prog->type == BPF_PROG_TYPE_LSM) { 19177 ret = bpf_lsm_verify_prog(&env->log, prog); 19178 if (ret < 0) 19179 return ret; 19180 } else if (prog->type == BPF_PROG_TYPE_TRACING && 19181 btf_id_set_contains(&btf_id_deny, btf_id)) { 19182 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 19183 tgt_info.tgt_name); 19184 return -EINVAL; 19185 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 19186 prog->expected_attach_type == BPF_TRACE_FSESSION || 19187 prog->expected_attach_type == BPF_MODIFY_RETURN) && 19188 btf_id_set_contains(&noreturn_deny, btf_id)) { 19189 verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n", 19190 tgt_info.tgt_name); 19191 return -EINVAL; 19192 } 19193 19194 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 19195 tr = bpf_trampoline_get(key, &tgt_info); 19196 if (!tr) 19197 return -ENOMEM; 19198 19199 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 19200 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 19201 19202 prog->aux->dst_trampoline = tr; 19203 return 0; 19204 } 19205 19206 struct btf *bpf_get_btf_vmlinux(void) 19207 { 19208 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 19209 mutex_lock(&bpf_verifier_lock); 19210 if (!btf_vmlinux) 19211 btf_vmlinux = btf_parse_vmlinux(); 19212 mutex_unlock(&bpf_verifier_lock); 19213 } 19214 return btf_vmlinux; 19215 } 19216 19217 /* 19218 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 19219 * this case expect that every file descriptor in the array is either a map or 19220 * a BTF. Everything else is considered to be trash. 19221 */ 19222 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) 19223 { 19224 struct bpf_map *map; 19225 struct btf *btf; 19226 CLASS(fd, f)(fd); 19227 int err; 19228 19229 map = __bpf_map_get(f); 19230 if (!IS_ERR(map)) { 19231 err = __add_used_map(env, map); 19232 if (err < 0) 19233 return err; 19234 return 0; 19235 } 19236 19237 btf = __btf_get_by_fd(f); 19238 if (!IS_ERR(btf)) { 19239 btf_get(btf); 19240 return __add_used_btf(env, btf); 19241 } 19242 19243 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 19244 return PTR_ERR(map); 19245 } 19246 19247 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr) 19248 { 19249 size_t size = sizeof(int); 19250 int ret; 19251 int fd; 19252 u32 i; 19253 19254 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 19255 19256 /* 19257 * The only difference between old (no fd_array_cnt is given) and new 19258 * APIs is that in the latter case the fd_array is expected to be 19259 * continuous and is scanned for map fds right away 19260 */ 19261 if (!attr->fd_array_cnt) 19262 return 0; 19263 19264 /* Check for integer overflow */ 19265 if (attr->fd_array_cnt >= (U32_MAX / size)) { 19266 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt); 19267 return -EINVAL; 19268 } 19269 19270 for (i = 0; i < attr->fd_array_cnt; i++) { 19271 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size)) 19272 return -EFAULT; 19273 19274 ret = add_fd_from_fd_array(env, fd); 19275 if (ret) 19276 return ret; 19277 } 19278 19279 return 0; 19280 } 19281 19282 /* replace a generic kfunc with a specialized version if necessary */ 19283 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx) 19284 { 19285 struct bpf_prog *prog = env->prog; 19286 bool seen_direct_write; 19287 void *xdp_kfunc; 19288 bool is_rdonly; 19289 u32 func_id = desc->func_id; 19290 u16 offset = desc->offset; 19291 unsigned long addr = desc->addr; 19292 19293 if (offset) /* return if module BTF is used */ 19294 return 0; 19295 19296 if (bpf_dev_bound_kfunc_id(func_id)) { 19297 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19298 if (xdp_kfunc) 19299 addr = (unsigned long)xdp_kfunc; 19300 /* fallback to default kfunc when not supported by netdev */ 19301 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19302 seen_direct_write = env->seen_direct_write; 19303 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19304 19305 if (is_rdonly) 19306 addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19307 19308 /* restore env->seen_direct_write to its original value, since 19309 * may_access_direct_pkt_data mutates it 19310 */ 19311 env->seen_direct_write = seen_direct_write; 19312 } else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) { 19313 if (bpf_lsm_has_d_inode_locked(prog)) 19314 addr = (unsigned long)bpf_set_dentry_xattr_locked; 19315 } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) { 19316 if (bpf_lsm_has_d_inode_locked(prog)) 19317 addr = (unsigned long)bpf_remove_dentry_xattr_locked; 19318 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 19319 if (!env->insn_aux_data[insn_idx].non_sleepable) 19320 addr = (unsigned long)bpf_dynptr_from_file_sleepable; 19321 } else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) { 19322 if (env->insn_aux_data[insn_idx].non_sleepable) 19323 addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable; 19324 } else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) { 19325 if (env->insn_aux_data[insn_idx].non_sleepable) 19326 addr = (unsigned long)bpf_arena_free_pages_non_sleepable; 19327 } 19328 desc->addr = addr; 19329 return 0; 19330 } 19331 19332 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19333 u16 struct_meta_reg, 19334 u16 node_offset_reg, 19335 struct bpf_insn *insn, 19336 struct bpf_insn *insn_buf, 19337 int *cnt) 19338 { 19339 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19340 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19341 19342 insn_buf[0] = addr[0]; 19343 insn_buf[1] = addr[1]; 19344 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19345 insn_buf[3] = *insn; 19346 *cnt = 4; 19347 } 19348 19349 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19350 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19351 { 19352 struct bpf_kfunc_desc *desc; 19353 int err; 19354 19355 if (!insn->imm) { 19356 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19357 return -EINVAL; 19358 } 19359 19360 *cnt = 0; 19361 19362 /* insn->imm has the btf func_id. Replace it with an offset relative to 19363 * __bpf_call_base, unless the JIT needs to call functions that are 19364 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19365 */ 19366 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19367 if (!desc) { 19368 verifier_bug(env, "kernel function descriptor not found for func_id %u", 19369 insn->imm); 19370 return -EFAULT; 19371 } 19372 19373 err = specialize_kfunc(env, desc, insn_idx); 19374 if (err) 19375 return err; 19376 19377 if (!bpf_jit_supports_far_kfunc_call()) 19378 insn->imm = BPF_CALL_IMM(desc->addr); 19379 19380 if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) { 19381 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19382 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19383 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19384 19385 if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) { 19386 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19387 insn_idx); 19388 return -EFAULT; 19389 } 19390 19391 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19392 insn_buf[1] = addr[0]; 19393 insn_buf[2] = addr[1]; 19394 insn_buf[3] = *insn; 19395 *cnt = 4; 19396 } else if (is_bpf_obj_drop_kfunc(desc->func_id) || 19397 is_bpf_percpu_obj_drop_kfunc(desc->func_id) || 19398 is_bpf_refcount_acquire_kfunc(desc->func_id)) { 19399 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19400 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19401 19402 if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) { 19403 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19404 insn_idx); 19405 return -EFAULT; 19406 } 19407 19408 if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) { 19409 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19410 insn_idx); 19411 return -EFAULT; 19412 } 19413 19414 insn_buf[0] = addr[0]; 19415 insn_buf[1] = addr[1]; 19416 insn_buf[2] = *insn; 19417 *cnt = 3; 19418 } else if (is_bpf_list_push_kfunc(desc->func_id) || 19419 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19420 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19421 int struct_meta_reg = BPF_REG_3; 19422 int node_offset_reg = BPF_REG_4; 19423 19424 /* list_add/rbtree_add have an extra arg (prev/less), 19425 * so args-to-fixup are in diff regs. 19426 */ 19427 if (desc->func_id == special_kfunc_list[KF_bpf_list_add] || 19428 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19429 struct_meta_reg = BPF_REG_4; 19430 node_offset_reg = BPF_REG_5; 19431 } 19432 19433 if (!kptr_struct_meta) { 19434 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19435 insn_idx); 19436 return -EFAULT; 19437 } 19438 19439 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19440 node_offset_reg, insn, insn_buf, cnt); 19441 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19442 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19443 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19444 *cnt = 1; 19445 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] && 19446 env->prog->expected_attach_type == BPF_TRACE_FSESSION) { 19447 /* 19448 * inline the bpf_session_is_return() for fsession: 19449 * bool bpf_session_is_return(void *ctx) 19450 * { 19451 * return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1; 19452 * } 19453 */ 19454 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19455 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT); 19456 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1); 19457 *cnt = 3; 19458 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] && 19459 env->prog->expected_attach_type == BPF_TRACE_FSESSION) { 19460 /* 19461 * inline bpf_session_cookie() for fsession: 19462 * __u64 *bpf_session_cookie(void *ctx) 19463 * { 19464 * u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF; 19465 * return &((u64 *)ctx)[-off]; 19466 * } 19467 */ 19468 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19469 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT); 19470 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF); 19471 insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19472 insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1); 19473 insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0); 19474 *cnt = 6; 19475 } 19476 19477 if (env->insn_aux_data[insn_idx].arg_prog) { 19478 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 19479 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 19480 int idx = *cnt; 19481 19482 insn_buf[idx++] = ld_addrs[0]; 19483 insn_buf[idx++] = ld_addrs[1]; 19484 insn_buf[idx++] = *insn; 19485 *cnt = idx; 19486 } 19487 return 0; 19488 } 19489 19490 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, 19491 struct bpf_log_attr *attr_log) 19492 { 19493 u64 start_time = ktime_get_ns(); 19494 struct bpf_verifier_env *env; 19495 int i, len, ret = -EINVAL, err; 19496 bool is_priv; 19497 19498 BTF_TYPE_EMIT(enum bpf_features); 19499 19500 /* no program is valid */ 19501 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 19502 return -EINVAL; 19503 19504 /* 'struct bpf_verifier_env' can be global, but since it's not small, 19505 * allocate/free it every time bpf_check() is called 19506 */ 19507 env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT); 19508 if (!env) 19509 return -ENOMEM; 19510 19511 env->bt.env = env; 19512 19513 len = (*prog)->len; 19514 env->insn_aux_data = 19515 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 19516 ret = -ENOMEM; 19517 if (!env->insn_aux_data) 19518 goto err_free_env; 19519 for (i = 0; i < len; i++) 19520 env->insn_aux_data[i].orig_idx = i; 19521 env->succ = bpf_iarray_realloc(NULL, 2); 19522 if (!env->succ) 19523 goto err_free_env; 19524 env->prog = *prog; 19525 env->ops = bpf_verifier_ops[env->prog->type]; 19526 19527 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 19528 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 19529 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 19530 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 19531 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 19532 19533 bpf_get_btf_vmlinux(); 19534 19535 /* grab the mutex to protect few globals used by verifier */ 19536 if (!is_priv) 19537 mutex_lock(&bpf_verifier_lock); 19538 19539 /* user could have requested verbose verifier output 19540 * and supplied buffer to store the verification trace 19541 */ 19542 ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size); 19543 if (ret) 19544 goto err_unlock; 19545 19546 ret = process_fd_array(env, attr, uattr); 19547 if (ret) 19548 goto skip_full_check; 19549 19550 mark_verifier_state_clean(env); 19551 19552 if (IS_ERR(btf_vmlinux)) { 19553 /* Either gcc or pahole or kernel are broken. */ 19554 verbose(env, "in-kernel BTF is malformed\n"); 19555 ret = PTR_ERR(btf_vmlinux); 19556 goto skip_full_check; 19557 } 19558 19559 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 19560 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 19561 env->strict_alignment = true; 19562 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 19563 env->strict_alignment = false; 19564 19565 if (is_priv) 19566 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 19567 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 19568 19569 env->explored_states = kvzalloc_objs(struct list_head, 19570 state_htab_size(env), 19571 GFP_KERNEL_ACCOUNT); 19572 ret = -ENOMEM; 19573 if (!env->explored_states) 19574 goto skip_full_check; 19575 19576 for (i = 0; i < state_htab_size(env); i++) 19577 INIT_LIST_HEAD(&env->explored_states[i]); 19578 INIT_LIST_HEAD(&env->free_list); 19579 19580 ret = bpf_check_btf_info_early(env, attr, uattr); 19581 if (ret < 0) 19582 goto skip_full_check; 19583 19584 ret = add_subprog_and_kfunc(env); 19585 if (ret < 0) 19586 goto skip_full_check; 19587 19588 ret = check_subprogs(env); 19589 if (ret < 0) 19590 goto skip_full_check; 19591 19592 ret = bpf_check_btf_info(env, attr, uattr); 19593 if (ret < 0) 19594 goto skip_full_check; 19595 19596 ret = check_and_resolve_insns(env); 19597 if (ret < 0) 19598 goto skip_full_check; 19599 19600 if (bpf_prog_is_offloaded(env->prog->aux)) { 19601 ret = bpf_prog_offload_verifier_prep(env->prog); 19602 if (ret) 19603 goto skip_full_check; 19604 } 19605 19606 ret = bpf_check_cfg(env); 19607 if (ret < 0) 19608 goto skip_full_check; 19609 19610 ret = bpf_compute_postorder(env); 19611 if (ret < 0) 19612 goto skip_full_check; 19613 19614 ret = bpf_stack_liveness_init(env); 19615 if (ret) 19616 goto skip_full_check; 19617 19618 ret = check_attach_btf_id(env); 19619 if (ret) 19620 goto skip_full_check; 19621 19622 ret = bpf_compute_const_regs(env); 19623 if (ret < 0) 19624 goto skip_full_check; 19625 19626 ret = bpf_prune_dead_branches(env); 19627 if (ret < 0) 19628 goto skip_full_check; 19629 19630 ret = sort_subprogs_topo(env); 19631 if (ret < 0) 19632 goto skip_full_check; 19633 19634 ret = bpf_compute_scc(env); 19635 if (ret < 0) 19636 goto skip_full_check; 19637 19638 ret = bpf_compute_live_registers(env); 19639 if (ret < 0) 19640 goto skip_full_check; 19641 19642 ret = mark_fastcall_patterns(env); 19643 if (ret < 0) 19644 goto skip_full_check; 19645 19646 ret = do_check_main(env); 19647 ret = ret ?: do_check_subprogs(env); 19648 19649 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 19650 ret = bpf_prog_offload_finalize(env); 19651 19652 skip_full_check: 19653 kvfree(env->explored_states); 19654 19655 /* might decrease stack depth, keep it before passes that 19656 * allocate additional slots. 19657 */ 19658 if (ret == 0) 19659 ret = bpf_remove_fastcall_spills_fills(env); 19660 19661 if (ret == 0) 19662 ret = check_max_stack_depth(env); 19663 19664 /* instruction rewrites happen after this point */ 19665 if (ret == 0) 19666 ret = bpf_optimize_bpf_loop(env); 19667 19668 if (is_priv) { 19669 if (ret == 0) 19670 bpf_opt_hard_wire_dead_code_branches(env); 19671 if (ret == 0) 19672 ret = bpf_opt_remove_dead_code(env); 19673 if (ret == 0) 19674 ret = bpf_opt_remove_nops(env); 19675 } else { 19676 if (ret == 0) 19677 sanitize_dead_code(env); 19678 } 19679 19680 if (ret == 0) 19681 /* program is valid, convert *(u32*)(ctx + off) accesses */ 19682 ret = bpf_convert_ctx_accesses(env); 19683 19684 if (ret == 0) 19685 ret = bpf_do_misc_fixups(env); 19686 19687 /* do 32-bit optimization after insn patching has done so those patched 19688 * insns could be handled correctly. 19689 */ 19690 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 19691 ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr); 19692 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 19693 : false; 19694 } 19695 19696 if (ret == 0) 19697 ret = bpf_fixup_call_args(env); 19698 19699 env->verification_time = ktime_get_ns() - start_time; 19700 print_verification_stats(env); 19701 env->prog->aux->verified_insns = env->insn_processed; 19702 19703 /* preserve original error even if log finalization is successful */ 19704 err = bpf_log_attr_finalize(attr_log, &env->log); 19705 if (err) 19706 ret = err; 19707 19708 if (ret) 19709 goto err_release_maps; 19710 19711 if (env->used_map_cnt) { 19712 /* if program passed verifier, update used_maps in bpf_prog_info */ 19713 env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0], 19714 env->used_map_cnt, 19715 GFP_KERNEL_ACCOUNT); 19716 19717 if (!env->prog->aux->used_maps) { 19718 ret = -ENOMEM; 19719 goto err_release_maps; 19720 } 19721 19722 memcpy(env->prog->aux->used_maps, env->used_maps, 19723 sizeof(env->used_maps[0]) * env->used_map_cnt); 19724 env->prog->aux->used_map_cnt = env->used_map_cnt; 19725 } 19726 if (env->used_btf_cnt) { 19727 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 19728 env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0], 19729 env->used_btf_cnt, 19730 GFP_KERNEL_ACCOUNT); 19731 if (!env->prog->aux->used_btfs) { 19732 ret = -ENOMEM; 19733 goto err_release_maps; 19734 } 19735 19736 memcpy(env->prog->aux->used_btfs, env->used_btfs, 19737 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 19738 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 19739 } 19740 if (env->used_map_cnt || env->used_btf_cnt) { 19741 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 19742 * bpf_ld_imm64 instructions 19743 */ 19744 convert_pseudo_ld_imm64(env); 19745 } 19746 19747 adjust_btf_func(env); 19748 19749 /* extension progs temporarily inherit the attach_type of their targets 19750 for verification purposes, so set it back to zero before returning 19751 */ 19752 if (env->prog->type == BPF_PROG_TYPE_EXT) 19753 env->prog->expected_attach_type = 0; 19754 19755 env->prog = __bpf_prog_select_runtime(env, env->prog, &ret); 19756 19757 err_release_maps: 19758 if (ret) 19759 release_insn_arrays(env); 19760 if (!env->prog->aux->used_maps) 19761 /* if we didn't copy map pointers into bpf_prog_info, release 19762 * them now. Otherwise free_used_maps() will release them. 19763 */ 19764 release_maps(env); 19765 if (!env->prog->aux->used_btfs) 19766 release_btfs(env); 19767 19768 *prog = env->prog; 19769 19770 module_put(env->attach_btf_mod); 19771 err_unlock: 19772 if (!is_priv) 19773 mutex_unlock(&bpf_verifier_lock); 19774 bpf_clear_insn_aux_data(env, 0, env->prog->len); 19775 vfree(env->insn_aux_data); 19776 err_free_env: 19777 bpf_stack_liveness_free(env); 19778 kvfree(env->cfg.insn_postorder); 19779 kvfree(env->scc_info); 19780 kvfree(env->succ); 19781 kvfree(env->gotox_tmp_buf); 19782 kvfree(env); 19783 return ret; 19784 } 19785