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 u32 i, nargs, ptr_type_id, id; 12821 const struct btf_param *args; 12822 struct btf *desc_btf; 12823 12824 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12825 if (!insn->imm) 12826 return 0; 12827 12828 err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta); 12829 if (err == -EACCES && meta.func_name) 12830 verbose(env, "calling kernel function %s is not allowed\n", meta.func_name); 12831 if (err) 12832 return err; 12833 desc_btf = meta.btf; 12834 func_name = meta.func_name; 12835 insn_aux = &env->insn_aux_data[insn_idx]; 12836 12837 insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta); 12838 12839 if (!insn->off && 12840 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 12841 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 12842 struct bpf_verifier_state *branch; 12843 struct bpf_reg_state *regs; 12844 12845 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 12846 if (IS_ERR(branch)) { 12847 verbose(env, "failed to push state for failed lock acquisition\n"); 12848 return PTR_ERR(branch); 12849 } 12850 12851 regs = branch->frame[branch->curframe]->regs; 12852 12853 /* Clear r0-r5 registers in forked state */ 12854 for (i = 0; i < CALLER_SAVED_REGS; i++) 12855 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 12856 12857 mark_reg_unknown(env, regs, BPF_REG_0); 12858 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 12859 if (err) { 12860 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 12861 return err; 12862 } 12863 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32)); 12864 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 12865 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 12866 return -EFAULT; 12867 } 12868 12869 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12870 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12871 return -EACCES; 12872 } 12873 12874 sleepable = bpf_is_kfunc_sleepable(&meta); 12875 if (sleepable && !in_sleepable(env)) { 12876 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12877 return -EACCES; 12878 } 12879 12880 /* Track non-sleepable context for kfuncs, same as for helpers. */ 12881 if (!in_sleepable_context(env)) 12882 insn_aux->non_sleepable = true; 12883 12884 /* Check the arguments */ 12885 err = check_kfunc_args(env, &meta, insn_idx); 12886 if (err < 0) 12887 return err; 12888 12889 if (is_bpf_rbtree_add_kfunc(meta.func_id)) { 12890 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12891 set_rbtree_add_callback_state); 12892 if (err) { 12893 verbose(env, "kfunc %s#%d failed callback verification\n", 12894 func_name, meta.func_id); 12895 return err; 12896 } 12897 } 12898 12899 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 12900 meta.r0_size = sizeof(u64); 12901 meta.r0_rdonly = false; 12902 } 12903 12904 if (is_bpf_wq_set_callback_kfunc(meta.func_id)) { 12905 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12906 set_timer_callback_state); 12907 if (err) { 12908 verbose(env, "kfunc %s#%d failed callback verification\n", 12909 func_name, meta.func_id); 12910 return err; 12911 } 12912 } 12913 12914 if (is_task_work_add_kfunc(meta.func_id)) { 12915 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12916 set_task_work_schedule_callback_state); 12917 if (err) { 12918 verbose(env, "kfunc %s#%d failed callback verification\n", 12919 func_name, meta.func_id); 12920 return err; 12921 } 12922 } 12923 12924 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12925 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12926 12927 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 12928 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 12929 12930 if (rcu_lock) { 12931 env->cur_state->active_rcu_locks++; 12932 } else if (rcu_unlock) { 12933 if (env->cur_state->active_rcu_locks == 0) { 12934 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12935 return -EINVAL; 12936 } 12937 if (--env->cur_state->active_rcu_locks == 0) 12938 invalidate_rcu_protected_refs(env); 12939 } else if (preempt_disable) { 12940 env->cur_state->active_preempt_locks++; 12941 } else if (preempt_enable) { 12942 if (env->cur_state->active_preempt_locks == 0) { 12943 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 12944 return -EINVAL; 12945 } 12946 env->cur_state->active_preempt_locks--; 12947 } 12948 12949 if (sleepable && !in_sleepable_context(env)) { 12950 verbose(env, "kernel func %s is sleepable within %s\n", 12951 func_name, non_sleepable_context_description(env)); 12952 return -EACCES; 12953 } 12954 12955 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12956 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12957 return -EACCES; 12958 } 12959 12960 if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) { 12961 verbose(env, "kernel func %s requires RCU critical section protection\n", func_name); 12962 return -EACCES; 12963 } 12964 12965 /* In case of release function, we get register number of refcounted 12966 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12967 */ 12968 if (meta.release_regno) { 12969 err = release_reg(env, ®s[meta.release_regno], false, !!meta.dynptr.id); 12970 if (err) 12971 return err; 12972 } 12973 12974 if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) { 12975 id = regs[BPF_REG_2].id; 12976 insn_aux->insert_off = regs[BPF_REG_2].var_off.value; 12977 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12978 ref_convert_owning_non_owning(env, id); 12979 } 12980 12981 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12982 if (!bpf_jit_supports_exceptions()) { 12983 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12984 func_name, meta.func_id); 12985 return -ENOTSUPP; 12986 } 12987 env->seen_exception = true; 12988 12989 /* In the case of the default callback, the cookie value passed 12990 * to bpf_throw becomes the return value of the program. 12991 */ 12992 if (!env->exception_callback_subprog) { 12993 err = check_return_code(env, BPF_REG_1, "R1"); 12994 if (err < 0) 12995 return err; 12996 } 12997 } 12998 12999 for (i = 0; i < CALLER_SAVED_REGS; i++) { 13000 u32 regno = caller_saved[i]; 13001 13002 bpf_mark_reg_not_init(env, ®s[regno]); 13003 regs[regno].subreg_def = DEF_NOT_SUBREG; 13004 } 13005 invalidate_outgoing_stack_args(env, cur_func(env)); 13006 13007 /* Check return type */ 13008 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13009 13010 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13011 if (meta.btf != btf_vmlinux || 13012 (!is_bpf_obj_new_kfunc(meta.func_id) && 13013 !is_bpf_percpu_obj_new_kfunc(meta.func_id) && 13014 !is_bpf_refcount_acquire_kfunc(meta.func_id))) { 13015 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13016 return -EINVAL; 13017 } 13018 } 13019 13020 if (btf_type_is_scalar(t)) { 13021 mark_reg_unknown(env, regs, BPF_REG_0); 13022 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13023 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13024 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 13025 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 13026 } else if (btf_type_is_ptr(t)) { 13027 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 13028 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 13029 if (err) { 13030 if (err < 0) 13031 return err; 13032 } else if (btf_type_is_void(ptr_type)) { 13033 /* kfunc returning 'void *' is equivalent to returning scalar */ 13034 mark_reg_unknown(env, regs, BPF_REG_0); 13035 } else if (!__btf_type_is_struct(ptr_type)) { 13036 if (!meta.r0_size) { 13037 __u32 sz; 13038 13039 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 13040 meta.r0_size = sz; 13041 meta.r0_rdonly = true; 13042 } 13043 } 13044 if (!meta.r0_size) { 13045 ptr_type_name = btf_name_by_offset(desc_btf, 13046 ptr_type->name_off); 13047 verbose(env, 13048 "kernel function %s returns pointer type %s %s is not supported\n", 13049 func_name, 13050 btf_type_str(ptr_type), 13051 ptr_type_name); 13052 return -EINVAL; 13053 } 13054 13055 mark_reg_known_zero(env, regs, BPF_REG_0); 13056 regs[BPF_REG_0].type = PTR_TO_MEM; 13057 regs[BPF_REG_0].mem_size = meta.r0_size; 13058 13059 if (meta.r0_rdonly) 13060 regs[BPF_REG_0].type |= MEM_RDONLY; 13061 13062 /* Ensures we don't access the memory after a release_reference() */ 13063 if (meta.ref_obj.id) { 13064 err = validate_ref_obj(env, &meta.ref_obj); 13065 if (err) 13066 return err; 13067 regs[BPF_REG_0].parent_id = meta.ref_obj.id; 13068 } 13069 13070 if (is_kfunc_rcu_protected(&meta)) 13071 regs[BPF_REG_0].type |= MEM_RCU; 13072 } else { 13073 enum bpf_reg_type type = PTR_TO_BTF_ID; 13074 13075 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 13076 type |= PTR_UNTRUSTED; 13077 else if (is_kfunc_rcu_protected(&meta) || 13078 (bpf_is_iter_next_kfunc(&meta) && 13079 (get_iter_from_state(env->cur_state, &meta) 13080 ->type & MEM_RCU))) { 13081 /* 13082 * If the iterator's constructor (the _new 13083 * function e.g., bpf_iter_task_new) has been 13084 * annotated with BPF kfunc flag 13085 * KF_RCU_PROTECTED and was called within a RCU 13086 * read-side critical section, also propagate 13087 * the MEM_RCU flag to the pointer returned from 13088 * the iterator's next function (e.g., 13089 * bpf_iter_task_next). 13090 */ 13091 type |= MEM_RCU; 13092 } else { 13093 /* 13094 * Any PTR_TO_BTF_ID that is returned from a BPF 13095 * kfunc should by default be treated as 13096 * implicitly trusted. 13097 */ 13098 type |= PTR_TRUSTED; 13099 } 13100 13101 mark_reg_known_zero(env, regs, BPF_REG_0); 13102 regs[BPF_REG_0].btf = desc_btf; 13103 regs[BPF_REG_0].type = type; 13104 regs[BPF_REG_0].btf_id = ptr_type_id; 13105 } 13106 13107 if (is_kfunc_ret_null(&meta)) { 13108 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 13109 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 13110 regs[BPF_REG_0].id = ++env->id_gen; 13111 } 13112 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 13113 if (is_kfunc_acquire(&meta)) { 13114 id = acquire_reference(env, insn_idx, 0); 13115 if (id < 0) 13116 return id; 13117 regs[BPF_REG_0].id = id; 13118 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 13119 ref_set_non_owning(env, ®s[BPF_REG_0]); 13120 } 13121 13122 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 13123 regs[BPF_REG_0].id = ++env->id_gen; 13124 } else if (btf_type_is_void(t)) { 13125 if (meta.btf == btf_vmlinux) { 13126 if (is_bpf_obj_drop_kfunc(meta.func_id) || 13127 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) { 13128 insn_aux->kptr_struct_meta = 13129 btf_find_struct_meta(meta.arg_btf, 13130 meta.arg_btf_id); 13131 } 13132 } 13133 } 13134 13135 if (bpf_is_kfunc_pkt_changing(&meta)) 13136 clear_all_pkt_pointers(env); 13137 13138 nargs = btf_type_vlen(meta.func_proto); 13139 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 13140 struct bpf_func_state *caller = cur_func(env); 13141 struct bpf_subprog_info *caller_info = &env->subprog_info[caller->subprogno]; 13142 u16 out_stack_arg_cnt = nargs - MAX_BPF_FUNC_REG_ARGS; 13143 u16 stack_arg_cnt = bpf_in_stack_arg_cnt(caller_info) + out_stack_arg_cnt; 13144 13145 if (stack_arg_cnt > caller_info->stack_arg_cnt) 13146 caller_info->stack_arg_cnt = stack_arg_cnt; 13147 } 13148 13149 args = (const struct btf_param *)(meta.func_proto + 1); 13150 for (i = 0; i < min_t(int, nargs, MAX_BPF_FUNC_REG_ARGS); i++) { 13151 u32 regno = i + 1; 13152 13153 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 13154 if (btf_type_is_ptr(t)) 13155 mark_btf_func_reg_size(env, regno, sizeof(void *)); 13156 else 13157 /* scalar. ensured by check_kfunc_args() */ 13158 mark_btf_func_reg_size(env, regno, t->size); 13159 } 13160 13161 if (bpf_is_iter_next_kfunc(&meta)) { 13162 err = process_iter_next_call(env, insn_idx, &meta); 13163 if (err) 13164 return err; 13165 } 13166 13167 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 13168 env->prog->call_session_cookie = true; 13169 13170 if (bpf_is_throw_kfunc(insn)) 13171 return process_bpf_exit_full(env, NULL, true); 13172 13173 return 0; 13174 } 13175 13176 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env, 13177 const struct bpf_reg_state *reg, 13178 enum bpf_reg_type type) 13179 { 13180 bool known = tnum_is_const(reg->var_off); 13181 s64 val = reg->var_off.value; 13182 s64 smin = reg_smin(reg); 13183 13184 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13185 verbose(env, "math between %s pointer and %lld is not allowed\n", 13186 reg_type_str(env, type), val); 13187 return false; 13188 } 13189 13190 if (smin == S64_MIN) { 13191 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 13192 reg_type_str(env, type)); 13193 return false; 13194 } 13195 13196 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13197 verbose(env, "value %lld makes %s pointer be out of bounds\n", 13198 smin, reg_type_str(env, type)); 13199 return false; 13200 } 13201 13202 return true; 13203 } 13204 13205 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env, 13206 const struct bpf_reg_state *reg, 13207 enum bpf_reg_type type) 13208 { 13209 bool known = tnum_is_const(reg->var_off); 13210 s64 val = reg->var_off.value; 13211 s64 smin = reg_smin(reg); 13212 13213 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13214 verbose(env, "%s pointer offset %lld is not allowed\n", 13215 reg_type_str(env, type), val); 13216 return false; 13217 } 13218 13219 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13220 verbose(env, "%s pointer offset %lld is not allowed\n", 13221 reg_type_str(env, type), smin); 13222 return false; 13223 } 13224 13225 return true; 13226 } 13227 13228 enum { 13229 REASON_BOUNDS = -1, 13230 REASON_TYPE = -2, 13231 REASON_PATHS = -3, 13232 REASON_LIMIT = -4, 13233 REASON_STACK = -5, 13234 }; 13235 13236 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 13237 u32 *alu_limit, bool mask_to_left) 13238 { 13239 u32 max = 0, ptr_limit = 0; 13240 13241 switch (ptr_reg->type) { 13242 case PTR_TO_STACK: 13243 /* Offset 0 is out-of-bounds, but acceptable start for the 13244 * left direction, see BPF_REG_FP. Also, unknown scalar 13245 * offset where we would need to deal with min/max bounds is 13246 * currently prohibited for unprivileged. 13247 */ 13248 max = MAX_BPF_STACK + mask_to_left; 13249 ptr_limit = -ptr_reg->var_off.value; 13250 break; 13251 case PTR_TO_MAP_VALUE: 13252 max = ptr_reg->map_ptr->value_size; 13253 ptr_limit = mask_to_left ? reg_smin(ptr_reg) : reg_umax(ptr_reg); 13254 break; 13255 default: 13256 return REASON_TYPE; 13257 } 13258 13259 if (ptr_limit >= max) 13260 return REASON_LIMIT; 13261 *alu_limit = ptr_limit; 13262 return 0; 13263 } 13264 13265 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 13266 const struct bpf_insn *insn) 13267 { 13268 return env->bypass_spec_v1 || 13269 BPF_SRC(insn->code) == BPF_K || 13270 cur_aux(env)->nospec; 13271 } 13272 13273 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 13274 u32 alu_state, u32 alu_limit) 13275 { 13276 /* If we arrived here from different branches with different 13277 * state or limits to sanitize, then this won't work. 13278 */ 13279 if (aux->alu_state && 13280 (aux->alu_state != alu_state || 13281 aux->alu_limit != alu_limit)) 13282 return REASON_PATHS; 13283 13284 /* Corresponding fixup done in do_misc_fixups(). */ 13285 aux->alu_state = alu_state; 13286 aux->alu_limit = alu_limit; 13287 return 0; 13288 } 13289 13290 static int sanitize_val_alu(struct bpf_verifier_env *env, 13291 struct bpf_insn *insn) 13292 { 13293 struct bpf_insn_aux_data *aux = cur_aux(env); 13294 13295 if (can_skip_alu_sanitation(env, insn)) 13296 return 0; 13297 13298 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13299 } 13300 13301 static bool sanitize_needed(u8 opcode) 13302 { 13303 return opcode == BPF_ADD || opcode == BPF_SUB; 13304 } 13305 13306 struct bpf_sanitize_info { 13307 struct bpf_insn_aux_data aux; 13308 bool mask_to_left; 13309 }; 13310 13311 static int sanitize_speculative_path(struct bpf_verifier_env *env, 13312 const struct bpf_insn *insn, 13313 u32 next_idx, u32 curr_idx) 13314 { 13315 struct bpf_verifier_state *branch; 13316 struct bpf_reg_state *regs; 13317 13318 branch = push_stack(env, next_idx, curr_idx, true); 13319 if (!IS_ERR(branch) && insn) { 13320 regs = branch->frame[branch->curframe]->regs; 13321 if (BPF_SRC(insn->code) == BPF_K) { 13322 mark_reg_unknown(env, regs, insn->dst_reg); 13323 } else if (BPF_SRC(insn->code) == BPF_X) { 13324 mark_reg_unknown(env, regs, insn->dst_reg); 13325 mark_reg_unknown(env, regs, insn->src_reg); 13326 } 13327 } 13328 return PTR_ERR_OR_ZERO(branch); 13329 } 13330 13331 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13332 struct bpf_insn *insn, 13333 const struct bpf_reg_state *ptr_reg, 13334 const struct bpf_reg_state *off_reg, 13335 struct bpf_reg_state *dst_reg, 13336 struct bpf_sanitize_info *info, 13337 const bool commit_window) 13338 { 13339 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13340 struct bpf_verifier_state *vstate = env->cur_state; 13341 bool off_is_imm = tnum_is_const(off_reg->var_off); 13342 bool off_is_neg = reg_smin(off_reg) < 0; 13343 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13344 u8 opcode = BPF_OP(insn->code); 13345 u32 alu_state, alu_limit; 13346 struct bpf_reg_state tmp; 13347 int err; 13348 13349 if (can_skip_alu_sanitation(env, insn)) 13350 return 0; 13351 13352 /* We already marked aux for masking from non-speculative 13353 * paths, thus we got here in the first place. We only care 13354 * to explore bad access from here. 13355 */ 13356 if (vstate->speculative) 13357 goto do_sim; 13358 13359 if (!commit_window) { 13360 if (!tnum_is_const(off_reg->var_off) && 13361 (reg_smin(off_reg) < 0) != (reg_smax(off_reg) < 0)) 13362 return REASON_BOUNDS; 13363 13364 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13365 (opcode == BPF_SUB && !off_is_neg); 13366 } 13367 13368 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13369 if (err < 0) 13370 return err; 13371 13372 if (commit_window) { 13373 /* In commit phase we narrow the masking window based on 13374 * the observed pointer move after the simulated operation. 13375 */ 13376 alu_state = info->aux.alu_state; 13377 alu_limit = abs(info->aux.alu_limit - alu_limit); 13378 } else { 13379 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13380 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13381 alu_state |= ptr_is_dst_reg ? 13382 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13383 13384 /* Limit pruning on unknown scalars to enable deep search for 13385 * potential masking differences from other program paths. 13386 */ 13387 if (!off_is_imm) 13388 env->explore_alu_limits = true; 13389 } 13390 13391 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13392 if (err < 0) 13393 return err; 13394 do_sim: 13395 /* If we're in commit phase, we're done here given we already 13396 * pushed the truncated dst_reg into the speculative verification 13397 * stack. 13398 * 13399 * Also, when register is a known constant, we rewrite register-based 13400 * operation to immediate-based, and thus do not need masking (and as 13401 * a consequence, do not need to simulate the zero-truncation either). 13402 */ 13403 if (commit_window || off_is_imm) 13404 return 0; 13405 13406 /* Simulate and find potential out-of-bounds access under 13407 * speculative execution from truncation as a result of 13408 * masking when off was not within expected range. If off 13409 * sits in dst, then we temporarily need to move ptr there 13410 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13411 * for cases where we use K-based arithmetic in one direction 13412 * and truncated reg-based in the other in order to explore 13413 * bad access. 13414 */ 13415 if (!ptr_is_dst_reg) { 13416 tmp = *dst_reg; 13417 *dst_reg = *ptr_reg; 13418 } 13419 err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx); 13420 if (err < 0) 13421 return REASON_STACK; 13422 if (!ptr_is_dst_reg) 13423 *dst_reg = tmp; 13424 return 0; 13425 } 13426 13427 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13428 { 13429 struct bpf_verifier_state *vstate = env->cur_state; 13430 13431 /* If we simulate paths under speculation, we don't update the 13432 * insn as 'seen' such that when we verify unreachable paths in 13433 * the non-speculative domain, sanitize_dead_code() can still 13434 * rewrite/sanitize them. 13435 */ 13436 if (!vstate->speculative) 13437 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13438 } 13439 13440 static int sanitize_err(struct bpf_verifier_env *env, 13441 const struct bpf_insn *insn, int reason, 13442 const struct bpf_reg_state *off_reg, 13443 const struct bpf_reg_state *dst_reg) 13444 { 13445 static const char *err = "pointer arithmetic with it prohibited for !root"; 13446 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13447 u32 dst = insn->dst_reg, src = insn->src_reg; 13448 13449 switch (reason) { 13450 case REASON_BOUNDS: 13451 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13452 off_reg == dst_reg ? dst : src, err); 13453 break; 13454 case REASON_TYPE: 13455 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13456 off_reg == dst_reg ? src : dst, err); 13457 break; 13458 case REASON_PATHS: 13459 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13460 dst, op, err); 13461 break; 13462 case REASON_LIMIT: 13463 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13464 dst, op, err); 13465 break; 13466 case REASON_STACK: 13467 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13468 dst, err); 13469 return -ENOMEM; 13470 default: 13471 verifier_bug(env, "unknown reason (%d)", reason); 13472 break; 13473 } 13474 13475 return -EACCES; 13476 } 13477 13478 /* check that stack access falls within stack limits and that 'reg' doesn't 13479 * have a variable offset. 13480 * 13481 * Variable offset is prohibited for unprivileged mode for simplicity since it 13482 * requires corresponding support in Spectre masking for stack ALU. See also 13483 * retrieve_ptr_limit(). 13484 */ 13485 static int check_stack_access_for_ptr_arithmetic( 13486 struct bpf_verifier_env *env, 13487 int regno, 13488 const struct bpf_reg_state *reg, 13489 int off) 13490 { 13491 if (!tnum_is_const(reg->var_off)) { 13492 char tn_buf[48]; 13493 13494 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13495 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13496 regno, tn_buf, off); 13497 return -EACCES; 13498 } 13499 13500 if (off >= 0 || off < -MAX_BPF_STACK) { 13501 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13502 "prohibited for !root; off=%d\n", regno, off); 13503 return -EACCES; 13504 } 13505 13506 return 0; 13507 } 13508 13509 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13510 const struct bpf_insn *insn, 13511 struct bpf_reg_state *dst_reg) 13512 { 13513 u32 dst = insn->dst_reg; 13514 13515 /* For unprivileged we require that resulting offset must be in bounds 13516 * in order to be able to sanitize access later on. 13517 */ 13518 if (env->bypass_spec_v1) 13519 return 0; 13520 13521 switch (dst_reg->type) { 13522 case PTR_TO_STACK: 13523 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13524 dst_reg->var_off.value)) 13525 return -EACCES; 13526 break; 13527 case PTR_TO_MAP_VALUE: 13528 if (check_map_access(env, dst_reg, argno_from_reg(dst), 0, 1, false, ACCESS_HELPER)) { 13529 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13530 "prohibited for !root\n", dst); 13531 return -EACCES; 13532 } 13533 break; 13534 default: 13535 return -EOPNOTSUPP; 13536 } 13537 13538 return 0; 13539 } 13540 13541 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13542 * Caller should also handle BPF_MOV case separately. 13543 * If we return -EACCES, caller may want to try again treating pointer as a 13544 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13545 */ 13546 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13547 struct bpf_insn *insn, 13548 const struct bpf_reg_state *ptr_reg, 13549 const struct bpf_reg_state *off_reg) 13550 { 13551 struct bpf_verifier_state *vstate = env->cur_state; 13552 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13553 struct bpf_reg_state *regs = state->regs, *dst_reg; 13554 bool known = tnum_is_const(off_reg->var_off); 13555 s64 smin_val = reg_smin(off_reg), smax_val = reg_smax(off_reg); 13556 u64 umin_val = reg_umin(off_reg), umax_val = reg_umax(off_reg); 13557 struct bpf_sanitize_info info = {}; 13558 u8 opcode = BPF_OP(insn->code); 13559 u32 dst = insn->dst_reg; 13560 int ret, bounds_ret; 13561 13562 dst_reg = ®s[dst]; 13563 13564 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13565 smin_val > smax_val || umin_val > umax_val) { 13566 /* Taint dst register if offset had invalid bounds derived from 13567 * e.g. dead branches. 13568 */ 13569 __mark_reg_unknown(env, dst_reg); 13570 return 0; 13571 } 13572 13573 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13574 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13575 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13576 __mark_reg_unknown(env, dst_reg); 13577 return 0; 13578 } 13579 13580 verbose(env, 13581 "R%d 32-bit pointer arithmetic prohibited\n", 13582 dst); 13583 return -EACCES; 13584 } 13585 13586 if (ptr_reg->type & PTR_MAYBE_NULL) { 13587 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13588 dst, reg_type_str(env, ptr_reg->type)); 13589 return -EACCES; 13590 } 13591 13592 /* 13593 * Accesses to untrusted PTR_TO_MEM are done through probe 13594 * instructions, hence no need to track offsets. 13595 */ 13596 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 13597 return 0; 13598 13599 switch (base_type(ptr_reg->type)) { 13600 case PTR_TO_CTX: 13601 case PTR_TO_MAP_VALUE: 13602 case PTR_TO_MAP_KEY: 13603 case PTR_TO_STACK: 13604 case PTR_TO_PACKET_META: 13605 case PTR_TO_PACKET: 13606 case PTR_TO_TP_BUFFER: 13607 case PTR_TO_BTF_ID: 13608 case PTR_TO_MEM: 13609 case PTR_TO_BUF: 13610 case PTR_TO_FUNC: 13611 case CONST_PTR_TO_DYNPTR: 13612 break; 13613 case PTR_TO_FLOW_KEYS: 13614 if (known) 13615 break; 13616 fallthrough; 13617 case CONST_PTR_TO_MAP: 13618 /* smin_val represents the known value */ 13619 if (known && smin_val == 0 && opcode == BPF_ADD) 13620 break; 13621 fallthrough; 13622 default: 13623 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13624 dst, reg_type_str(env, ptr_reg->type)); 13625 return -EACCES; 13626 } 13627 13628 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13629 * The id may be overwritten later if we create a new variable offset. 13630 */ 13631 dst_reg->type = ptr_reg->type; 13632 dst_reg->id = ptr_reg->id; 13633 13634 if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type) || 13635 !check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) 13636 return -EINVAL; 13637 13638 /* pointer types do not carry 32-bit bounds at the moment. */ 13639 __mark_reg32_unbounded(dst_reg); 13640 13641 if (sanitize_needed(opcode)) { 13642 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13643 &info, false); 13644 if (ret < 0) 13645 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13646 } 13647 13648 switch (opcode) { 13649 case BPF_ADD: 13650 /* 13651 * dst_reg gets the pointer type and since some positive 13652 * integer value was added to the pointer, give it a new 'id' 13653 * if it's a PTR_TO_PACKET. 13654 * this creates a new 'base' pointer, off_reg (variable) gets 13655 * added into the variable offset, and we copy the fixed offset 13656 * from ptr_reg. 13657 */ 13658 dst_reg->r64 = cnum64_add(ptr_reg->r64, off_reg->r64); 13659 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13660 dst_reg->raw = ptr_reg->raw; 13661 if (reg_is_pkt_pointer(ptr_reg)) { 13662 if (!known) 13663 dst_reg->id = ++env->id_gen; 13664 /* 13665 * Clear range for unknown addends since we can't know 13666 * where the pkt pointer ended up. Also clear AT_PKT_END / 13667 * BEYOND_PKT_END from prior comparison as any pointer 13668 * arithmetic invalidates them. 13669 */ 13670 if (!known || dst_reg->range < 0) 13671 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13672 } 13673 break; 13674 case BPF_SUB: 13675 if (dst_reg == off_reg) { 13676 /* scalar -= pointer. Creates an unknown scalar */ 13677 verbose(env, "R%d tried to subtract pointer from scalar\n", 13678 dst); 13679 return -EACCES; 13680 } 13681 /* We don't allow subtraction from FP, because (according to 13682 * test_verifier.c test "invalid fp arithmetic", JITs might not 13683 * be able to deal with it. 13684 */ 13685 if (ptr_reg->type == PTR_TO_STACK) { 13686 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13687 dst); 13688 return -EACCES; 13689 } 13690 dst_reg->r64 = cnum64_add(ptr_reg->r64, cnum64_negate(off_reg->r64)); 13691 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13692 dst_reg->raw = ptr_reg->raw; 13693 if (reg_is_pkt_pointer(ptr_reg)) { 13694 if (!known) 13695 dst_reg->id = ++env->id_gen; 13696 /* 13697 * Clear range if the subtrahend may be negative since 13698 * pkt pointer could move past its bounds. A positive 13699 * subtrahend moves it backwards keeping positive range 13700 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from 13701 * prior comparison as arithmetic invalidates them. 13702 */ 13703 if ((!known && smin_val < 0) || dst_reg->range < 0) 13704 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13705 } 13706 break; 13707 case BPF_AND: 13708 case BPF_OR: 13709 case BPF_XOR: 13710 /* bitwise ops on pointers are troublesome, prohibit. */ 13711 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13712 dst, bpf_alu_string[opcode >> 4]); 13713 return -EACCES; 13714 default: 13715 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13716 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13717 dst, bpf_alu_string[opcode >> 4]); 13718 return -EACCES; 13719 } 13720 13721 if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) 13722 return -EINVAL; 13723 reg_bounds_sync(dst_reg); 13724 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 13725 if (bounds_ret == -EACCES) 13726 return bounds_ret; 13727 if (sanitize_needed(opcode)) { 13728 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13729 &info, true); 13730 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 13731 && !env->cur_state->speculative 13732 && bounds_ret 13733 && !ret, 13734 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 13735 return -EFAULT; 13736 } 13737 if (ret < 0) 13738 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13739 } 13740 13741 return 0; 13742 } 13743 13744 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13745 struct bpf_reg_state *src_reg) 13746 { 13747 dst_reg->r32 = cnum32_add(dst_reg->r32, src_reg->r32); 13748 } 13749 13750 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13751 struct bpf_reg_state *src_reg) 13752 { 13753 dst_reg->r64 = cnum64_add(dst_reg->r64, src_reg->r64); 13754 } 13755 13756 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13757 struct bpf_reg_state *src_reg) 13758 { 13759 dst_reg->r32 = cnum32_add(dst_reg->r32, cnum32_negate(src_reg->r32)); 13760 } 13761 13762 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13763 struct bpf_reg_state *src_reg) 13764 { 13765 dst_reg->r64 = cnum64_add(dst_reg->r64, cnum64_negate(src_reg->r64)); 13766 } 13767 13768 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13769 struct bpf_reg_state *src_reg) 13770 { 13771 s32 smin = reg_s32_min(dst_reg); 13772 s32 smax = reg_s32_max(dst_reg); 13773 u32 umin = reg_u32_min(dst_reg); 13774 u32 umax = reg_u32_max(dst_reg); 13775 s32 tmp_prod[4]; 13776 13777 if (check_mul_overflow(umax, reg_u32_max(src_reg), &umax) || 13778 check_mul_overflow(umin, reg_u32_min(src_reg), &umin)) { 13779 /* Overflow possible, we know nothing */ 13780 umin = 0; 13781 umax = U32_MAX; 13782 } 13783 if (check_mul_overflow(smin, reg_s32_min(src_reg), &tmp_prod[0]) || 13784 check_mul_overflow(smin, reg_s32_max(src_reg), &tmp_prod[1]) || 13785 check_mul_overflow(smax, reg_s32_min(src_reg), &tmp_prod[2]) || 13786 check_mul_overflow(smax, reg_s32_max(src_reg), &tmp_prod[3])) { 13787 /* Overflow possible, we know nothing */ 13788 smin = S32_MIN; 13789 smax = S32_MAX; 13790 } else { 13791 smin = min_array(tmp_prod, 4); 13792 smax = max_array(tmp_prod, 4); 13793 } 13794 13795 dst_reg->r32 = cnum32_intersect(cnum32_from_urange(umin, umax), 13796 cnum32_from_srange(smin, smax)); 13797 } 13798 13799 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13800 struct bpf_reg_state *src_reg) 13801 { 13802 s64 smin = reg_smin(dst_reg); 13803 s64 smax = reg_smax(dst_reg); 13804 u64 umin = reg_umin(dst_reg); 13805 u64 umax = reg_umax(dst_reg); 13806 s64 tmp_prod[4]; 13807 13808 if (check_mul_overflow(umax, reg_umax(src_reg), &umax) || 13809 check_mul_overflow(umin, reg_umin(src_reg), &umin)) { 13810 /* Overflow possible, we know nothing */ 13811 umin = 0; 13812 umax = U64_MAX; 13813 } 13814 if (check_mul_overflow(smin, reg_smin(src_reg), &tmp_prod[0]) || 13815 check_mul_overflow(smin, reg_smax(src_reg), &tmp_prod[1]) || 13816 check_mul_overflow(smax, reg_smin(src_reg), &tmp_prod[2]) || 13817 check_mul_overflow(smax, reg_smax(src_reg), &tmp_prod[3])) { 13818 /* Overflow possible, we know nothing */ 13819 smin = S64_MIN; 13820 smax = S64_MAX; 13821 } else { 13822 smin = min_array(tmp_prod, 4); 13823 smax = max_array(tmp_prod, 4); 13824 } 13825 13826 dst_reg->r64 = cnum64_intersect(cnum64_from_urange(umin, umax), 13827 cnum64_from_srange(smin, smax)); 13828 } 13829 13830 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg, 13831 struct bpf_reg_state *src_reg) 13832 { 13833 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 13834 13835 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) / src_val, 13836 reg_u32_max(dst_reg) / src_val); 13837 13838 /* Reset other ranges/tnum to unbounded/unknown. */ 13839 reset_reg64_and_tnum(dst_reg); 13840 } 13841 13842 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg, 13843 struct bpf_reg_state *src_reg) 13844 { 13845 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 13846 13847 reg_set_urange64(dst_reg, div64_u64(reg_umin(dst_reg), src_val), 13848 div64_u64(reg_umax(dst_reg), src_val)); 13849 13850 /* Reset other ranges/tnum to unbounded/unknown. */ 13851 reset_reg32_and_tnum(dst_reg); 13852 } 13853 13854 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg, 13855 struct bpf_reg_state *src_reg) 13856 { 13857 s32 smin = reg_s32_min(dst_reg); 13858 s32 smax = reg_s32_max(dst_reg); 13859 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 13860 s32 res1, res2; 13861 13862 /* BPF div specification: S32_MIN / -1 = S32_MIN */ 13863 if (smin == S32_MIN && src_val == -1) { 13864 /* 13865 * If the dividend range contains more than just S32_MIN, 13866 * we cannot precisely track the result, so it becomes unbounded. 13867 * e.g., [S32_MIN, S32_MIN+10]/(-1), 13868 * = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)] 13869 * = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX] 13870 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN. 13871 */ 13872 if (smax != S32_MIN) { 13873 smin = S32_MIN; 13874 smax = S32_MAX; 13875 } 13876 goto reset; 13877 } 13878 13879 res1 = smin / src_val; 13880 res2 = smax / src_val; 13881 smin = min(res1, res2); 13882 smax = max(res1, res2); 13883 13884 reset: 13885 reg_set_srange32(dst_reg, smin, smax); 13886 /* Reset other ranges/tnum to unbounded/unknown. */ 13887 reset_reg64_and_tnum(dst_reg); 13888 } 13889 13890 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg, 13891 struct bpf_reg_state *src_reg) 13892 { 13893 s64 smin = reg_smin(dst_reg); 13894 s64 smax = reg_smax(dst_reg); 13895 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 13896 s64 res1, res2; 13897 13898 /* BPF div specification: S64_MIN / -1 = S64_MIN */ 13899 if (smin == S64_MIN && src_val == -1) { 13900 /* 13901 * If the dividend range contains more than just S64_MIN, 13902 * we cannot precisely track the result, so it becomes unbounded. 13903 * e.g., [S64_MIN, S64_MIN+10]/(-1), 13904 * = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)] 13905 * = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX] 13906 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN. 13907 */ 13908 if (smax != S64_MIN) { 13909 smin = S64_MIN; 13910 smax = S64_MAX; 13911 } 13912 goto reset; 13913 } 13914 13915 res1 = div64_s64(smin, src_val); 13916 res2 = div64_s64(smax, src_val); 13917 smin = min(res1, res2); 13918 smax = max(res1, res2); 13919 13920 reset: 13921 reg_set_srange64(dst_reg, smin, smax); 13922 /* Reset other ranges/tnum to unbounded/unknown. */ 13923 reset_reg32_and_tnum(dst_reg); 13924 } 13925 13926 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg, 13927 struct bpf_reg_state *src_reg) 13928 { 13929 u32 src_val = reg_u32_min(src_reg); /* non-zero, const divisor */ 13930 u32 res_max = src_val - 1; 13931 13932 /* 13933 * If dst_umax <= res_max, the result remains unchanged. 13934 * e.g., [2, 5] % 10 = [2, 5]. 13935 */ 13936 if (reg_u32_max(dst_reg) <= res_max) 13937 return; 13938 13939 reg_set_urange32(dst_reg, 0, min(reg_u32_max(dst_reg), res_max)); 13940 13941 /* Reset other ranges/tnum to unbounded/unknown. */ 13942 reset_reg64_and_tnum(dst_reg); 13943 } 13944 13945 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg, 13946 struct bpf_reg_state *src_reg) 13947 { 13948 u64 src_val = reg_umin(src_reg); /* non-zero, const divisor */ 13949 u64 res_max = src_val - 1; 13950 13951 /* 13952 * If dst_umax <= res_max, the result remains unchanged. 13953 * e.g., [2, 5] % 10 = [2, 5]. 13954 */ 13955 if (reg_umax(dst_reg) <= res_max) 13956 return; 13957 13958 reg_set_urange64(dst_reg, 0, min(reg_umax(dst_reg), res_max)); 13959 13960 /* Reset other ranges/tnum to unbounded/unknown. */ 13961 reset_reg32_and_tnum(dst_reg); 13962 } 13963 13964 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg, 13965 struct bpf_reg_state *src_reg) 13966 { 13967 s32 src_val = reg_s32_min(src_reg); /* non-zero, const divisor */ 13968 13969 /* 13970 * Safe absolute value calculation: 13971 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648. 13972 * Here use unsigned integer to avoid overflow. 13973 */ 13974 u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val; 13975 13976 /* 13977 * Calculate the maximum possible absolute value of the result. 13978 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives 13979 * 2147483647 (S32_MAX), which fits perfectly in s32. 13980 */ 13981 s32 res_max_abs = src_abs - 1; 13982 13983 /* 13984 * If the dividend is already within the result range, 13985 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 13986 */ 13987 if (reg_s32_min(dst_reg) >= -res_max_abs && reg_s32_max(dst_reg) <= res_max_abs) 13988 return; 13989 13990 /* General case: result has the same sign as the dividend. */ 13991 if (reg_s32_min(dst_reg) >= 0) { 13992 reg_set_srange32(dst_reg, 0, min(reg_s32_max(dst_reg), res_max_abs)); 13993 } else if (reg_s32_max(dst_reg) <= 0) { 13994 reg_set_srange32(dst_reg, max(reg_s32_min(dst_reg), -res_max_abs), 0); 13995 } else { 13996 reg_set_srange32(dst_reg, -res_max_abs, res_max_abs); 13997 } 13998 13999 /* Reset other ranges/tnum to unbounded/unknown. */ 14000 reset_reg64_and_tnum(dst_reg); 14001 } 14002 14003 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg, 14004 struct bpf_reg_state *src_reg) 14005 { 14006 s64 src_val = reg_smin(src_reg); /* non-zero, const divisor */ 14007 14008 /* 14009 * Safe absolute value calculation: 14010 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63. 14011 * Here use unsigned integer to avoid overflow. 14012 */ 14013 u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val; 14014 14015 /* 14016 * Calculate the maximum possible absolute value of the result. 14017 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives 14018 * 2^63 - 1 (S64_MAX), which fits perfectly in s64. 14019 */ 14020 s64 res_max_abs = src_abs - 1; 14021 14022 /* 14023 * If the dividend is already within the result range, 14024 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14025 */ 14026 if (reg_smin(dst_reg) >= -res_max_abs && reg_smax(dst_reg) <= res_max_abs) 14027 return; 14028 14029 /* General case: result has the same sign as the dividend. */ 14030 if (reg_smin(dst_reg) >= 0) { 14031 reg_set_srange64(dst_reg, 0, min(reg_smax(dst_reg), res_max_abs)); 14032 } else if (reg_smax(dst_reg) <= 0) { 14033 reg_set_srange64(dst_reg, max(reg_smin(dst_reg), -res_max_abs), 0); 14034 } else { 14035 reg_set_srange64(dst_reg, -res_max_abs, res_max_abs); 14036 } 14037 14038 /* Reset other ranges/tnum to unbounded/unknown. */ 14039 reset_reg32_and_tnum(dst_reg); 14040 } 14041 14042 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14043 struct bpf_reg_state *src_reg) 14044 { 14045 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14046 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14047 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14048 u32 umax_val = reg_u32_max(src_reg); 14049 14050 if (src_known && dst_known) { 14051 __mark_reg32_known(dst_reg, var32_off.value); 14052 return; 14053 } 14054 14055 /* We get our minimum from the var_off, since that's inherently 14056 * bitwise. Our maximum is the minimum of the operands' maxima. 14057 */ 14058 reg_set_urange32(dst_reg, 14059 var32_off.value, 14060 min(reg_u32_max(dst_reg), umax_val)); 14061 } 14062 14063 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14064 struct bpf_reg_state *src_reg) 14065 { 14066 bool src_known = tnum_is_const(src_reg->var_off); 14067 bool dst_known = tnum_is_const(dst_reg->var_off); 14068 u64 umax_val = reg_umax(src_reg); 14069 14070 if (src_known && dst_known) { 14071 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14072 return; 14073 } 14074 14075 /* We get our minimum from the var_off, since that's inherently 14076 * bitwise. Our maximum is the minimum of the operands' maxima. 14077 */ 14078 reg_set_urange64(dst_reg, 14079 dst_reg->var_off.value, 14080 min(reg_umax(dst_reg), umax_val)); 14081 14082 /* We may learn something more from the var_off */ 14083 __update_reg_bounds(dst_reg); 14084 } 14085 14086 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14087 struct bpf_reg_state *src_reg) 14088 { 14089 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14090 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14091 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14092 u32 umin_val = reg_u32_min(src_reg); 14093 14094 if (src_known && dst_known) { 14095 __mark_reg32_known(dst_reg, var32_off.value); 14096 return; 14097 } 14098 14099 /* We get our maximum from the var_off, and our minimum is the 14100 * maximum of the operands' minima 14101 */ 14102 reg_set_urange32(dst_reg, 14103 max(reg_u32_min(dst_reg), umin_val), 14104 var32_off.value | var32_off.mask); 14105 } 14106 14107 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14108 struct bpf_reg_state *src_reg) 14109 { 14110 bool src_known = tnum_is_const(src_reg->var_off); 14111 bool dst_known = tnum_is_const(dst_reg->var_off); 14112 u64 umin_val = reg_umin(src_reg); 14113 14114 if (src_known && dst_known) { 14115 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14116 return; 14117 } 14118 14119 /* We get our maximum from the var_off, and our minimum is the 14120 * maximum of the operands' minima 14121 */ 14122 reg_set_urange64(dst_reg, 14123 max(reg_umin(dst_reg), umin_val), 14124 dst_reg->var_off.value | dst_reg->var_off.mask); 14125 14126 /* We may learn something more from the var_off */ 14127 __update_reg_bounds(dst_reg); 14128 } 14129 14130 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 14131 struct bpf_reg_state *src_reg) 14132 { 14133 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14134 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14135 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14136 14137 if (src_known && dst_known) { 14138 __mark_reg32_known(dst_reg, var32_off.value); 14139 return; 14140 } 14141 14142 /* We get both minimum and maximum from the var32_off. */ 14143 reg_set_urange32(dst_reg, var32_off.value, var32_off.value | var32_off.mask); 14144 } 14145 14146 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 14147 struct bpf_reg_state *src_reg) 14148 { 14149 bool src_known = tnum_is_const(src_reg->var_off); 14150 bool dst_known = tnum_is_const(dst_reg->var_off); 14151 14152 if (src_known && dst_known) { 14153 /* dst_reg->var_off.value has been updated earlier */ 14154 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14155 return; 14156 } 14157 14158 /* We get both minimum and maximum from the var_off. */ 14159 reg_set_urange64(dst_reg, 14160 dst_reg->var_off.value, 14161 dst_reg->var_off.value | dst_reg->var_off.mask); 14162 } 14163 14164 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14165 u64 umin_val, u64 umax_val) 14166 { 14167 /* If we might shift our top bit out, then we know nothing */ 14168 if (umax_val > 31 || reg_u32_max(dst_reg) > 1ULL << (31 - umax_val)) 14169 reg_set_urange32(dst_reg, 0, U32_MAX); 14170 else 14171 /* We lose all sign bit information (except what we can pick 14172 * up from var_off) 14173 */ 14174 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) << umin_val, 14175 reg_u32_max(dst_reg) << umax_val); 14176 } 14177 14178 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14179 struct bpf_reg_state *src_reg) 14180 { 14181 u32 umax_val = reg_u32_max(src_reg); 14182 u32 umin_val = reg_u32_min(src_reg); 14183 /* u32 alu operation will zext upper bits */ 14184 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14185 14186 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14187 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 14188 /* Not required but being careful mark reg64 bounds as unknown so 14189 * that we are forced to pick them up from tnum and zext later and 14190 * if some path skips this step we are still safe. 14191 */ 14192 __mark_reg64_unbounded(dst_reg); 14193 __update_reg32_bounds(dst_reg); 14194 } 14195 14196 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 14197 u64 umin_val, u64 umax_val) 14198 { 14199 struct cnum64 u, s; 14200 14201 /* Special case <<32 because it is a common compiler pattern to sign 14202 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct 14203 * because s32 bounds don't flip sign when shifting to the left by 14204 * 32bits. 14205 */ 14206 if (umin_val == 32 && umax_val == 32) 14207 s = cnum64_from_srange((s64)reg_s32_min(dst_reg) << 32, 14208 (s64)reg_s32_max(dst_reg) << 32); 14209 else 14210 s = CNUM64_UNBOUNDED; 14211 14212 /* If we might shift our top bit out, then we know nothing */ 14213 if (reg_umax(dst_reg) > 1ULL << (63 - umax_val)) 14214 u = CNUM64_UNBOUNDED; 14215 else 14216 u = cnum64_from_urange(reg_umin(dst_reg) << umin_val, 14217 reg_umax(dst_reg) << umax_val); 14218 14219 dst_reg->r64 = cnum64_intersect(u, s); 14220 } 14221 14222 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 14223 struct bpf_reg_state *src_reg) 14224 { 14225 u64 umax_val = reg_umax(src_reg); 14226 u64 umin_val = reg_umin(src_reg); 14227 14228 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 14229 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 14230 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14231 14232 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 14233 /* We may learn something more from the var_off */ 14234 __update_reg_bounds(dst_reg); 14235 } 14236 14237 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 14238 struct bpf_reg_state *src_reg) 14239 { 14240 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14241 u32 umax_val = reg_u32_max(src_reg); 14242 u32 umin_val = reg_u32_min(src_reg); 14243 14244 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14245 * be negative, then either: 14246 * 1) src_reg might be zero, so the sign bit of the result is 14247 * unknown, so we lose our signed bounds 14248 * 2) it's known negative, thus the unsigned bounds capture the 14249 * signed bounds 14250 * 3) the signed bounds cross zero, so they tell us nothing 14251 * about the result 14252 * If the value in dst_reg is known nonnegative, then again the 14253 * unsigned bounds capture the signed bounds. 14254 * Thus, in all cases it suffices to blow away our signed bounds 14255 * and rely on inferring new ones from the unsigned bounds and 14256 * var_off of the result. 14257 */ 14258 14259 dst_reg->var_off = tnum_rshift(subreg, umin_val); 14260 reg_set_urange32(dst_reg, reg_u32_min(dst_reg) >> umax_val, 14261 reg_u32_max(dst_reg) >> umin_val); 14262 14263 __mark_reg64_unbounded(dst_reg); 14264 __update_reg32_bounds(dst_reg); 14265 } 14266 14267 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 14268 struct bpf_reg_state *src_reg) 14269 { 14270 u64 umax_val = reg_umax(src_reg); 14271 u64 umin_val = reg_umin(src_reg); 14272 14273 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14274 * be negative, then either: 14275 * 1) src_reg might be zero, so the sign bit of the result is 14276 * unknown, so we lose our signed bounds 14277 * 2) it's known negative, thus the unsigned bounds capture the 14278 * signed bounds 14279 * 3) the signed bounds cross zero, so they tell us nothing 14280 * about the result 14281 * If the value in dst_reg is known nonnegative, then again the 14282 * unsigned bounds capture the signed bounds. 14283 * Thus, in all cases it suffices to blow away our signed bounds 14284 * and rely on inferring new ones from the unsigned bounds and 14285 * var_off of the result. 14286 */ 14287 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 14288 reg_set_urange64(dst_reg, reg_umin(dst_reg) >> umax_val, 14289 reg_umax(dst_reg) >> umin_val); 14290 14291 /* Its not easy to operate on alu32 bounds here because it depends 14292 * on bits being shifted in. Take easy way out and mark unbounded 14293 * so we can recalculate later from tnum. 14294 */ 14295 __mark_reg32_unbounded(dst_reg); 14296 __update_reg_bounds(dst_reg); 14297 } 14298 14299 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 14300 struct bpf_reg_state *src_reg) 14301 { 14302 u64 umin_val = reg_u32_min(src_reg); 14303 14304 /* Upon reaching here, src_known is true and 14305 * umax_val is equal to umin_val. 14306 * Blow away the dst_reg umin_value/umax_value and rely on 14307 * dst_reg var_off to refine the result. 14308 */ 14309 reg_set_srange32(dst_reg, 14310 (u32)(((s32)reg_s32_min(dst_reg)) >> umin_val), 14311 (u32)(((s32)reg_s32_max(dst_reg)) >> umin_val)); 14312 14313 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 14314 14315 __mark_reg64_unbounded(dst_reg); 14316 __update_reg32_bounds(dst_reg); 14317 } 14318 14319 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 14320 struct bpf_reg_state *src_reg) 14321 { 14322 u64 umin_val = reg_umin(src_reg); 14323 14324 /* Upon reaching here, src_known is true and umax_val is equal 14325 * to umin_val. 14326 */ 14327 reg_set_srange64(dst_reg, reg_smin(dst_reg) >> umin_val, 14328 reg_smax(dst_reg) >> umin_val); 14329 14330 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14331 14332 /* Its not easy to operate on alu32 bounds here because it depends 14333 * on bits being shifted in from upper 32-bits. Take easy way out 14334 * and mark unbounded so we can recalculate later from tnum. 14335 */ 14336 __mark_reg32_unbounded(dst_reg); 14337 __update_reg_bounds(dst_reg); 14338 } 14339 14340 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn) 14341 { 14342 /* 14343 * Byte swap operation - update var_off using tnum_bswap. 14344 * Three cases: 14345 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE) 14346 * unconditional swap 14347 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE) 14348 * swap on big-endian, truncation or no-op on little-endian 14349 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE) 14350 * swap on little-endian, truncation or no-op on big-endian 14351 */ 14352 14353 bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64; 14354 bool to_le = BPF_SRC(insn->code) == BPF_TO_LE; 14355 bool is_big_endian; 14356 #ifdef CONFIG_CPU_BIG_ENDIAN 14357 is_big_endian = true; 14358 #else 14359 is_big_endian = false; 14360 #endif 14361 /* Apply bswap if alu64 or switch between big-endian and little-endian machines */ 14362 bool need_bswap = alu64 || (to_le == is_big_endian); 14363 14364 /* 14365 * If the register is mutated, manually reset its scalar ID to break 14366 * any existing ties and avoid incorrect bounds propagation. 14367 */ 14368 if (need_bswap || insn->imm == 16 || insn->imm == 32) 14369 clear_scalar_id(dst_reg); 14370 14371 if (need_bswap) { 14372 if (insn->imm == 16) 14373 dst_reg->var_off = tnum_bswap16(dst_reg->var_off); 14374 else if (insn->imm == 32) 14375 dst_reg->var_off = tnum_bswap32(dst_reg->var_off); 14376 else if (insn->imm == 64) 14377 dst_reg->var_off = tnum_bswap64(dst_reg->var_off); 14378 /* 14379 * Byteswap scrambles the range, so we must reset bounds. 14380 * Bounds will be re-derived from the new tnum later. 14381 */ 14382 __mark_reg_unbounded(dst_reg); 14383 } 14384 /* For bswap16/32, truncate dst register to match the swapped size */ 14385 if (insn->imm == 16 || insn->imm == 32) 14386 coerce_reg_to_size(dst_reg, insn->imm / 8); 14387 } 14388 14389 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14390 const struct bpf_reg_state *src_reg) 14391 { 14392 bool src_is_const = false; 14393 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14394 14395 if (insn_bitness == 32) { 14396 if (tnum_subreg_is_const(src_reg->var_off) 14397 && reg_s32_min(src_reg) == reg_s32_max(src_reg) 14398 && reg_u32_min(src_reg) == reg_u32_max(src_reg)) 14399 src_is_const = true; 14400 } else { 14401 if (tnum_is_const(src_reg->var_off) 14402 && reg_smin(src_reg) == reg_smax(src_reg) 14403 && reg_umin(src_reg) == reg_umax(src_reg)) 14404 src_is_const = true; 14405 } 14406 14407 switch (BPF_OP(insn->code)) { 14408 case BPF_ADD: 14409 case BPF_SUB: 14410 case BPF_NEG: 14411 case BPF_AND: 14412 case BPF_XOR: 14413 case BPF_OR: 14414 case BPF_MUL: 14415 case BPF_END: 14416 return true; 14417 14418 /* 14419 * Division and modulo operators range is only safe to compute when the 14420 * divisor is a constant. 14421 */ 14422 case BPF_DIV: 14423 case BPF_MOD: 14424 return src_is_const; 14425 14426 /* Shift operators range is only computable if shift dimension operand 14427 * is a constant. Shifts greater than 31 or 63 are undefined. This 14428 * includes shifts by a negative number. 14429 */ 14430 case BPF_LSH: 14431 case BPF_RSH: 14432 case BPF_ARSH: 14433 return (src_is_const && reg_umax(src_reg) < insn_bitness); 14434 default: 14435 return false; 14436 } 14437 } 14438 14439 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn, 14440 struct bpf_reg_state *dst_reg) 14441 { 14442 struct bpf_verifier_state *branch; 14443 struct bpf_reg_state *regs; 14444 bool alu32; 14445 14446 if (reg_smin(dst_reg) == -1 && reg_smax(dst_reg) == 0) 14447 alu32 = false; 14448 else if (reg_s32_min(dst_reg) == -1 && reg_s32_max(dst_reg) == 0) 14449 alu32 = true; 14450 else 14451 return 0; 14452 14453 branch = push_stack(env, env->insn_idx, env->insn_idx, false); 14454 if (IS_ERR(branch)) 14455 return PTR_ERR(branch); 14456 14457 regs = branch->frame[branch->curframe]->regs; 14458 if (alu32) { 14459 __mark_reg32_known(®s[insn->dst_reg], 0); 14460 __mark_reg32_known(dst_reg, -1ull); 14461 } else { 14462 __mark_reg_known(®s[insn->dst_reg], 0); 14463 __mark_reg_known(dst_reg, -1ull); 14464 } 14465 return 0; 14466 } 14467 14468 /* WARNING: This function does calculations on 64-bit values, but the actual 14469 * execution may occur on 32-bit values. Therefore, things like bitshifts 14470 * need extra checks in the 32-bit case. 14471 */ 14472 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14473 struct bpf_insn *insn, 14474 struct bpf_reg_state *dst_reg, 14475 struct bpf_reg_state src_reg) 14476 { 14477 u8 opcode = BPF_OP(insn->code); 14478 s16 off = insn->off; 14479 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14480 int ret; 14481 14482 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14483 __mark_reg_unknown(env, dst_reg); 14484 return 0; 14485 } 14486 14487 if (sanitize_needed(opcode)) { 14488 ret = sanitize_val_alu(env, insn); 14489 if (ret < 0) 14490 return sanitize_err(env, insn, ret, NULL, NULL); 14491 } 14492 14493 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14494 * There are two classes of instructions: The first class we track both 14495 * alu32 and alu64 sign/unsigned bounds independently this provides the 14496 * greatest amount of precision when alu operations are mixed with jmp32 14497 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14498 * and BPF_OR. This is possible because these ops have fairly easy to 14499 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14500 * See alu32 verifier tests for examples. The second class of 14501 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14502 * with regards to tracking sign/unsigned bounds because the bits may 14503 * cross subreg boundaries in the alu64 case. When this happens we mark 14504 * the reg unbounded in the subreg bound space and use the resulting 14505 * tnum to calculate an approximation of the sign/unsigned bounds. 14506 */ 14507 switch (opcode) { 14508 case BPF_ADD: 14509 scalar32_min_max_add(dst_reg, &src_reg); 14510 scalar_min_max_add(dst_reg, &src_reg); 14511 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14512 break; 14513 case BPF_SUB: 14514 scalar32_min_max_sub(dst_reg, &src_reg); 14515 scalar_min_max_sub(dst_reg, &src_reg); 14516 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14517 break; 14518 case BPF_NEG: 14519 env->fake_reg[0] = *dst_reg; 14520 __mark_reg_known(dst_reg, 0); 14521 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 14522 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 14523 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 14524 break; 14525 case BPF_MUL: 14526 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14527 scalar32_min_max_mul(dst_reg, &src_reg); 14528 scalar_min_max_mul(dst_reg, &src_reg); 14529 break; 14530 case BPF_DIV: 14531 /* BPF div specification: x / 0 = 0 */ 14532 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) { 14533 ___mark_reg_known(dst_reg, 0); 14534 break; 14535 } 14536 if (alu32) 14537 if (off == 1) 14538 scalar32_min_max_sdiv(dst_reg, &src_reg); 14539 else 14540 scalar32_min_max_udiv(dst_reg, &src_reg); 14541 else 14542 if (off == 1) 14543 scalar_min_max_sdiv(dst_reg, &src_reg); 14544 else 14545 scalar_min_max_udiv(dst_reg, &src_reg); 14546 break; 14547 case BPF_MOD: 14548 /* BPF mod specification: x % 0 = x */ 14549 if ((alu32 && reg_u32_min(&src_reg) == 0) || (!alu32 && reg_umin(&src_reg) == 0)) 14550 break; 14551 if (alu32) 14552 if (off == 1) 14553 scalar32_min_max_smod(dst_reg, &src_reg); 14554 else 14555 scalar32_min_max_umod(dst_reg, &src_reg); 14556 else 14557 if (off == 1) 14558 scalar_min_max_smod(dst_reg, &src_reg); 14559 else 14560 scalar_min_max_umod(dst_reg, &src_reg); 14561 break; 14562 case BPF_AND: 14563 if (tnum_is_const(src_reg.var_off)) { 14564 ret = maybe_fork_scalars(env, insn, dst_reg); 14565 if (ret) 14566 return ret; 14567 } 14568 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 14569 scalar32_min_max_and(dst_reg, &src_reg); 14570 scalar_min_max_and(dst_reg, &src_reg); 14571 break; 14572 case BPF_OR: 14573 if (tnum_is_const(src_reg.var_off)) { 14574 ret = maybe_fork_scalars(env, insn, dst_reg); 14575 if (ret) 14576 return ret; 14577 } 14578 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 14579 scalar32_min_max_or(dst_reg, &src_reg); 14580 scalar_min_max_or(dst_reg, &src_reg); 14581 break; 14582 case BPF_XOR: 14583 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 14584 scalar32_min_max_xor(dst_reg, &src_reg); 14585 scalar_min_max_xor(dst_reg, &src_reg); 14586 break; 14587 case BPF_LSH: 14588 if (alu32) 14589 scalar32_min_max_lsh(dst_reg, &src_reg); 14590 else 14591 scalar_min_max_lsh(dst_reg, &src_reg); 14592 break; 14593 case BPF_RSH: 14594 if (alu32) 14595 scalar32_min_max_rsh(dst_reg, &src_reg); 14596 else 14597 scalar_min_max_rsh(dst_reg, &src_reg); 14598 break; 14599 case BPF_ARSH: 14600 if (alu32) 14601 scalar32_min_max_arsh(dst_reg, &src_reg); 14602 else 14603 scalar_min_max_arsh(dst_reg, &src_reg); 14604 break; 14605 case BPF_END: 14606 scalar_byte_swap(dst_reg, insn); 14607 break; 14608 default: 14609 break; 14610 } 14611 14612 /* 14613 * ALU32 ops are zero extended into 64bit register. 14614 * 14615 * BPF_END is already handled inside the helper (truncation), 14616 * so skip zext here to avoid unexpected zero extension. 14617 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40 14618 * This is a 64bit byte swap operation with alu32==true, 14619 * but we should not zero extend the result. 14620 */ 14621 if (alu32 && opcode != BPF_END) 14622 zext_32_to_64(dst_reg); 14623 reg_bounds_sync(dst_reg); 14624 return 0; 14625 } 14626 14627 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 14628 * and var_off. 14629 */ 14630 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 14631 struct bpf_insn *insn) 14632 { 14633 struct bpf_verifier_state *vstate = env->cur_state; 14634 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14635 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 14636 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 14637 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14638 u8 opcode = BPF_OP(insn->code); 14639 int err; 14640 14641 dst_reg = ®s[insn->dst_reg]; 14642 if (BPF_SRC(insn->code) == BPF_X) 14643 src_reg = ®s[insn->src_reg]; 14644 else 14645 src_reg = NULL; 14646 14647 /* Case where at least one operand is an arena. */ 14648 if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) { 14649 struct bpf_insn_aux_data *aux = cur_aux(env); 14650 14651 if (dst_reg->type != PTR_TO_ARENA) 14652 *dst_reg = *src_reg; 14653 14654 dst_reg->subreg_def = env->insn_idx + 1; 14655 14656 if (BPF_CLASS(insn->code) == BPF_ALU64) 14657 /* 14658 * 32-bit operations zero upper bits automatically. 14659 * 64-bit operations need to be converted to 32. 14660 */ 14661 aux->needs_zext = true; 14662 14663 /* Any arithmetic operations are allowed on arena pointers */ 14664 return 0; 14665 } 14666 14667 if (dst_reg->type != SCALAR_VALUE) 14668 ptr_reg = dst_reg; 14669 14670 if (BPF_SRC(insn->code) == BPF_X) { 14671 if (src_reg->type != SCALAR_VALUE) { 14672 if (dst_reg->type != SCALAR_VALUE) { 14673 /* Combining two pointers by any ALU op yields 14674 * an arbitrary scalar. Disallow all math except 14675 * pointer subtraction 14676 */ 14677 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 14678 mark_reg_unknown(env, regs, insn->dst_reg); 14679 return 0; 14680 } 14681 verbose(env, "R%d pointer %s pointer prohibited\n", 14682 insn->dst_reg, 14683 bpf_alu_string[opcode >> 4]); 14684 return -EACCES; 14685 } else { 14686 /* scalar += pointer 14687 * This is legal, but we have to reverse our 14688 * src/dest handling in computing the range 14689 */ 14690 err = mark_chain_precision(env, insn->dst_reg); 14691 if (err) 14692 return err; 14693 return adjust_ptr_min_max_vals(env, insn, 14694 src_reg, dst_reg); 14695 } 14696 } else if (ptr_reg) { 14697 /* pointer += scalar */ 14698 err = mark_chain_precision(env, insn->src_reg); 14699 if (err) 14700 return err; 14701 return adjust_ptr_min_max_vals(env, insn, 14702 dst_reg, src_reg); 14703 } else if (dst_reg->precise) { 14704 /* if dst_reg is precise, src_reg should be precise as well */ 14705 err = mark_chain_precision(env, insn->src_reg); 14706 if (err) 14707 return err; 14708 } 14709 } else { 14710 /* Pretend the src is a reg with a known value, since we only 14711 * need to be able to read from this state. 14712 */ 14713 off_reg.type = SCALAR_VALUE; 14714 __mark_reg_known(&off_reg, insn->imm); 14715 src_reg = &off_reg; 14716 if (ptr_reg) /* pointer += K */ 14717 return adjust_ptr_min_max_vals(env, insn, 14718 ptr_reg, src_reg); 14719 } 14720 14721 /* Got here implies adding two SCALAR_VALUEs */ 14722 if (WARN_ON_ONCE(ptr_reg)) { 14723 print_verifier_state(env, vstate, vstate->curframe, true); 14724 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 14725 return -EFAULT; 14726 } 14727 if (WARN_ON(!src_reg)) { 14728 print_verifier_state(env, vstate, vstate->curframe, true); 14729 verbose(env, "verifier internal error: no src_reg\n"); 14730 return -EFAULT; 14731 } 14732 /* 14733 * For alu32 linked register tracking, we need to check dst_reg's 14734 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(), 14735 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX. 14736 */ 14737 u64 dst_umax = reg_umax(dst_reg); 14738 14739 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 14740 if (err) 14741 return err; 14742 /* 14743 * Compilers can generate the code 14744 * r1 = r2 14745 * r1 += 0x1 14746 * if r2 < 1000 goto ... 14747 * use r1 in memory access 14748 * So remember constant delta between r2 and r1 and update r1 after 14749 * 'if' condition. 14750 */ 14751 if (env->bpf_capable && 14752 (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) && 14753 dst_reg->id && is_reg_const(src_reg, alu32) && 14754 !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) { 14755 u64 val = reg_const_value(src_reg, alu32); 14756 s32 off; 14757 14758 if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX)) 14759 goto clear_id; 14760 14761 if (alu32 && (dst_umax > U32_MAX)) 14762 goto clear_id; 14763 14764 off = (s32)val; 14765 14766 if (BPF_OP(insn->code) == BPF_SUB) { 14767 /* Negating S32_MIN would overflow */ 14768 if (off == S32_MIN) 14769 goto clear_id; 14770 off = -off; 14771 } 14772 14773 if (dst_reg->id & BPF_ADD_CONST) { 14774 /* 14775 * If the register already went through rX += val 14776 * we cannot accumulate another val into rx->off. 14777 */ 14778 clear_id: 14779 clear_scalar_id(dst_reg); 14780 } else { 14781 if (alu32) 14782 dst_reg->id |= BPF_ADD_CONST32; 14783 else 14784 dst_reg->id |= BPF_ADD_CONST64; 14785 dst_reg->delta = off; 14786 } 14787 } else { 14788 /* 14789 * Make sure ID is cleared otherwise dst_reg min/max could be 14790 * incorrectly propagated into other registers by sync_linked_regs() 14791 */ 14792 clear_scalar_id(dst_reg); 14793 } 14794 return 0; 14795 } 14796 14797 /* check validity of 32-bit and 64-bit arithmetic operations */ 14798 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 14799 { 14800 struct bpf_reg_state *regs = cur_regs(env); 14801 u8 opcode = BPF_OP(insn->code); 14802 int err; 14803 14804 if (opcode == BPF_END || opcode == BPF_NEG) { 14805 /* check src operand */ 14806 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14807 if (err) 14808 return err; 14809 14810 if (is_pointer_value(env, insn->dst_reg)) { 14811 verbose(env, "R%d pointer arithmetic prohibited\n", 14812 insn->dst_reg); 14813 return -EACCES; 14814 } 14815 14816 /* check dest operand */ 14817 if (regs[insn->dst_reg].type == SCALAR_VALUE) { 14818 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14819 err = err ?: adjust_scalar_min_max_vals(env, insn, 14820 ®s[insn->dst_reg], 14821 regs[insn->dst_reg]); 14822 } else { 14823 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14824 } 14825 if (err) 14826 return err; 14827 14828 } else if (opcode == BPF_MOV) { 14829 14830 if (BPF_SRC(insn->code) == BPF_X) { 14831 if (insn->off == BPF_ADDR_SPACE_CAST) { 14832 if (!env->prog->aux->arena) { 14833 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14834 return -EINVAL; 14835 } 14836 } 14837 14838 /* check src operand */ 14839 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14840 if (err) 14841 return err; 14842 } 14843 14844 /* check dest operand, mark as required later */ 14845 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14846 if (err) 14847 return err; 14848 14849 if (BPF_SRC(insn->code) == BPF_X) { 14850 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14851 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14852 14853 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14854 if (insn->imm) { 14855 /* off == BPF_ADDR_SPACE_CAST */ 14856 mark_reg_unknown(env, regs, insn->dst_reg); 14857 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14858 dst_reg->type = PTR_TO_ARENA; 14859 /* PTR_TO_ARENA is 32-bit */ 14860 dst_reg->subreg_def = env->insn_idx + 1; 14861 } 14862 } else if (insn->off == 0) { 14863 /* case: R1 = R2 14864 * copy register state to dest reg 14865 */ 14866 assign_scalar_id_before_mov(env, src_reg); 14867 *dst_reg = *src_reg; 14868 dst_reg->subreg_def = DEF_NOT_SUBREG; 14869 } else { 14870 /* case: R1 = (s8, s16 s32)R2 */ 14871 if (is_pointer_value(env, insn->src_reg)) { 14872 verbose(env, 14873 "R%d sign-extension part of pointer\n", 14874 insn->src_reg); 14875 return -EACCES; 14876 } else if (src_reg->type == SCALAR_VALUE) { 14877 bool no_sext; 14878 14879 no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 14880 if (no_sext) 14881 assign_scalar_id_before_mov(env, src_reg); 14882 *dst_reg = *src_reg; 14883 if (!no_sext) 14884 clear_scalar_id(dst_reg); 14885 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 14886 dst_reg->subreg_def = DEF_NOT_SUBREG; 14887 } else { 14888 mark_reg_unknown(env, regs, insn->dst_reg); 14889 } 14890 } 14891 } else { 14892 /* R1 = (u32) R2 */ 14893 if (is_pointer_value(env, insn->src_reg)) { 14894 verbose(env, 14895 "R%d partial copy of pointer\n", 14896 insn->src_reg); 14897 return -EACCES; 14898 } else if (src_reg->type == SCALAR_VALUE) { 14899 if (insn->off == 0) { 14900 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 14901 14902 if (is_src_reg_u32) 14903 assign_scalar_id_before_mov(env, src_reg); 14904 *dst_reg = *src_reg; 14905 /* Make sure ID is cleared if src_reg is not in u32 14906 * range otherwise dst_reg min/max could be incorrectly 14907 * propagated into src_reg by sync_linked_regs() 14908 */ 14909 if (!is_src_reg_u32) 14910 clear_scalar_id(dst_reg); 14911 dst_reg->subreg_def = env->insn_idx + 1; 14912 } else { 14913 /* case: W1 = (s8, s16)W2 */ 14914 bool no_sext = reg_umax(src_reg) < (1ULL << (insn->off - 1)); 14915 14916 if (no_sext) 14917 assign_scalar_id_before_mov(env, src_reg); 14918 *dst_reg = *src_reg; 14919 if (!no_sext) 14920 clear_scalar_id(dst_reg); 14921 dst_reg->subreg_def = env->insn_idx + 1; 14922 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 14923 } 14924 } else { 14925 mark_reg_unknown(env, regs, 14926 insn->dst_reg); 14927 } 14928 zext_32_to_64(dst_reg); 14929 reg_bounds_sync(dst_reg); 14930 } 14931 } else { 14932 /* case: R = imm 14933 * remember the value we stored into this reg 14934 */ 14935 /* clear any state __mark_reg_known doesn't set */ 14936 mark_reg_unknown(env, regs, insn->dst_reg); 14937 regs[insn->dst_reg].type = SCALAR_VALUE; 14938 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14939 __mark_reg_known(regs + insn->dst_reg, 14940 insn->imm); 14941 } else { 14942 __mark_reg_known(regs + insn->dst_reg, 14943 (u32)insn->imm); 14944 } 14945 } 14946 14947 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14948 14949 if (BPF_SRC(insn->code) == BPF_X) { 14950 /* check src1 operand */ 14951 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14952 if (err) 14953 return err; 14954 } 14955 14956 /* check src2 operand */ 14957 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14958 if (err) 14959 return err; 14960 14961 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14962 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14963 verbose(env, "div by zero\n"); 14964 return -EINVAL; 14965 } 14966 14967 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14968 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14969 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14970 14971 if (insn->imm < 0 || insn->imm >= size) { 14972 verbose(env, "invalid shift %d\n", insn->imm); 14973 return -EINVAL; 14974 } 14975 } 14976 14977 /* check dest operand */ 14978 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14979 err = err ?: adjust_reg_min_max_vals(env, insn); 14980 if (err) 14981 return err; 14982 } 14983 14984 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14985 } 14986 14987 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14988 struct bpf_reg_state *dst_reg, 14989 enum bpf_reg_type type, 14990 bool range_right_open) 14991 { 14992 struct bpf_func_state *state; 14993 struct bpf_reg_state *reg; 14994 int new_range; 14995 14996 if (reg_umax(dst_reg) == 0 && range_right_open) 14997 /* This doesn't give us any range */ 14998 return; 14999 15000 if (reg_umax(dst_reg) > MAX_PACKET_OFF) 15001 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15002 * than pkt_end, but that's because it's also less than pkt. 15003 */ 15004 return; 15005 15006 new_range = reg_umax(dst_reg); 15007 if (range_right_open) 15008 new_range++; 15009 15010 /* Examples for register markings: 15011 * 15012 * pkt_data in dst register: 15013 * 15014 * r2 = r3; 15015 * r2 += 8; 15016 * if (r2 > pkt_end) goto <handle exception> 15017 * <access okay> 15018 * 15019 * r2 = r3; 15020 * r2 += 8; 15021 * if (r2 < pkt_end) goto <access okay> 15022 * <handle exception> 15023 * 15024 * Where: 15025 * r2 == dst_reg, pkt_end == src_reg 15026 * r2=pkt(id=n,off=8,r=0) 15027 * r3=pkt(id=n,off=0,r=0) 15028 * 15029 * pkt_data in src register: 15030 * 15031 * r2 = r3; 15032 * r2 += 8; 15033 * if (pkt_end >= r2) goto <access okay> 15034 * <handle exception> 15035 * 15036 * r2 = r3; 15037 * r2 += 8; 15038 * if (pkt_end <= r2) goto <handle exception> 15039 * <access okay> 15040 * 15041 * Where: 15042 * pkt_end == dst_reg, r2 == src_reg 15043 * r2=pkt(id=n,off=8,r=0) 15044 * r3=pkt(id=n,off=0,r=0) 15045 * 15046 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15047 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15048 * and [r3, r3 + 8-1) respectively is safe to access depending on 15049 * the check. 15050 */ 15051 15052 /* If our ids match, then we must have the same max_value. And we 15053 * don't care about the other reg's fixed offset, since if it's too big 15054 * the range won't allow anything. 15055 * reg_umax(dst_reg) is known < MAX_PACKET_OFF, therefore it fits in a u16. 15056 */ 15057 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15058 if (reg->type == type && reg->id == dst_reg->id) 15059 /* keep the maximum range already checked */ 15060 reg->range = max(reg->range, new_range); 15061 })); 15062 } 15063 15064 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15065 u8 opcode, bool is_jmp32); 15066 static u8 rev_opcode(u8 opcode); 15067 15068 /* 15069 * Learn more information about live branches by simulating refinement on both branches. 15070 * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means 15071 * that branch is dead. 15072 */ 15073 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32) 15074 { 15075 /* Fallthrough (FALSE) branch */ 15076 regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32); 15077 reg_bounds_sync(&env->false_reg1); 15078 reg_bounds_sync(&env->false_reg2); 15079 /* 15080 * If there is a range bounds violation in *any* of the abstract values in either 15081 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only 15082 * TRUE branch will be taken. 15083 */ 15084 if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2)) 15085 return 1; 15086 15087 /* Jump (TRUE) branch */ 15088 regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32); 15089 reg_bounds_sync(&env->true_reg1); 15090 reg_bounds_sync(&env->true_reg2); 15091 /* 15092 * If there is a range bounds violation in *any* of the abstract values in either 15093 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead. 15094 * Only FALSE branch will be taken. 15095 */ 15096 if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2)) 15097 return 0; 15098 15099 /* Both branches are possible, we can't determine which one will be taken. */ 15100 return -1; 15101 } 15102 15103 /* 15104 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15105 */ 15106 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15107 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15108 { 15109 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15110 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15111 u64 umin1 = is_jmp32 ? (u64)reg_u32_min(reg1) : reg_umin(reg1); 15112 u64 umax1 = is_jmp32 ? (u64)reg_u32_max(reg1) : reg_umax(reg1); 15113 s64 smin1 = is_jmp32 ? (s64)reg_s32_min(reg1) : reg_smin(reg1); 15114 s64 smax1 = is_jmp32 ? (s64)reg_s32_max(reg1) : reg_smax(reg1); 15115 u64 umin2 = is_jmp32 ? (u64)reg_u32_min(reg2) : reg_umin(reg2); 15116 u64 umax2 = is_jmp32 ? (u64)reg_u32_max(reg2) : reg_umax(reg2); 15117 s64 smin2 = is_jmp32 ? (s64)reg_s32_min(reg2) : reg_smin(reg2); 15118 s64 smax2 = is_jmp32 ? (s64)reg_s32_max(reg2) : reg_smax(reg2); 15119 15120 if (reg1 == reg2) { 15121 switch (opcode) { 15122 case BPF_JGE: 15123 case BPF_JLE: 15124 case BPF_JSGE: 15125 case BPF_JSLE: 15126 case BPF_JEQ: 15127 return 1; 15128 case BPF_JGT: 15129 case BPF_JLT: 15130 case BPF_JSGT: 15131 case BPF_JSLT: 15132 case BPF_JNE: 15133 return 0; 15134 case BPF_JSET: 15135 if (tnum_is_const(t1)) 15136 return t1.value != 0; 15137 else 15138 return (smin1 <= 0 && smax1 >= 0) ? -1 : 1; 15139 default: 15140 return -1; 15141 } 15142 } 15143 15144 switch (opcode) { 15145 case BPF_JEQ: 15146 /* constants, umin/umax and smin/smax checks would be 15147 * redundant in this case because they all should match 15148 */ 15149 if (tnum_is_const(t1) && tnum_is_const(t2)) 15150 return t1.value == t2.value; 15151 if (!tnum_overlap(t1, t2)) 15152 return 0; 15153 /* non-overlapping ranges */ 15154 if (umin1 > umax2 || umax1 < umin2) 15155 return 0; 15156 if (smin1 > smax2 || smax1 < smin2) 15157 return 0; 15158 if (!is_jmp32) { 15159 /* if 64-bit ranges are inconclusive, see if we can 15160 * utilize 32-bit subrange knowledge to eliminate 15161 * branches that can't be taken a priori 15162 */ 15163 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15164 reg_u32_max(reg1) < reg_u32_min(reg2)) 15165 return 0; 15166 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15167 reg_s32_max(reg1) < reg_s32_min(reg2)) 15168 return 0; 15169 } 15170 break; 15171 case BPF_JNE: 15172 /* constants, umin/umax and smin/smax checks would be 15173 * redundant in this case because they all should match 15174 */ 15175 if (tnum_is_const(t1) && tnum_is_const(t2)) 15176 return t1.value != t2.value; 15177 if (!tnum_overlap(t1, t2)) 15178 return 1; 15179 /* non-overlapping ranges */ 15180 if (umin1 > umax2 || umax1 < umin2) 15181 return 1; 15182 if (smin1 > smax2 || smax1 < smin2) 15183 return 1; 15184 if (!is_jmp32) { 15185 /* if 64-bit ranges are inconclusive, see if we can 15186 * utilize 32-bit subrange knowledge to eliminate 15187 * branches that can't be taken a priori 15188 */ 15189 if (reg_u32_min(reg1) > reg_u32_max(reg2) || 15190 reg_u32_max(reg1) < reg_u32_min(reg2)) 15191 return 1; 15192 if (reg_s32_min(reg1) > reg_s32_max(reg2) || 15193 reg_s32_max(reg1) < reg_s32_min(reg2)) 15194 return 1; 15195 } 15196 break; 15197 case BPF_JSET: 15198 if (!is_reg_const(reg2, is_jmp32)) { 15199 swap(reg1, reg2); 15200 swap(t1, t2); 15201 } 15202 if (!is_reg_const(reg2, is_jmp32)) 15203 return -1; 15204 if ((~t1.mask & t1.value) & t2.value) 15205 return 1; 15206 if (!((t1.mask | t1.value) & t2.value)) 15207 return 0; 15208 break; 15209 case BPF_JGT: 15210 if (umin1 > umax2) 15211 return 1; 15212 else if (umax1 <= umin2) 15213 return 0; 15214 break; 15215 case BPF_JSGT: 15216 if (smin1 > smax2) 15217 return 1; 15218 else if (smax1 <= smin2) 15219 return 0; 15220 break; 15221 case BPF_JLT: 15222 if (umax1 < umin2) 15223 return 1; 15224 else if (umin1 >= umax2) 15225 return 0; 15226 break; 15227 case BPF_JSLT: 15228 if (smax1 < smin2) 15229 return 1; 15230 else if (smin1 >= smax2) 15231 return 0; 15232 break; 15233 case BPF_JGE: 15234 if (umin1 >= umax2) 15235 return 1; 15236 else if (umax1 < umin2) 15237 return 0; 15238 break; 15239 case BPF_JSGE: 15240 if (smin1 >= smax2) 15241 return 1; 15242 else if (smax1 < smin2) 15243 return 0; 15244 break; 15245 case BPF_JLE: 15246 if (umax1 <= umin2) 15247 return 1; 15248 else if (umin1 > umax2) 15249 return 0; 15250 break; 15251 case BPF_JSLE: 15252 if (smax1 <= smin2) 15253 return 1; 15254 else if (smin1 > smax2) 15255 return 0; 15256 break; 15257 } 15258 15259 return simulate_both_branches_taken(env, opcode, is_jmp32); 15260 } 15261 15262 static int flip_opcode(u32 opcode) 15263 { 15264 /* How can we transform "a <op> b" into "b <op> a"? */ 15265 static const u8 opcode_flip[16] = { 15266 /* these stay the same */ 15267 [BPF_JEQ >> 4] = BPF_JEQ, 15268 [BPF_JNE >> 4] = BPF_JNE, 15269 [BPF_JSET >> 4] = BPF_JSET, 15270 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 15271 [BPF_JGE >> 4] = BPF_JLE, 15272 [BPF_JGT >> 4] = BPF_JLT, 15273 [BPF_JLE >> 4] = BPF_JGE, 15274 [BPF_JLT >> 4] = BPF_JGT, 15275 [BPF_JSGE >> 4] = BPF_JSLE, 15276 [BPF_JSGT >> 4] = BPF_JSLT, 15277 [BPF_JSLE >> 4] = BPF_JSGE, 15278 [BPF_JSLT >> 4] = BPF_JSGT 15279 }; 15280 return opcode_flip[opcode >> 4]; 15281 } 15282 15283 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 15284 struct bpf_reg_state *src_reg, 15285 u8 opcode) 15286 { 15287 struct bpf_reg_state *pkt; 15288 15289 if (src_reg->type == PTR_TO_PACKET_END) { 15290 pkt = dst_reg; 15291 } else if (dst_reg->type == PTR_TO_PACKET_END) { 15292 pkt = src_reg; 15293 opcode = flip_opcode(opcode); 15294 } else { 15295 return -1; 15296 } 15297 15298 if (pkt->range >= 0) 15299 return -1; 15300 15301 switch (opcode) { 15302 case BPF_JLE: 15303 /* pkt <= pkt_end */ 15304 fallthrough; 15305 case BPF_JGT: 15306 /* pkt > pkt_end */ 15307 if (pkt->range == BEYOND_PKT_END) 15308 /* pkt has at last one extra byte beyond pkt_end */ 15309 return opcode == BPF_JGT; 15310 break; 15311 case BPF_JLT: 15312 /* pkt < pkt_end */ 15313 fallthrough; 15314 case BPF_JGE: 15315 /* pkt >= pkt_end */ 15316 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 15317 return opcode == BPF_JGE; 15318 break; 15319 } 15320 return -1; 15321 } 15322 15323 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 15324 * and return: 15325 * 1 - branch will be taken and "goto target" will be executed 15326 * 0 - branch will not be taken and fall-through to next insn 15327 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 15328 * range [0,10] 15329 */ 15330 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15331 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15332 { 15333 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 15334 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 15335 15336 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 15337 u64 val; 15338 15339 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 15340 if (!is_reg_const(reg2, is_jmp32)) { 15341 opcode = flip_opcode(opcode); 15342 swap(reg1, reg2); 15343 } 15344 /* and ensure that reg2 is a constant */ 15345 if (!is_reg_const(reg2, is_jmp32)) 15346 return -1; 15347 15348 if (!reg_not_null(env, reg1)) 15349 return -1; 15350 15351 /* If pointer is valid tests against zero will fail so we can 15352 * use this to direct branch taken. 15353 */ 15354 val = reg_const_value(reg2, is_jmp32); 15355 if (val != 0) 15356 return -1; 15357 15358 switch (opcode) { 15359 case BPF_JEQ: 15360 return 0; 15361 case BPF_JNE: 15362 return 1; 15363 default: 15364 return -1; 15365 } 15366 } 15367 15368 /* now deal with two scalars, but not necessarily constants */ 15369 return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32); 15370 } 15371 15372 /* Opcode that corresponds to a *false* branch condition. 15373 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 15374 */ 15375 static u8 rev_opcode(u8 opcode) 15376 { 15377 switch (opcode) { 15378 case BPF_JEQ: return BPF_JNE; 15379 case BPF_JNE: return BPF_JEQ; 15380 /* JSET doesn't have it's reverse opcode in BPF, so add 15381 * BPF_X flag to denote the reverse of that operation 15382 */ 15383 case BPF_JSET: return BPF_JSET | BPF_X; 15384 case BPF_JSET | BPF_X: return BPF_JSET; 15385 case BPF_JGE: return BPF_JLT; 15386 case BPF_JGT: return BPF_JLE; 15387 case BPF_JLE: return BPF_JGT; 15388 case BPF_JLT: return BPF_JGE; 15389 case BPF_JSGE: return BPF_JSLT; 15390 case BPF_JSGT: return BPF_JSLE; 15391 case BPF_JSLE: return BPF_JSGT; 15392 case BPF_JSLT: return BPF_JSGE; 15393 default: return 0; 15394 } 15395 } 15396 15397 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 15398 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15399 u8 opcode, bool is_jmp32) 15400 { 15401 struct tnum t; 15402 u64 val; 15403 15404 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 15405 switch (opcode) { 15406 case BPF_JGE: 15407 case BPF_JGT: 15408 case BPF_JSGE: 15409 case BPF_JSGT: 15410 opcode = flip_opcode(opcode); 15411 swap(reg1, reg2); 15412 break; 15413 default: 15414 break; 15415 } 15416 15417 switch (opcode) { 15418 case BPF_JEQ: 15419 if (is_jmp32) { 15420 reg1->r32 = cnum32_intersect(reg1->r32, reg2->r32); 15421 reg2->r32 = reg1->r32; 15422 15423 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 15424 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15425 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 15426 } else { 15427 reg1->r64 = cnum64_intersect(reg1->r64, reg2->r64); 15428 reg2->r64 = reg1->r64; 15429 15430 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 15431 reg2->var_off = reg1->var_off; 15432 } 15433 break; 15434 case BPF_JNE: 15435 if (!is_reg_const(reg2, is_jmp32)) 15436 swap(reg1, reg2); 15437 if (!is_reg_const(reg2, is_jmp32)) 15438 break; 15439 15440 /* try to recompute the bound of reg1 if reg2 is a const and 15441 * is exactly the edge of reg1. 15442 */ 15443 val = reg_const_value(reg2, is_jmp32); 15444 if (is_jmp32) { 15445 /* Complement of the range [val, val] as cnum32. */ 15446 cnum32_intersect_with(®1->r32, (struct cnum32){ val + 1, U32_MAX - 1 }); 15447 } else { 15448 /* Complement of the range [val, val] as cnum64. */ 15449 cnum64_intersect_with(®1->r64, (struct cnum64){ val + 1, U64_MAX - 1 }); 15450 } 15451 break; 15452 case BPF_JSET: 15453 if (!is_reg_const(reg2, is_jmp32)) 15454 swap(reg1, reg2); 15455 if (!is_reg_const(reg2, is_jmp32)) 15456 break; 15457 val = reg_const_value(reg2, is_jmp32); 15458 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 15459 * requires single bit to learn something useful. E.g., if we 15460 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 15461 * are actually set? We can learn something definite only if 15462 * it's a single-bit value to begin with. 15463 * 15464 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 15465 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 15466 * bit 1 is set, which we can readily use in adjustments. 15467 */ 15468 if (!is_power_of_2(val)) 15469 break; 15470 if (is_jmp32) { 15471 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 15472 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15473 } else { 15474 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 15475 } 15476 break; 15477 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 15478 if (!is_reg_const(reg2, is_jmp32)) 15479 swap(reg1, reg2); 15480 if (!is_reg_const(reg2, is_jmp32)) 15481 break; 15482 val = reg_const_value(reg2, is_jmp32); 15483 /* Forget the ranges before narrowing tnums, to avoid invariant 15484 * violations if we're on a dead branch. 15485 */ 15486 __mark_reg_unbounded(reg1); 15487 if (is_jmp32) { 15488 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 15489 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15490 } else { 15491 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15492 } 15493 break; 15494 case BPF_JLE: 15495 if (is_jmp32) { 15496 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2)); 15497 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1), U32_MAX); 15498 } else { 15499 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2)); 15500 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1), U64_MAX); 15501 } 15502 break; 15503 case BPF_JLT: 15504 if (is_jmp32) { 15505 cnum32_intersect_with_urange(®1->r32, 0, reg_u32_max(reg2) - 1); 15506 cnum32_intersect_with_urange(®2->r32, reg_u32_min(reg1) + 1, U32_MAX); 15507 } else { 15508 cnum64_intersect_with_urange(®1->r64, 0, reg_umax(reg2) - 1); 15509 cnum64_intersect_with_urange(®2->r64, reg_umin(reg1) + 1, U64_MAX); 15510 } 15511 break; 15512 case BPF_JSLE: 15513 if (is_jmp32) { 15514 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2)); 15515 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1), S32_MAX); 15516 } else { 15517 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2)); 15518 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1), S64_MAX); 15519 } 15520 break; 15521 case BPF_JSLT: 15522 if (is_jmp32) { 15523 cnum32_intersect_with_srange(®1->r32, S32_MIN, reg_s32_max(reg2) - 1); 15524 cnum32_intersect_with_srange(®2->r32, reg_s32_min(reg1) + 1, S32_MAX); 15525 } else { 15526 cnum64_intersect_with_srange(®1->r64, S64_MIN, reg_smax(reg2) - 1); 15527 cnum64_intersect_with_srange(®2->r64, reg_smin(reg1) + 1, S64_MAX); 15528 } 15529 break; 15530 default: 15531 return; 15532 } 15533 } 15534 15535 /* Check for invariant violations on the registers for both branches of a condition */ 15536 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env) 15537 { 15538 int err; 15539 15540 err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1"); 15541 err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2"); 15542 err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1"); 15543 err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2"); 15544 return err; 15545 } 15546 15547 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 15548 struct bpf_reg_state *reg, u32 id, 15549 bool is_null) 15550 { 15551 if (type_may_be_null(reg->type) && reg->id == id && 15552 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 15553 /* Old offset should have been known-zero, because we don't 15554 * allow pointer arithmetic on pointers that might be NULL. 15555 * If we see this happening, don't convert the register. 15556 * 15557 * But in some cases, some helpers that return local kptrs 15558 * advance offset for the returned pointer. In those cases, 15559 * it is fine to expect to see reg->var_off. 15560 */ 15561 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 15562 WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0))) 15563 return; 15564 if (is_null) { 15565 /* We don't need id from this point 15566 * onwards anymore, thus we should better reset it, 15567 * so that state pruning has chances to take effect. 15568 */ 15569 __mark_reg_known_zero(reg); 15570 reg->type = SCALAR_VALUE; 15571 15572 return; 15573 } 15574 15575 mark_ptr_not_null_reg(reg); 15576 15577 /* 15578 * reg->id is preserved for object relationship tracking 15579 * and spin_lock lock state tracking 15580 */ 15581 } 15582 } 15583 15584 /* The logic is similar to find_good_pkt_pointers(), both could eventually 15585 * be folded together at some point. 15586 */ 15587 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 15588 bool is_null) 15589 { 15590 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15591 struct bpf_reg_state *regs = state->regs, *reg; 15592 u32 id = regs[regno].id; 15593 15594 if (is_null && find_reference_state(vstate, id)) 15595 /* regs[regno] is in the " == NULL" branch. 15596 * No one could have freed the reference state before 15597 * doing the NULL check. 15598 */ 15599 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 15600 15601 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15602 mark_ptr_or_null_reg(state, reg, id, is_null); 15603 })); 15604 } 15605 15606 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 15607 struct bpf_reg_state *dst_reg, 15608 struct bpf_reg_state *src_reg, 15609 struct bpf_verifier_state *this_branch, 15610 struct bpf_verifier_state *other_branch) 15611 { 15612 if (BPF_SRC(insn->code) != BPF_X) 15613 return false; 15614 15615 /* Pointers are always 64-bit. */ 15616 if (BPF_CLASS(insn->code) == BPF_JMP32) 15617 return false; 15618 15619 switch (BPF_OP(insn->code)) { 15620 case BPF_JGT: 15621 if ((dst_reg->type == PTR_TO_PACKET && 15622 src_reg->type == PTR_TO_PACKET_END) || 15623 (dst_reg->type == PTR_TO_PACKET_META && 15624 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15625 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 15626 find_good_pkt_pointers(this_branch, dst_reg, 15627 dst_reg->type, false); 15628 mark_pkt_end(other_branch, insn->dst_reg, true); 15629 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15630 src_reg->type == PTR_TO_PACKET) || 15631 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15632 src_reg->type == PTR_TO_PACKET_META)) { 15633 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 15634 find_good_pkt_pointers(other_branch, src_reg, 15635 src_reg->type, true); 15636 mark_pkt_end(this_branch, insn->src_reg, false); 15637 } else { 15638 return false; 15639 } 15640 break; 15641 case BPF_JLT: 15642 if ((dst_reg->type == PTR_TO_PACKET && 15643 src_reg->type == PTR_TO_PACKET_END) || 15644 (dst_reg->type == PTR_TO_PACKET_META && 15645 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15646 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 15647 find_good_pkt_pointers(other_branch, dst_reg, 15648 dst_reg->type, true); 15649 mark_pkt_end(this_branch, insn->dst_reg, false); 15650 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15651 src_reg->type == PTR_TO_PACKET) || 15652 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15653 src_reg->type == PTR_TO_PACKET_META)) { 15654 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 15655 find_good_pkt_pointers(this_branch, src_reg, 15656 src_reg->type, false); 15657 mark_pkt_end(other_branch, insn->src_reg, true); 15658 } else { 15659 return false; 15660 } 15661 break; 15662 case BPF_JGE: 15663 if ((dst_reg->type == PTR_TO_PACKET && 15664 src_reg->type == PTR_TO_PACKET_END) || 15665 (dst_reg->type == PTR_TO_PACKET_META && 15666 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15667 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 15668 find_good_pkt_pointers(this_branch, dst_reg, 15669 dst_reg->type, true); 15670 mark_pkt_end(other_branch, insn->dst_reg, false); 15671 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15672 src_reg->type == PTR_TO_PACKET) || 15673 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15674 src_reg->type == PTR_TO_PACKET_META)) { 15675 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 15676 find_good_pkt_pointers(other_branch, src_reg, 15677 src_reg->type, false); 15678 mark_pkt_end(this_branch, insn->src_reg, true); 15679 } else { 15680 return false; 15681 } 15682 break; 15683 case BPF_JLE: 15684 if ((dst_reg->type == PTR_TO_PACKET && 15685 src_reg->type == PTR_TO_PACKET_END) || 15686 (dst_reg->type == PTR_TO_PACKET_META && 15687 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 15688 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 15689 find_good_pkt_pointers(other_branch, dst_reg, 15690 dst_reg->type, false); 15691 mark_pkt_end(this_branch, insn->dst_reg, true); 15692 } else if ((dst_reg->type == PTR_TO_PACKET_END && 15693 src_reg->type == PTR_TO_PACKET) || 15694 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 15695 src_reg->type == PTR_TO_PACKET_META)) { 15696 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 15697 find_good_pkt_pointers(this_branch, src_reg, 15698 src_reg->type, true); 15699 mark_pkt_end(other_branch, insn->src_reg, false); 15700 } else { 15701 return false; 15702 } 15703 break; 15704 default: 15705 return false; 15706 } 15707 15708 return true; 15709 } 15710 15711 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 15712 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 15713 { 15714 struct linked_reg *e; 15715 15716 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 15717 return; 15718 15719 e = linked_regs_push(reg_set); 15720 if (e) { 15721 e->frameno = frameno; 15722 e->is_reg = is_reg; 15723 e->regno = spi_or_reg; 15724 } else { 15725 clear_scalar_id(reg); 15726 } 15727 } 15728 15729 /* For all R being scalar registers or spilled scalar registers 15730 * in verifier state, save R in linked_regs if R->id == id. 15731 * If there are too many Rs sharing same id, reset id for leftover Rs. 15732 */ 15733 static void collect_linked_regs(struct bpf_verifier_env *env, 15734 struct bpf_verifier_state *vstate, 15735 u32 id, 15736 struct linked_regs *linked_regs) 15737 { 15738 struct bpf_insn_aux_data *aux = env->insn_aux_data; 15739 struct bpf_func_state *func; 15740 struct bpf_reg_state *reg; 15741 u16 live_regs; 15742 int i, j; 15743 15744 id = id & ~BPF_ADD_CONST; 15745 for (i = vstate->curframe; i >= 0; i--) { 15746 live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before; 15747 func = vstate->frame[i]; 15748 for (j = 0; j < BPF_REG_FP; j++) { 15749 if (!(live_regs & BIT(j))) 15750 continue; 15751 reg = &func->regs[j]; 15752 __collect_linked_regs(linked_regs, reg, id, i, j, true); 15753 } 15754 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 15755 if (!bpf_is_spilled_reg(&func->stack[j])) 15756 continue; 15757 reg = &func->stack[j].spilled_ptr; 15758 __collect_linked_regs(linked_regs, reg, id, i, j, false); 15759 } 15760 } 15761 } 15762 15763 /* For all R in linked_regs, copy known_reg range into R 15764 * if R->id == known_reg->id. 15765 */ 15766 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate, 15767 struct bpf_reg_state *known_reg, struct linked_regs *linked_regs) 15768 { 15769 struct bpf_reg_state fake_reg; 15770 struct bpf_reg_state *reg; 15771 struct linked_reg *e; 15772 int i; 15773 15774 for (i = 0; i < linked_regs->cnt; ++i) { 15775 e = &linked_regs->entries[i]; 15776 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 15777 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 15778 if (reg->type != SCALAR_VALUE || reg == known_reg) 15779 continue; 15780 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 15781 continue; 15782 /* 15783 * Skip mixed 32/64-bit links: the delta relationship doesn't 15784 * hold across different ALU widths. 15785 */ 15786 if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST) 15787 continue; 15788 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 15789 reg->delta == known_reg->delta) { 15790 s32 saved_subreg_def = reg->subreg_def; 15791 15792 *reg = *known_reg; 15793 reg->subreg_def = saved_subreg_def; 15794 } else { 15795 s32 saved_subreg_def = reg->subreg_def; 15796 s32 saved_off = reg->delta; 15797 u32 saved_id = reg->id; 15798 15799 fake_reg.type = SCALAR_VALUE; 15800 __mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta); 15801 15802 /* reg = known_reg; reg += delta */ 15803 *reg = *known_reg; 15804 /* 15805 * Must preserve off, id and subreg_def flag, 15806 * otherwise another sync_linked_regs() will be incorrect. 15807 */ 15808 reg->delta = saved_off; 15809 reg->id = saved_id; 15810 reg->subreg_def = saved_subreg_def; 15811 15812 scalar32_min_max_add(reg, &fake_reg); 15813 scalar_min_max_add(reg, &fake_reg); 15814 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 15815 if ((reg->id | known_reg->id) & BPF_ADD_CONST32) 15816 zext_32_to_64(reg); 15817 reg_bounds_sync(reg); 15818 } 15819 if (e->is_reg) 15820 mark_reg_scratched(env, e->regno); 15821 else 15822 mark_stack_slot_scratched(env, e->spi); 15823 } 15824 } 15825 15826 static int check_cond_jmp_op(struct bpf_verifier_env *env, 15827 struct bpf_insn *insn, int *insn_idx) 15828 { 15829 struct bpf_verifier_state *this_branch = env->cur_state; 15830 struct bpf_verifier_state *other_branch; 15831 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 15832 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 15833 struct bpf_reg_state *eq_branch_regs; 15834 struct linked_regs linked_regs = {}; 15835 u8 opcode = BPF_OP(insn->code); 15836 int insn_flags = 0; 15837 bool is_jmp32; 15838 int pred = -1; 15839 int err; 15840 15841 /* Only conditional jumps are expected to reach here. */ 15842 if (opcode == BPF_JA || opcode > BPF_JCOND) { 15843 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 15844 return -EINVAL; 15845 } 15846 15847 if (opcode == BPF_JCOND) { 15848 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 15849 int idx = *insn_idx; 15850 15851 prev_st = find_prev_entry(env, cur_st->parent, idx); 15852 15853 /* branch out 'fallthrough' insn as a new state to explore */ 15854 queued_st = push_stack(env, idx + 1, idx, false); 15855 if (IS_ERR(queued_st)) 15856 return PTR_ERR(queued_st); 15857 15858 queued_st->may_goto_depth++; 15859 if (prev_st) 15860 widen_imprecise_scalars(env, prev_st, queued_st); 15861 *insn_idx += insn->off; 15862 return 0; 15863 } 15864 15865 /* check src2 operand */ 15866 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15867 if (err) 15868 return err; 15869 15870 dst_reg = ®s[insn->dst_reg]; 15871 if (BPF_SRC(insn->code) == BPF_X) { 15872 /* check src1 operand */ 15873 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15874 if (err) 15875 return err; 15876 15877 src_reg = ®s[insn->src_reg]; 15878 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15879 is_pointer_value(env, insn->src_reg)) { 15880 verbose(env, "R%d pointer comparison prohibited\n", 15881 insn->src_reg); 15882 return -EACCES; 15883 } 15884 15885 if (src_reg->type == PTR_TO_STACK) 15886 insn_flags |= INSN_F_SRC_REG_STACK; 15887 if (dst_reg->type == PTR_TO_STACK) 15888 insn_flags |= INSN_F_DST_REG_STACK; 15889 } else { 15890 src_reg = &env->fake_reg[0]; 15891 memset(src_reg, 0, sizeof(*src_reg)); 15892 src_reg->type = SCALAR_VALUE; 15893 __mark_reg_known(src_reg, insn->imm); 15894 15895 if (dst_reg->type == PTR_TO_STACK) 15896 insn_flags |= INSN_F_DST_REG_STACK; 15897 } 15898 15899 if (insn_flags) { 15900 err = bpf_push_jmp_history(env, this_branch, insn_flags, 0, 0, 0); 15901 if (err) 15902 return err; 15903 } 15904 15905 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 15906 env->false_reg1 = *dst_reg; 15907 env->false_reg2 = *src_reg; 15908 env->true_reg1 = *dst_reg; 15909 env->true_reg2 = *src_reg; 15910 pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32); 15911 if (pred >= 0) { 15912 /* If we get here with a dst_reg pointer type it is because 15913 * above is_branch_taken() special cased the 0 comparison. 15914 */ 15915 if (!__is_pointer_value(false, dst_reg)) 15916 err = mark_chain_precision(env, insn->dst_reg); 15917 if (BPF_SRC(insn->code) == BPF_X && !err && 15918 !__is_pointer_value(false, src_reg)) 15919 err = mark_chain_precision(env, insn->src_reg); 15920 if (err) 15921 return err; 15922 } 15923 15924 if (pred == 1) { 15925 /* Only follow the goto, ignore fall-through. If needed, push 15926 * the fall-through branch for simulation under speculative 15927 * execution. 15928 */ 15929 if (!env->bypass_spec_v1) { 15930 err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx); 15931 if (err < 0) 15932 return err; 15933 } 15934 if (env->log.level & BPF_LOG_LEVEL) 15935 print_insn_state(env, this_branch, this_branch->curframe); 15936 *insn_idx += insn->off; 15937 return 0; 15938 } else if (pred == 0) { 15939 /* Only follow the fall-through branch, since that's where the 15940 * program will go. If needed, push the goto branch for 15941 * simulation under speculative execution. 15942 */ 15943 if (!env->bypass_spec_v1) { 15944 err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1, 15945 *insn_idx); 15946 if (err < 0) 15947 return err; 15948 } 15949 if (env->log.level & BPF_LOG_LEVEL) 15950 print_insn_state(env, this_branch, this_branch->curframe); 15951 return 0; 15952 } 15953 15954 /* Push scalar registers sharing same ID to jump history, 15955 * do this before creating 'other_branch', so that both 15956 * 'this_branch' and 'other_branch' share this history 15957 * if parent state is created. 15958 */ 15959 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 15960 collect_linked_regs(env, this_branch, src_reg->id, &linked_regs); 15961 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 15962 collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs); 15963 if (linked_regs.cnt > 1) { 15964 err = bpf_push_jmp_history(env, this_branch, 0, 0, 0, linked_regs_pack(&linked_regs)); 15965 if (err) 15966 return err; 15967 } 15968 15969 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); 15970 if (IS_ERR(other_branch)) 15971 return PTR_ERR(other_branch); 15972 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 15973 15974 err = regs_bounds_sanity_check_branches(env); 15975 if (err) 15976 return err; 15977 15978 *dst_reg = env->false_reg1; 15979 *src_reg = env->false_reg2; 15980 other_branch_regs[insn->dst_reg] = env->true_reg1; 15981 if (BPF_SRC(insn->code) == BPF_X) 15982 other_branch_regs[insn->src_reg] = env->true_reg2; 15983 15984 if (BPF_SRC(insn->code) == BPF_X && 15985 src_reg->type == SCALAR_VALUE && src_reg->id && 15986 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 15987 sync_linked_regs(env, this_branch, src_reg, &linked_regs); 15988 sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg], 15989 &linked_regs); 15990 } 15991 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 15992 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 15993 sync_linked_regs(env, this_branch, dst_reg, &linked_regs); 15994 sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg], 15995 &linked_regs); 15996 } 15997 15998 /* if one pointer register is compared to another pointer 15999 * register check if PTR_MAYBE_NULL could be lifted. 16000 * E.g. register A - maybe null 16001 * register B - not null 16002 * for JNE A, B, ... - A is not null in the false branch; 16003 * for JEQ A, B, ... - A is not null in the true branch. 16004 * 16005 * Since PTR_TO_BTF_ID points to a kernel struct that does 16006 * not need to be null checked by the BPF program, i.e., 16007 * could be null even without PTR_MAYBE_NULL marking, so 16008 * only propagate nullness when neither reg is that type. 16009 */ 16010 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16011 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16012 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16013 base_type(src_reg->type) != PTR_TO_BTF_ID && 16014 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16015 eq_branch_regs = NULL; 16016 switch (opcode) { 16017 case BPF_JEQ: 16018 eq_branch_regs = other_branch_regs; 16019 break; 16020 case BPF_JNE: 16021 eq_branch_regs = regs; 16022 break; 16023 default: 16024 /* do nothing */ 16025 break; 16026 } 16027 if (eq_branch_regs) { 16028 if (type_may_be_null(src_reg->type)) 16029 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16030 else 16031 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16032 } 16033 } 16034 16035 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16036 * Also does the same detection for a register whose the value is 16037 * known to be 0. 16038 * NOTE: these optimizations below are related with pointer comparison 16039 * which will never be JMP32. 16040 */ 16041 if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16042 type_may_be_null(dst_reg->type) && 16043 ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) || 16044 (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) { 16045 /* Mark all identical registers in each branch as either 16046 * safe or unknown depending R == 0 or R != 0 conditional. 16047 */ 16048 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16049 opcode == BPF_JNE); 16050 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16051 opcode == BPF_JEQ); 16052 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16053 this_branch, other_branch) && 16054 is_pointer_value(env, insn->dst_reg)) { 16055 verbose(env, "R%d pointer comparison prohibited\n", 16056 insn->dst_reg); 16057 return -EACCES; 16058 } 16059 if (env->log.level & BPF_LOG_LEVEL) 16060 print_insn_state(env, this_branch, this_branch->curframe); 16061 return 0; 16062 } 16063 16064 /* verify BPF_LD_IMM64 instruction */ 16065 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16066 { 16067 struct bpf_insn_aux_data *aux = cur_aux(env); 16068 struct bpf_reg_state *regs = cur_regs(env); 16069 struct bpf_reg_state *dst_reg; 16070 struct bpf_map *map; 16071 int err; 16072 16073 if (BPF_SIZE(insn->code) != BPF_DW) { 16074 verbose(env, "invalid BPF_LD_IMM insn\n"); 16075 return -EINVAL; 16076 } 16077 16078 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16079 if (err) 16080 return err; 16081 16082 dst_reg = ®s[insn->dst_reg]; 16083 if (insn->src_reg == 0) { 16084 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16085 16086 dst_reg->type = SCALAR_VALUE; 16087 __mark_reg_known(®s[insn->dst_reg], imm); 16088 return 0; 16089 } 16090 16091 /* All special src_reg cases are listed below. From this point onwards 16092 * we either succeed and assign a corresponding dst_reg->type after 16093 * zeroing the offset, or fail and reject the program. 16094 */ 16095 mark_reg_known_zero(env, regs, insn->dst_reg); 16096 16097 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16098 dst_reg->type = aux->btf_var.reg_type; 16099 switch (base_type(dst_reg->type)) { 16100 case PTR_TO_MEM: 16101 dst_reg->mem_size = aux->btf_var.mem_size; 16102 break; 16103 case PTR_TO_BTF_ID: 16104 dst_reg->btf = aux->btf_var.btf; 16105 dst_reg->btf_id = aux->btf_var.btf_id; 16106 break; 16107 default: 16108 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 16109 return -EFAULT; 16110 } 16111 return 0; 16112 } 16113 16114 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16115 struct bpf_prog_aux *aux = env->prog->aux; 16116 u32 subprogno = bpf_find_subprog(env, 16117 env->insn_idx + insn->imm + 1); 16118 16119 if (!aux->func_info) { 16120 verbose(env, "missing btf func_info\n"); 16121 return -EINVAL; 16122 } 16123 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16124 verbose(env, "callback function not static\n"); 16125 return -EINVAL; 16126 } 16127 16128 dst_reg->type = PTR_TO_FUNC; 16129 dst_reg->subprogno = subprogno; 16130 return 0; 16131 } 16132 16133 map = env->used_maps[aux->map_index]; 16134 16135 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16136 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16137 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16138 __mark_reg_unknown(env, dst_reg); 16139 dst_reg->map_ptr = map; 16140 return 0; 16141 } 16142 __mark_reg_known(dst_reg, aux->map_off); 16143 dst_reg->type = PTR_TO_MAP_VALUE; 16144 dst_reg->map_ptr = map; 16145 WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY && 16146 map->max_entries != 1); 16147 /* We want reg->id to be same (0) as map_value is not distinct */ 16148 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16149 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16150 dst_reg->type = CONST_PTR_TO_MAP; 16151 dst_reg->map_ptr = map; 16152 } else { 16153 verifier_bug(env, "unexpected src reg value for ldimm64"); 16154 return -EFAULT; 16155 } 16156 16157 return 0; 16158 } 16159 16160 static bool may_access_skb(enum bpf_prog_type type) 16161 { 16162 switch (type) { 16163 case BPF_PROG_TYPE_SOCKET_FILTER: 16164 case BPF_PROG_TYPE_SCHED_CLS: 16165 case BPF_PROG_TYPE_SCHED_ACT: 16166 return true; 16167 default: 16168 return false; 16169 } 16170 } 16171 16172 /* verify safety of LD_ABS|LD_IND instructions: 16173 * - they can only appear in the programs where ctx == skb 16174 * - since they are wrappers of function calls, they scratch R1-R5 registers, 16175 * preserve R6-R9, and store return value into R0 16176 * 16177 * Implicit input: 16178 * ctx == skb == R6 == CTX 16179 * 16180 * Explicit input: 16181 * SRC == any register 16182 * IMM == 32-bit immediate 16183 * 16184 * Output: 16185 * R0 - 8/16/32-bit skb data converted to cpu endianness 16186 */ 16187 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 16188 { 16189 struct bpf_reg_state *regs = cur_regs(env); 16190 static const int ctx_reg = BPF_REG_6; 16191 u8 mode = BPF_MODE(insn->code); 16192 int i, err; 16193 16194 if (!may_access_skb(resolve_prog_type(env->prog))) { 16195 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 16196 return -EINVAL; 16197 } 16198 16199 if (!env->ops->gen_ld_abs) { 16200 verifier_bug(env, "gen_ld_abs is null"); 16201 return -EFAULT; 16202 } 16203 16204 /* check whether implicit source operand (register R6) is readable */ 16205 err = check_reg_arg(env, ctx_reg, SRC_OP); 16206 if (err) 16207 return err; 16208 16209 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 16210 * gen_ld_abs() may terminate the program at runtime, leading to 16211 * reference leak. 16212 */ 16213 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 16214 if (err) 16215 return err; 16216 16217 if (regs[ctx_reg].type != PTR_TO_CTX) { 16218 verbose(env, 16219 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 16220 return -EINVAL; 16221 } 16222 16223 if (mode == BPF_IND) { 16224 /* check explicit source operand */ 16225 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16226 if (err) 16227 return err; 16228 } 16229 16230 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 16231 if (err < 0) 16232 return err; 16233 16234 /* reset caller saved regs to unreadable */ 16235 for (i = 0; i < CALLER_SAVED_REGS; i++) { 16236 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 16237 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 16238 } 16239 16240 /* mark destination R0 register as readable, since it contains 16241 * the value fetched from the packet. 16242 * Already marked as written above. 16243 */ 16244 mark_reg_unknown(env, regs, BPF_REG_0); 16245 /* ld_abs load up to 32-bit skb data. */ 16246 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 16247 /* 16248 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0 16249 * which must be explored by the verifier when in a subprog. 16250 */ 16251 if (env->cur_state->curframe) { 16252 struct bpf_verifier_state *branch; 16253 16254 mark_reg_scratched(env, BPF_REG_0); 16255 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 16256 if (IS_ERR(branch)) 16257 return PTR_ERR(branch); 16258 mark_reg_known_zero(env, regs, BPF_REG_0); 16259 err = prepare_func_exit(env, &env->insn_idx); 16260 if (err) 16261 return err; 16262 env->insn_idx--; 16263 } 16264 return 0; 16265 } 16266 16267 16268 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range) 16269 { 16270 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16271 16272 /* Default return value range. */ 16273 *range = retval_range(0, 1); 16274 16275 switch (prog_type) { 16276 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 16277 switch (env->prog->expected_attach_type) { 16278 case BPF_CGROUP_UDP4_RECVMSG: 16279 case BPF_CGROUP_UDP6_RECVMSG: 16280 case BPF_CGROUP_UNIX_RECVMSG: 16281 case BPF_CGROUP_INET4_GETPEERNAME: 16282 case BPF_CGROUP_INET6_GETPEERNAME: 16283 case BPF_CGROUP_UNIX_GETPEERNAME: 16284 case BPF_CGROUP_INET4_GETSOCKNAME: 16285 case BPF_CGROUP_INET6_GETSOCKNAME: 16286 case BPF_CGROUP_UNIX_GETSOCKNAME: 16287 *range = retval_range(1, 1); 16288 break; 16289 case BPF_CGROUP_INET4_BIND: 16290 case BPF_CGROUP_INET6_BIND: 16291 *range = retval_range(0, 3); 16292 break; 16293 default: 16294 break; 16295 } 16296 break; 16297 case BPF_PROG_TYPE_CGROUP_SKB: 16298 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) 16299 *range = retval_range(0, 3); 16300 break; 16301 case BPF_PROG_TYPE_CGROUP_SOCK: 16302 case BPF_PROG_TYPE_SOCK_OPS: 16303 case BPF_PROG_TYPE_CGROUP_DEVICE: 16304 case BPF_PROG_TYPE_CGROUP_SYSCTL: 16305 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 16306 break; 16307 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16308 if (!env->prog->aux->attach_btf_id) 16309 return false; 16310 *range = retval_range(0, 0); 16311 break; 16312 case BPF_PROG_TYPE_TRACING: 16313 switch (env->prog->expected_attach_type) { 16314 case BPF_TRACE_FENTRY: 16315 case BPF_TRACE_FEXIT: 16316 case BPF_TRACE_FSESSION: 16317 *range = retval_range(0, 0); 16318 break; 16319 case BPF_TRACE_RAW_TP: 16320 case BPF_MODIFY_RETURN: 16321 return false; 16322 case BPF_TRACE_ITER: 16323 default: 16324 break; 16325 } 16326 break; 16327 case BPF_PROG_TYPE_KPROBE: 16328 switch (env->prog->expected_attach_type) { 16329 case BPF_TRACE_KPROBE_SESSION: 16330 case BPF_TRACE_UPROBE_SESSION: 16331 break; 16332 default: 16333 return false; 16334 } 16335 break; 16336 case BPF_PROG_TYPE_SK_LOOKUP: 16337 *range = retval_range(SK_DROP, SK_PASS); 16338 break; 16339 16340 case BPF_PROG_TYPE_LSM: 16341 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 16342 /* no range found, any return value is allowed */ 16343 if (!get_func_retval_range(env->prog, range)) 16344 return false; 16345 /* no restricted range, any return value is allowed */ 16346 if (range->minval == S32_MIN && range->maxval == S32_MAX) 16347 return false; 16348 range->return_32bit = true; 16349 } else if (!env->prog->aux->attach_func_proto->type) { 16350 /* Make sure programs that attach to void 16351 * hooks don't try to modify return value. 16352 */ 16353 *range = retval_range(1, 1); 16354 } 16355 break; 16356 16357 case BPF_PROG_TYPE_NETFILTER: 16358 *range = retval_range(NF_DROP, NF_ACCEPT); 16359 break; 16360 case BPF_PROG_TYPE_STRUCT_OPS: 16361 *range = retval_range(0, 0); 16362 break; 16363 case BPF_PROG_TYPE_EXT: 16364 /* freplace program can return anything as its return value 16365 * depends on the to-be-replaced kernel func or bpf program. 16366 */ 16367 default: 16368 return false; 16369 } 16370 16371 /* Continue calculating. */ 16372 16373 return true; 16374 } 16375 16376 static bool program_returns_void(struct bpf_verifier_env *env) 16377 { 16378 const struct bpf_prog *prog = env->prog; 16379 enum bpf_prog_type prog_type = prog->type; 16380 16381 switch (prog_type) { 16382 case BPF_PROG_TYPE_LSM: 16383 /* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */ 16384 if (prog->expected_attach_type != BPF_LSM_CGROUP && 16385 !prog->aux->attach_func_proto->type) 16386 return true; 16387 break; 16388 case BPF_PROG_TYPE_STRUCT_OPS: 16389 if (!prog->aux->attach_func_proto->type) 16390 return true; 16391 break; 16392 case BPF_PROG_TYPE_EXT: 16393 /* 16394 * If the actual program is an extension, let it 16395 * return void - attaching will succeed only if the 16396 * program being replaced also returns void, and since 16397 * it has passed verification its actual type doesn't matter. 16398 */ 16399 if (subprog_returns_void(env, 0)) 16400 return true; 16401 break; 16402 default: 16403 break; 16404 } 16405 return false; 16406 } 16407 16408 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 16409 { 16410 const char *exit_ctx = "At program exit"; 16411 struct tnum enforce_attach_type_range = tnum_unknown; 16412 const struct bpf_prog *prog = env->prog; 16413 struct bpf_reg_state *reg = reg_state(env, regno); 16414 struct bpf_retval_range range = retval_range(0, 1); 16415 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16416 struct bpf_func_state *frame = env->cur_state->frame[0]; 16417 const struct btf_type *reg_type, *ret_type = NULL; 16418 int err; 16419 16420 /* LSM and struct_ops func-ptr's return type could be "void" */ 16421 if (!frame->in_async_callback_fn && program_returns_void(env)) 16422 return 0; 16423 16424 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) { 16425 /* Allow a struct_ops program to return a referenced kptr if it 16426 * matches the operator's return type and is in its unmodified 16427 * form. A scalar zero (i.e., a null pointer) is also allowed. 16428 */ 16429 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 16430 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 16431 prog->aux->attach_func_proto->type, 16432 NULL); 16433 if (ret_type && ret_type == reg_type && reg_is_referenced(env, reg)) 16434 return __check_ptr_off_reg(env, reg, argno_from_reg(regno), false); 16435 } 16436 16437 /* eBPF calling convention is such that R0 is used 16438 * to return the value from eBPF program. 16439 * Make sure that it's readable at this time 16440 * of bpf_exit, which means that program wrote 16441 * something into it earlier 16442 */ 16443 err = check_reg_arg(env, regno, SRC_OP); 16444 if (err) 16445 return err; 16446 16447 if (is_pointer_value(env, regno)) { 16448 verbose(env, "R%d leaks addr as return value\n", regno); 16449 return -EACCES; 16450 } 16451 16452 if (frame->in_async_callback_fn) { 16453 exit_ctx = "At async callback return"; 16454 range = frame->callback_ret_range; 16455 goto enforce_retval; 16456 } 16457 16458 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type) 16459 return 0; 16460 16461 if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)) 16462 enforce_attach_type_range = tnum_range(2, 3); 16463 16464 if (!return_retval_range(env, &range)) 16465 return 0; 16466 16467 enforce_retval: 16468 if (reg->type != SCALAR_VALUE) { 16469 verbose(env, "%s the register R%d is not a known value (%s)\n", 16470 exit_ctx, regno, reg_type_str(env, reg->type)); 16471 return -EINVAL; 16472 } 16473 16474 err = mark_chain_precision(env, regno); 16475 if (err) 16476 return err; 16477 16478 if (!retval_range_within(range, reg)) { 16479 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 16480 if (prog->expected_attach_type == BPF_LSM_CGROUP && 16481 prog_type == BPF_PROG_TYPE_LSM && 16482 !prog->aux->attach_func_proto->type) 16483 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 16484 return -EINVAL; 16485 } 16486 16487 if (!tnum_is_unknown(enforce_attach_type_range) && 16488 tnum_in(enforce_attach_type_range, reg->var_off)) 16489 env->prog->enforce_expected_attach_type = 1; 16490 return 0; 16491 } 16492 16493 static int check_global_subprog_return_code(struct bpf_verifier_env *env) 16494 { 16495 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 16496 struct bpf_func_state *cur_frame = cur_func(env); 16497 int err; 16498 16499 if (subprog_returns_void(env, cur_frame->subprogno)) 16500 return 0; 16501 16502 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 16503 if (err) 16504 return err; 16505 16506 /* Pointers to arena are safe to pass between subprograms. */ 16507 if (is_arena_reg(env, BPF_REG_0)) 16508 return 0; 16509 16510 if (is_pointer_value(env, BPF_REG_0)) { 16511 verbose(env, "R%d leaks addr as return value\n", BPF_REG_0); 16512 return -EACCES; 16513 } 16514 16515 if (reg->type != SCALAR_VALUE) { 16516 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 16517 reg_type_str(env, reg->type)); 16518 return -EINVAL; 16519 } 16520 16521 return 0; 16522 } 16523 16524 /* Bitmask with 1s for all caller saved registers */ 16525 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16526 16527 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16528 * replacement patch is presumed to follow bpf_fastcall contract 16529 * (see mark_fastcall_pattern_for_call() below). 16530 */ 16531 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 16532 { 16533 switch (imm) { 16534 #ifdef CONFIG_X86_64 16535 case BPF_FUNC_get_smp_processor_id: 16536 #ifdef CONFIG_SMP 16537 case BPF_FUNC_get_current_task_btf: 16538 case BPF_FUNC_get_current_task: 16539 #endif 16540 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 16541 #endif 16542 default: 16543 return false; 16544 } 16545 } 16546 16547 /* If @call is a kfunc or helper call, fills @cs and returns true, 16548 * otherwise returns false. 16549 */ 16550 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 16551 struct bpf_call_summary *cs) 16552 { 16553 struct bpf_kfunc_call_arg_meta meta; 16554 const struct bpf_func_proto *fn; 16555 int i; 16556 16557 if (bpf_helper_call(call)) { 16558 16559 if (bpf_get_helper_proto(env, call->imm, &fn) < 0) 16560 /* error would be reported later */ 16561 return false; 16562 cs->fastcall = fn->allow_fastcall && 16563 (bpf_verifier_inlines_helper_call(env, call->imm) || 16564 bpf_jit_inlines_helper_call(call->imm)); 16565 cs->is_void = fn->ret_type == RET_VOID; 16566 cs->num_params = 0; 16567 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 16568 if (fn->arg_type[i] == ARG_DONTCARE) 16569 break; 16570 cs->num_params++; 16571 } 16572 return true; 16573 } 16574 16575 if (bpf_pseudo_kfunc_call(call)) { 16576 int err; 16577 16578 err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta); 16579 if (err < 0) 16580 /* error would be reported later */ 16581 return false; 16582 cs->num_params = btf_type_vlen(meta.func_proto); 16583 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 16584 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 16585 return true; 16586 } 16587 16588 return false; 16589 } 16590 16591 /* LLVM define a bpf_fastcall function attribute. 16592 * This attribute means that function scratches only some of 16593 * the caller saved registers defined by ABI. 16594 * For BPF the set of such registers could be defined as follows: 16595 * - R0 is scratched only if function is non-void; 16596 * - R1-R5 are scratched only if corresponding parameter type is defined 16597 * in the function prototype. 16598 * 16599 * The contract between kernel and clang allows to simultaneously use 16600 * such functions and maintain backwards compatibility with old 16601 * kernels that don't understand bpf_fastcall calls: 16602 * 16603 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 16604 * registers are not scratched by the call; 16605 * 16606 * - as a post-processing step, clang visits each bpf_fastcall call and adds 16607 * spill/fill for every live r0-r5; 16608 * 16609 * - stack offsets used for the spill/fill are allocated as lowest 16610 * stack offsets in whole function and are not used for any other 16611 * purposes; 16612 * 16613 * - when kernel loads a program, it looks for such patterns 16614 * (bpf_fastcall function surrounded by spills/fills) and checks if 16615 * spill/fill stack offsets are used exclusively in fastcall patterns; 16616 * 16617 * - if so, and if verifier or current JIT inlines the call to the 16618 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 16619 * spill/fill pairs; 16620 * 16621 * - when old kernel loads a program, presence of spill/fill pairs 16622 * keeps BPF program valid, albeit slightly less efficient. 16623 * 16624 * For example: 16625 * 16626 * r1 = 1; 16627 * r2 = 2; 16628 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16629 * *(u64 *)(r10 - 16) = r2; r2 = 2; 16630 * call %[to_be_inlined] --> call %[to_be_inlined] 16631 * r2 = *(u64 *)(r10 - 16); r0 = r1; 16632 * r1 = *(u64 *)(r10 - 8); r0 += r2; 16633 * r0 = r1; exit; 16634 * r0 += r2; 16635 * exit; 16636 * 16637 * The purpose of mark_fastcall_pattern_for_call is to: 16638 * - look for such patterns; 16639 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 16640 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 16641 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 16642 * at which bpf_fastcall spill/fill stack slots start; 16643 * - update env->subprog_info[*]->keep_fastcall_stack. 16644 * 16645 * The .fastcall_pattern and .fastcall_stack_off are used by 16646 * check_fastcall_stack_contract() to check if every stack access to 16647 * fastcall spill/fill stack slot originates from spill/fill 16648 * instructions, members of fastcall patterns. 16649 * 16650 * If such condition holds true for a subprogram, fastcall patterns could 16651 * be rewritten by remove_fastcall_spills_fills(). 16652 * Otherwise bpf_fastcall patterns are not changed in the subprogram 16653 * (code, presumably, generated by an older clang version). 16654 * 16655 * For example, it is *not* safe to remove spill/fill below: 16656 * 16657 * r1 = 1; 16658 * *(u64 *)(r10 - 8) = r1; r1 = 1; 16659 * call %[to_be_inlined] --> call %[to_be_inlined] 16660 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 16661 * r0 = *(u64 *)(r10 - 8); r0 += r1; 16662 * r0 += r1; exit; 16663 * exit; 16664 */ 16665 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 16666 struct bpf_subprog_info *subprog, 16667 int insn_idx, s16 lowest_off) 16668 { 16669 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 16670 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 16671 u32 clobbered_regs_mask; 16672 struct bpf_call_summary cs; 16673 u32 expected_regs_mask; 16674 s16 off; 16675 int i; 16676 16677 if (!bpf_get_call_summary(env, call, &cs)) 16678 return; 16679 16680 /* A bitmask specifying which caller saved registers are clobbered 16681 * by a call to a helper/kfunc *as if* this helper/kfunc follows 16682 * bpf_fastcall contract: 16683 * - includes R0 if function is non-void; 16684 * - includes R1-R5 if corresponding parameter has is described 16685 * in the function prototype. 16686 */ 16687 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 16688 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 16689 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 16690 16691 /* match pairs of form: 16692 * 16693 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 16694 * ... 16695 * call %[to_be_inlined] 16696 * ... 16697 * rX = *(u64 *)(r10 - Y) 16698 */ 16699 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 16700 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 16701 break; 16702 stx = &insns[insn_idx - i]; 16703 ldx = &insns[insn_idx + i]; 16704 /* must be a stack spill/fill pair */ 16705 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 16706 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 16707 stx->dst_reg != BPF_REG_10 || 16708 ldx->src_reg != BPF_REG_10) 16709 break; 16710 /* must be a spill/fill for the same reg */ 16711 if (stx->src_reg != ldx->dst_reg) 16712 break; 16713 /* must be one of the previously unseen registers */ 16714 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 16715 break; 16716 /* must be a spill/fill for the same expected offset, 16717 * no need to check offset alignment, BPF_DW stack access 16718 * is always 8-byte aligned. 16719 */ 16720 if (stx->off != off || ldx->off != off) 16721 break; 16722 expected_regs_mask &= ~BIT(stx->src_reg); 16723 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 16724 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 16725 } 16726 if (i == 1) 16727 return; 16728 16729 /* Conditionally set 'fastcall_spills_num' to allow forward 16730 * compatibility when more helper functions are marked as 16731 * bpf_fastcall at compile time than current kernel supports, e.g: 16732 * 16733 * 1: *(u64 *)(r10 - 8) = r1 16734 * 2: call A ;; assume A is bpf_fastcall for current kernel 16735 * 3: r1 = *(u64 *)(r10 - 8) 16736 * 4: *(u64 *)(r10 - 8) = r1 16737 * 5: call B ;; assume B is not bpf_fastcall for current kernel 16738 * 6: r1 = *(u64 *)(r10 - 8) 16739 * 16740 * There is no need to block bpf_fastcall rewrite for such program. 16741 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 16742 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 16743 * does not remove spill/fill pair {4,6}. 16744 */ 16745 if (cs.fastcall) 16746 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 16747 else 16748 subprog->keep_fastcall_stack = 1; 16749 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 16750 } 16751 16752 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 16753 { 16754 struct bpf_subprog_info *subprog = env->subprog_info; 16755 struct bpf_insn *insn; 16756 s16 lowest_off; 16757 int s, i; 16758 16759 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 16760 /* find lowest stack spill offset used in this subprog */ 16761 lowest_off = 0; 16762 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16763 insn = env->prog->insnsi + i; 16764 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 16765 insn->dst_reg != BPF_REG_10) 16766 continue; 16767 lowest_off = min(lowest_off, insn->off); 16768 } 16769 /* use this offset to find fastcall patterns */ 16770 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 16771 insn = env->prog->insnsi + i; 16772 if (insn->code != (BPF_JMP | BPF_CALL)) 16773 continue; 16774 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 16775 } 16776 } 16777 return 0; 16778 } 16779 16780 static void adjust_btf_func(struct bpf_verifier_env *env) 16781 { 16782 struct bpf_prog_aux *aux = env->prog->aux; 16783 int i; 16784 16785 if (!aux->func_info) 16786 return; 16787 16788 /* func_info is not available for hidden subprogs */ 16789 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16790 aux->func_info[i].insn_off = env->subprog_info[i].start; 16791 } 16792 16793 /* Find id in idset and increment its count, or add new entry */ 16794 static void idset_cnt_inc(struct bpf_idset *idset, u32 id) 16795 { 16796 u32 i; 16797 16798 for (i = 0; i < idset->num_ids; i++) { 16799 if (idset->entries[i].id == id) { 16800 idset->entries[i].cnt++; 16801 return; 16802 } 16803 } 16804 /* New id */ 16805 if (idset->num_ids < BPF_ID_MAP_SIZE) { 16806 idset->entries[idset->num_ids].id = id; 16807 idset->entries[idset->num_ids].cnt = 1; 16808 idset->num_ids++; 16809 } 16810 } 16811 16812 /* Find id in idset and return its count, or 0 if not found */ 16813 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id) 16814 { 16815 u32 i; 16816 16817 for (i = 0; i < idset->num_ids; i++) { 16818 if (idset->entries[i].id == id) 16819 return idset->entries[i].cnt; 16820 } 16821 return 0; 16822 } 16823 16824 /* 16825 * Clear singular scalar ids in a state. 16826 * A register with a non-zero id is called singular if no other register shares 16827 * the same base id. Such registers can be treated as independent (id=0). 16828 */ 16829 void bpf_clear_singular_ids(struct bpf_verifier_env *env, 16830 struct bpf_verifier_state *st) 16831 { 16832 struct bpf_idset *idset = &env->idset_scratch; 16833 struct bpf_func_state *func; 16834 struct bpf_reg_state *reg; 16835 16836 idset->num_ids = 0; 16837 16838 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16839 if (reg->type != SCALAR_VALUE) 16840 continue; 16841 if (!reg->id) 16842 continue; 16843 idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST); 16844 })); 16845 16846 bpf_for_each_reg_in_vstate(st, func, reg, ({ 16847 if (reg->type != SCALAR_VALUE) 16848 continue; 16849 if (!reg->id) 16850 continue; 16851 if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1) 16852 clear_scalar_id(reg); 16853 })); 16854 } 16855 16856 /* Return true if it's OK to have the same insn return a different type. */ 16857 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 16858 { 16859 switch (base_type(type)) { 16860 case PTR_TO_CTX: 16861 case PTR_TO_SOCKET: 16862 case PTR_TO_SOCK_COMMON: 16863 case PTR_TO_TCP_SOCK: 16864 case PTR_TO_XDP_SOCK: 16865 case PTR_TO_BTF_ID: 16866 case PTR_TO_ARENA: 16867 return false; 16868 default: 16869 return true; 16870 } 16871 } 16872 16873 /* If an instruction was previously used with particular pointer types, then we 16874 * need to be careful to avoid cases such as the below, where it may be ok 16875 * for one branch accessing the pointer, but not ok for the other branch: 16876 * 16877 * R1 = sock_ptr 16878 * goto X; 16879 * ... 16880 * R1 = some_other_valid_ptr; 16881 * goto X; 16882 * ... 16883 * R2 = *(u32 *)(R1 + 0); 16884 */ 16885 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 16886 { 16887 return src != prev && (!reg_type_mismatch_ok(src) || 16888 !reg_type_mismatch_ok(prev)); 16889 } 16890 16891 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type) 16892 { 16893 switch (base_type(type)) { 16894 case PTR_TO_MEM: 16895 case PTR_TO_BTF_ID: 16896 return true; 16897 default: 16898 return false; 16899 } 16900 } 16901 16902 static bool is_ptr_to_mem(enum bpf_reg_type type) 16903 { 16904 return base_type(type) == PTR_TO_MEM; 16905 } 16906 16907 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 16908 bool allow_trust_mismatch) 16909 { 16910 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 16911 enum bpf_reg_type merged_type; 16912 16913 if (*prev_type == NOT_INIT) { 16914 /* Saw a valid insn 16915 * dst_reg = *(u32 *)(src_reg + off) 16916 * save type to validate intersecting paths 16917 */ 16918 *prev_type = type; 16919 } else if (reg_type_mismatch(type, *prev_type)) { 16920 /* Abuser program is trying to use the same insn 16921 * dst_reg = *(u32*) (src_reg + off) 16922 * with different pointer types: 16923 * src_reg == ctx in one branch and 16924 * src_reg == stack|map in some other branch. 16925 * Reject it. 16926 */ 16927 if (allow_trust_mismatch && 16928 is_ptr_to_mem_or_btf_id(type) && 16929 is_ptr_to_mem_or_btf_id(*prev_type)) { 16930 /* 16931 * Have to support a use case when one path through 16932 * the program yields TRUSTED pointer while another 16933 * is UNTRUSTED. Fallback to UNTRUSTED to generate 16934 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 16935 * Same behavior of MEM_RDONLY flag. 16936 */ 16937 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type)) 16938 merged_type = PTR_TO_MEM; 16939 else 16940 merged_type = PTR_TO_BTF_ID; 16941 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED)) 16942 merged_type |= PTR_UNTRUSTED; 16943 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY)) 16944 merged_type |= MEM_RDONLY; 16945 *prev_type = merged_type; 16946 } else { 16947 verbose(env, "same insn cannot be used with different pointers\n"); 16948 return -EINVAL; 16949 } 16950 } 16951 16952 return 0; 16953 } 16954 16955 enum { 16956 PROCESS_BPF_EXIT = 1, 16957 INSN_IDX_UPDATED = 2, 16958 }; 16959 16960 static int process_bpf_exit_full(struct bpf_verifier_env *env, 16961 bool *do_print_state, 16962 bool exception_exit) 16963 { 16964 struct bpf_func_state *cur_frame = cur_func(env); 16965 16966 /* We must do check_reference_leak here before 16967 * prepare_func_exit to handle the case when 16968 * state->curframe > 0, it may be a callback function, 16969 * for which reference_state must match caller reference 16970 * state when it exits. 16971 */ 16972 int err = check_resource_leak(env, exception_exit, 16973 exception_exit || !env->cur_state->curframe, 16974 exception_exit ? "bpf_throw" : 16975 "BPF_EXIT instruction in main prog"); 16976 if (err) 16977 return err; 16978 16979 /* The side effect of the prepare_func_exit which is 16980 * being skipped is that it frees bpf_func_state. 16981 * Typically, process_bpf_exit will only be hit with 16982 * outermost exit. copy_verifier_state in pop_stack will 16983 * handle freeing of any extra bpf_func_state left over 16984 * from not processing all nested function exits. We 16985 * also skip return code checks as they are not needed 16986 * for exceptional exits. 16987 */ 16988 if (exception_exit) 16989 return PROCESS_BPF_EXIT; 16990 16991 if (env->cur_state->curframe) { 16992 /* exit from nested function */ 16993 err = prepare_func_exit(env, &env->insn_idx); 16994 if (err) 16995 return err; 16996 *do_print_state = true; 16997 return INSN_IDX_UPDATED; 16998 } 16999 17000 /* 17001 * Return from a regular global subprogram differs from return 17002 * from the main program or async/exception callback. 17003 * Main program exit implies return code restrictions 17004 * that depend on program type. 17005 * Exit from exception callback is equivalent to main program exit. 17006 * Exit from async callback implies return code restrictions 17007 * that depend on async scheduling mechanism. 17008 */ 17009 if (cur_frame->subprogno && 17010 !cur_frame->in_async_callback_fn && 17011 !cur_frame->in_exception_callback_fn) 17012 err = check_global_subprog_return_code(env); 17013 else 17014 err = check_return_code(env, BPF_REG_0, "R0"); 17015 if (err) 17016 return err; 17017 return PROCESS_BPF_EXIT; 17018 } 17019 17020 static int indirect_jump_min_max_index(struct bpf_verifier_env *env, 17021 int regno, 17022 struct bpf_map *map, 17023 u32 *pmin_index, u32 *pmax_index) 17024 { 17025 struct bpf_reg_state *reg = reg_state(env, regno); 17026 u64 min_index = reg_umin(reg); 17027 u64 max_index = reg_umax(reg); 17028 const u32 size = 8; 17029 17030 if (min_index > (u64) U32_MAX * size) { 17031 verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg_umin(reg)); 17032 return -ERANGE; 17033 } 17034 if (max_index > (u64) U32_MAX * size) { 17035 verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg_umax(reg)); 17036 return -ERANGE; 17037 } 17038 17039 min_index /= size; 17040 max_index /= size; 17041 17042 if (max_index >= map->max_entries) { 17043 verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n", 17044 regno, min_index, max_index, map->max_entries); 17045 return -EINVAL; 17046 } 17047 17048 *pmin_index = min_index; 17049 *pmax_index = max_index; 17050 return 0; 17051 } 17052 17053 /* gotox *dst_reg */ 17054 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn) 17055 { 17056 struct bpf_verifier_state *other_branch; 17057 struct bpf_reg_state *dst_reg; 17058 struct bpf_map *map; 17059 u32 min_index, max_index; 17060 int err = 0; 17061 int n; 17062 int i; 17063 17064 dst_reg = reg_state(env, insn->dst_reg); 17065 if (dst_reg->type != PTR_TO_INSN) { 17066 verbose(env, "R%d has type %s, expected PTR_TO_INSN\n", 17067 insn->dst_reg, reg_type_str(env, dst_reg->type)); 17068 return -EINVAL; 17069 } 17070 17071 map = dst_reg->map_ptr; 17072 if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg)) 17073 return -EFAULT; 17074 17075 if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env, 17076 "R%d has incorrect map type %d", insn->dst_reg, map->map_type)) 17077 return -EFAULT; 17078 17079 err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index); 17080 if (err) 17081 return err; 17082 17083 /* Ensure that the buffer is large enough */ 17084 if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) { 17085 env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf, 17086 max_index - min_index + 1); 17087 if (!env->gotox_tmp_buf) 17088 return -ENOMEM; 17089 } 17090 17091 n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items); 17092 if (n < 0) 17093 return n; 17094 if (n == 0) { 17095 verbose(env, "register R%d doesn't point to any offset in map id=%d\n", 17096 insn->dst_reg, map->id); 17097 return -EINVAL; 17098 } 17099 17100 for (i = 0; i < n - 1; i++) { 17101 mark_indirect_target(env, env->gotox_tmp_buf->items[i]); 17102 other_branch = push_stack(env, env->gotox_tmp_buf->items[i], 17103 env->insn_idx, env->cur_state->speculative); 17104 if (IS_ERR(other_branch)) 17105 return PTR_ERR(other_branch); 17106 } 17107 env->insn_idx = env->gotox_tmp_buf->items[n-1]; 17108 mark_indirect_target(env, env->insn_idx); 17109 return INSN_IDX_UPDATED; 17110 } 17111 17112 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 17113 { 17114 int err; 17115 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 17116 u8 class = BPF_CLASS(insn->code); 17117 17118 switch (class) { 17119 case BPF_ALU: 17120 case BPF_ALU64: 17121 return check_alu_op(env, insn); 17122 17123 case BPF_LDX: 17124 return check_load_mem(env, insn, false, 17125 BPF_MODE(insn->code) == BPF_MEMSX, 17126 true, "ldx"); 17127 17128 case BPF_STX: 17129 if (BPF_MODE(insn->code) == BPF_ATOMIC) 17130 return check_atomic(env, insn); 17131 return check_store_reg(env, insn, false); 17132 17133 case BPF_ST: { 17134 /* Handle stack arg write (store immediate) */ 17135 if (is_stack_arg_st(insn)) { 17136 struct bpf_verifier_state *vstate = env->cur_state; 17137 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 17138 17139 return check_stack_arg_write(env, state, insn->off, NULL); 17140 } 17141 17142 enum bpf_reg_type dst_reg_type; 17143 17144 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17145 if (err) 17146 return err; 17147 17148 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 17149 17150 err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg, argno_from_reg(insn->dst_reg), 17151 insn->off, BPF_SIZE(insn->code), 17152 BPF_WRITE, -1, false, false); 17153 if (err) 17154 return err; 17155 17156 return save_aux_ptr_type(env, dst_reg_type, false); 17157 } 17158 case BPF_JMP: 17159 case BPF_JMP32: { 17160 u8 opcode = BPF_OP(insn->code); 17161 17162 env->jmps_processed++; 17163 if (opcode == BPF_CALL) { 17164 if (env->cur_state->active_locks) { 17165 if ((insn->src_reg == BPF_REG_0 && 17166 insn->imm != BPF_FUNC_spin_unlock && 17167 insn->imm != BPF_FUNC_kptr_xchg) || 17168 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17169 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) { 17170 verbose(env, 17171 "function calls are not allowed while holding a lock\n"); 17172 return -EINVAL; 17173 } 17174 } 17175 mark_reg_scratched(env, BPF_REG_0); 17176 if (bpf_in_stack_arg_cnt(&env->subprog_info[cur_func(env)->subprogno])) 17177 cur_func(env)->no_stack_arg_load = true; 17178 if (insn->src_reg == BPF_PSEUDO_CALL) 17179 return check_func_call(env, insn, &env->insn_idx); 17180 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17181 return check_kfunc_call(env, insn, &env->insn_idx); 17182 return check_helper_call(env, insn, &env->insn_idx); 17183 } else if (opcode == BPF_JA) { 17184 if (BPF_SRC(insn->code) == BPF_X) 17185 return check_indirect_jump(env, insn); 17186 17187 if (class == BPF_JMP) 17188 env->insn_idx += insn->off + 1; 17189 else 17190 env->insn_idx += insn->imm + 1; 17191 return INSN_IDX_UPDATED; 17192 } else if (opcode == BPF_EXIT) { 17193 return process_bpf_exit_full(env, do_print_state, false); 17194 } 17195 return check_cond_jmp_op(env, insn, &env->insn_idx); 17196 } 17197 case BPF_LD: { 17198 u8 mode = BPF_MODE(insn->code); 17199 17200 if (mode == BPF_ABS || mode == BPF_IND) 17201 return check_ld_abs(env, insn); 17202 17203 if (mode == BPF_IMM) { 17204 err = check_ld_imm(env, insn); 17205 if (err) 17206 return err; 17207 17208 env->insn_idx++; 17209 sanitize_mark_insn_seen(env); 17210 } 17211 return 0; 17212 } 17213 } 17214 /* all class values are handled above. silence compiler warning */ 17215 return -EFAULT; 17216 } 17217 17218 static int do_check(struct bpf_verifier_env *env) 17219 { 17220 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17221 struct bpf_verifier_state *state = env->cur_state; 17222 struct bpf_insn *insns = env->prog->insnsi; 17223 int insn_cnt = env->prog->len; 17224 bool do_print_state = false; 17225 int prev_insn_idx = -1; 17226 17227 for (;;) { 17228 struct bpf_insn *insn; 17229 struct bpf_insn_aux_data *insn_aux; 17230 int err; 17231 17232 /* reset current history entry on each new instruction */ 17233 env->cur_hist_ent = NULL; 17234 17235 env->prev_insn_idx = prev_insn_idx; 17236 if (env->insn_idx >= insn_cnt) { 17237 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17238 env->insn_idx, insn_cnt); 17239 return -EFAULT; 17240 } 17241 17242 insn = &insns[env->insn_idx]; 17243 insn_aux = &env->insn_aux_data[env->insn_idx]; 17244 17245 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17246 verbose(env, 17247 "BPF program is too large. Processed %d insn\n", 17248 env->insn_processed); 17249 return -E2BIG; 17250 } 17251 17252 state->last_insn_idx = env->prev_insn_idx; 17253 state->insn_idx = env->insn_idx; 17254 17255 if (bpf_is_prune_point(env, env->insn_idx)) { 17256 err = bpf_is_state_visited(env, env->insn_idx); 17257 if (err < 0) 17258 return err; 17259 if (err == 1) { 17260 /* found equivalent state, can prune the search */ 17261 if (env->log.level & BPF_LOG_LEVEL) { 17262 if (do_print_state) 17263 verbose(env, "\nfrom %d to %d%s: safe\n", 17264 env->prev_insn_idx, env->insn_idx, 17265 env->cur_state->speculative ? 17266 " (speculative execution)" : ""); 17267 else 17268 verbose(env, "%d: safe\n", env->insn_idx); 17269 } 17270 goto process_bpf_exit; 17271 } 17272 } 17273 17274 if (bpf_is_jmp_point(env, env->insn_idx)) { 17275 err = bpf_push_jmp_history(env, state, 0, 0, 0, 0); 17276 if (err) 17277 return err; 17278 } 17279 17280 if (signal_pending(current)) 17281 return -EAGAIN; 17282 17283 if (need_resched()) 17284 cond_resched(); 17285 17286 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17287 verbose(env, "\nfrom %d to %d%s:", 17288 env->prev_insn_idx, env->insn_idx, 17289 env->cur_state->speculative ? 17290 " (speculative execution)" : ""); 17291 print_verifier_state(env, state, state->curframe, true); 17292 do_print_state = false; 17293 } 17294 17295 if (env->log.level & BPF_LOG_LEVEL) { 17296 if (verifier_state_scratched(env)) 17297 print_insn_state(env, state, state->curframe); 17298 17299 verbose_linfo(env, env->insn_idx, "; "); 17300 env->prev_log_pos = env->log.end_pos; 17301 verbose(env, "%d: ", env->insn_idx); 17302 bpf_verbose_insn(env, insn); 17303 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17304 env->prev_log_pos = env->log.end_pos; 17305 } 17306 17307 if (bpf_prog_is_offloaded(env->prog->aux)) { 17308 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17309 env->prev_insn_idx); 17310 if (err) 17311 return err; 17312 } 17313 17314 sanitize_mark_insn_seen(env); 17315 prev_insn_idx = env->insn_idx; 17316 17317 /* Sanity check: precomputed constants must match verifier state */ 17318 if (!state->speculative && insn_aux->const_reg_mask) { 17319 struct bpf_reg_state *regs = cur_regs(env); 17320 u16 mask = insn_aux->const_reg_mask; 17321 17322 for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) { 17323 u32 cval = insn_aux->const_reg_vals[r]; 17324 17325 if (!(mask & BIT(r))) 17326 continue; 17327 if (regs[r].type != SCALAR_VALUE) 17328 continue; 17329 if (!tnum_is_const(regs[r].var_off)) 17330 continue; 17331 if (verifier_bug_if((u32)regs[r].var_off.value != cval, 17332 env, "const R%d: %u != %llu", 17333 r, cval, regs[r].var_off.value)) 17334 return -EFAULT; 17335 } 17336 } 17337 17338 /* Reduce verification complexity by stopping speculative path 17339 * verification when a nospec is encountered. 17340 */ 17341 if (state->speculative && insn_aux->nospec) 17342 goto process_bpf_exit; 17343 17344 err = do_check_insn(env, &do_print_state); 17345 if (error_recoverable_with_nospec(err) && state->speculative) { 17346 /* Prevent this speculative path from ever reaching the 17347 * insn that would have been unsafe to execute. 17348 */ 17349 insn_aux->nospec = true; 17350 /* If it was an ADD/SUB insn, potentially remove any 17351 * markings for alu sanitization. 17352 */ 17353 insn_aux->alu_state = 0; 17354 goto process_bpf_exit; 17355 } else if (err < 0) { 17356 return err; 17357 } else if (err == PROCESS_BPF_EXIT) { 17358 goto process_bpf_exit; 17359 } else if (err == INSN_IDX_UPDATED) { 17360 } else if (err == 0) { 17361 env->insn_idx++; 17362 } 17363 17364 if (state->speculative && insn_aux->nospec_result) { 17365 /* If we are on a path that performed a jump-op, this 17366 * may skip a nospec patched-in after the jump. This can 17367 * currently never happen because nospec_result is only 17368 * used for the write-ops 17369 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper 17370 * calls. These must never skip the following insn 17371 * (i.e., bpf_insn_successors()'s opcode_info.can_jump 17372 * is false). Still, add a warning to document this in 17373 * case nospec_result is used elsewhere in the future. 17374 * 17375 * All non-branch instructions have a single 17376 * fall-through edge. For these, nospec_result should 17377 * already work. 17378 */ 17379 if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP || 17380 BPF_CLASS(insn->code) == BPF_JMP32) && 17381 BPF_OP(insn->code) != BPF_CALL, env, 17382 "speculation barrier after jump instruction may not have the desired effect")) 17383 return -EFAULT; 17384 process_bpf_exit: 17385 mark_verifier_state_scratched(env); 17386 err = bpf_update_branch_counts(env, env->cur_state); 17387 if (err) 17388 return err; 17389 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 17390 pop_log); 17391 if (err < 0) { 17392 if (err != -ENOENT) 17393 return err; 17394 break; 17395 } else { 17396 do_print_state = true; 17397 continue; 17398 } 17399 } 17400 } 17401 17402 return 0; 17403 } 17404 17405 static int find_btf_percpu_datasec(struct btf *btf) 17406 { 17407 const struct btf_type *t; 17408 const char *tname; 17409 int i, n; 17410 17411 /* 17412 * Both vmlinux and module each have their own ".data..percpu" 17413 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17414 * types to look at only module's own BTF types. 17415 */ 17416 n = btf_nr_types(btf); 17417 for (i = btf_named_start_id(btf, true); i < n; i++) { 17418 t = btf_type_by_id(btf, i); 17419 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17420 continue; 17421 17422 tname = btf_name_by_offset(btf, t->name_off); 17423 if (!strcmp(tname, ".data..percpu")) 17424 return i; 17425 } 17426 17427 return -ENOENT; 17428 } 17429 17430 /* 17431 * Add btf to the env->used_btfs array. If needed, refcount the 17432 * corresponding kernel module. To simplify caller's logic 17433 * in case of error or if btf was added before the function 17434 * decreases the btf refcount. 17435 */ 17436 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 17437 { 17438 struct btf_mod_pair *btf_mod; 17439 int ret = 0; 17440 int i; 17441 17442 /* check whether we recorded this BTF (and maybe module) already */ 17443 for (i = 0; i < env->used_btf_cnt; i++) 17444 if (env->used_btfs[i].btf == btf) 17445 goto ret_put; 17446 17447 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17448 verbose(env, "The total number of btfs per program has reached the limit of %u\n", 17449 MAX_USED_BTFS); 17450 ret = -E2BIG; 17451 goto ret_put; 17452 } 17453 17454 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17455 btf_mod->btf = btf; 17456 btf_mod->module = NULL; 17457 17458 /* if we reference variables from kernel module, bump its refcount */ 17459 if (btf_is_module(btf)) { 17460 btf_mod->module = btf_try_get_module(btf); 17461 if (!btf_mod->module) { 17462 ret = -ENXIO; 17463 goto ret_put; 17464 } 17465 } 17466 17467 env->used_btf_cnt++; 17468 return 0; 17469 17470 ret_put: 17471 /* Either error or this BTF was already added */ 17472 btf_put(btf); 17473 return ret; 17474 } 17475 17476 /* replace pseudo btf_id with kernel symbol address */ 17477 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 17478 struct bpf_insn *insn, 17479 struct bpf_insn_aux_data *aux, 17480 struct btf *btf) 17481 { 17482 const struct btf_var_secinfo *vsi; 17483 const struct btf_type *datasec; 17484 const struct btf_type *t; 17485 const char *sym_name; 17486 bool percpu = false; 17487 u32 type, id = insn->imm; 17488 s32 datasec_id; 17489 u64 addr; 17490 int i; 17491 17492 t = btf_type_by_id(btf, id); 17493 if (!t) { 17494 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17495 return -ENOENT; 17496 } 17497 17498 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17499 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17500 return -EINVAL; 17501 } 17502 17503 sym_name = btf_name_by_offset(btf, t->name_off); 17504 addr = kallsyms_lookup_name(sym_name); 17505 if (!addr) { 17506 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17507 sym_name); 17508 return -ENOENT; 17509 } 17510 insn[0].imm = (u32)addr; 17511 insn[1].imm = addr >> 32; 17512 17513 if (btf_type_is_func(t)) { 17514 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17515 aux->btf_var.mem_size = 0; 17516 return 0; 17517 } 17518 17519 datasec_id = find_btf_percpu_datasec(btf); 17520 if (datasec_id > 0) { 17521 datasec = btf_type_by_id(btf, datasec_id); 17522 for_each_vsi(i, datasec, vsi) { 17523 if (vsi->type == id) { 17524 percpu = true; 17525 break; 17526 } 17527 } 17528 } 17529 17530 type = t->type; 17531 t = btf_type_skip_modifiers(btf, type, NULL); 17532 if (percpu) { 17533 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17534 aux->btf_var.btf = btf; 17535 aux->btf_var.btf_id = type; 17536 } else if (!btf_type_is_struct(t)) { 17537 const struct btf_type *ret; 17538 const char *tname; 17539 u32 tsize; 17540 17541 /* resolve the type size of ksym. */ 17542 ret = btf_resolve_size(btf, t, &tsize); 17543 if (IS_ERR(ret)) { 17544 tname = btf_name_by_offset(btf, t->name_off); 17545 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 17546 tname, PTR_ERR(ret)); 17547 return -EINVAL; 17548 } 17549 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17550 aux->btf_var.mem_size = tsize; 17551 } else { 17552 aux->btf_var.reg_type = PTR_TO_BTF_ID; 17553 aux->btf_var.btf = btf; 17554 aux->btf_var.btf_id = type; 17555 } 17556 17557 return 0; 17558 } 17559 17560 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17561 struct bpf_insn *insn, 17562 struct bpf_insn_aux_data *aux) 17563 { 17564 struct btf *btf; 17565 int btf_fd; 17566 int err; 17567 17568 btf_fd = insn[1].imm; 17569 if (btf_fd) { 17570 btf = btf_get_by_fd(btf_fd); 17571 if (IS_ERR(btf)) { 17572 verbose(env, "invalid module BTF object FD specified.\n"); 17573 return -EINVAL; 17574 } 17575 } else { 17576 if (!btf_vmlinux) { 17577 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17578 return -EINVAL; 17579 } 17580 btf_get(btf_vmlinux); 17581 btf = btf_vmlinux; 17582 } 17583 17584 err = __check_pseudo_btf_id(env, insn, aux, btf); 17585 if (err) { 17586 btf_put(btf); 17587 return err; 17588 } 17589 17590 return __add_used_btf(env, btf); 17591 } 17592 17593 static bool is_tracing_prog_type(enum bpf_prog_type type) 17594 { 17595 switch (type) { 17596 case BPF_PROG_TYPE_KPROBE: 17597 case BPF_PROG_TYPE_TRACEPOINT: 17598 case BPF_PROG_TYPE_PERF_EVENT: 17599 case BPF_PROG_TYPE_RAW_TRACEPOINT: 17600 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 17601 return true; 17602 default: 17603 return false; 17604 } 17605 } 17606 17607 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 17608 { 17609 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 17610 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 17611 } 17612 17613 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 17614 struct bpf_map *map, 17615 struct bpf_prog *prog) 17616 17617 { 17618 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17619 17620 if (map->excl_prog_sha && 17621 memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) { 17622 verbose(env, "program's hash doesn't match map's excl_prog_hash\n"); 17623 return -EACCES; 17624 } 17625 17626 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 17627 btf_record_has_field(map->record, BPF_RB_ROOT)) { 17628 if (is_tracing_prog_type(prog_type)) { 17629 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 17630 return -EINVAL; 17631 } 17632 } 17633 17634 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 17635 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 17636 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 17637 return -EINVAL; 17638 } 17639 17640 if (is_tracing_prog_type(prog_type)) { 17641 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 17642 return -EINVAL; 17643 } 17644 } 17645 17646 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 17647 !bpf_offload_prog_map_match(prog, map)) { 17648 verbose(env, "offload device mismatch between prog and map\n"); 17649 return -EINVAL; 17650 } 17651 17652 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 17653 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 17654 return -EINVAL; 17655 } 17656 17657 if (prog->sleepable) 17658 switch (map->map_type) { 17659 case BPF_MAP_TYPE_HASH: 17660 case BPF_MAP_TYPE_LRU_HASH: 17661 case BPF_MAP_TYPE_ARRAY: 17662 case BPF_MAP_TYPE_PERCPU_HASH: 17663 case BPF_MAP_TYPE_PERCPU_ARRAY: 17664 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 17665 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 17666 case BPF_MAP_TYPE_HASH_OF_MAPS: 17667 case BPF_MAP_TYPE_RINGBUF: 17668 case BPF_MAP_TYPE_USER_RINGBUF: 17669 case BPF_MAP_TYPE_INODE_STORAGE: 17670 case BPF_MAP_TYPE_SK_STORAGE: 17671 case BPF_MAP_TYPE_TASK_STORAGE: 17672 case BPF_MAP_TYPE_CGRP_STORAGE: 17673 case BPF_MAP_TYPE_QUEUE: 17674 case BPF_MAP_TYPE_STACK: 17675 case BPF_MAP_TYPE_ARENA: 17676 case BPF_MAP_TYPE_INSN_ARRAY: 17677 case BPF_MAP_TYPE_PROG_ARRAY: 17678 break; 17679 default: 17680 verbose(env, 17681 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 17682 return -EINVAL; 17683 } 17684 17685 if (bpf_map_is_cgroup_storage(map) && 17686 bpf_cgroup_storage_assign(env->prog->aux, map)) { 17687 verbose(env, "only one cgroup storage of each type is allowed\n"); 17688 return -EBUSY; 17689 } 17690 17691 if (map->map_type == BPF_MAP_TYPE_ARENA) { 17692 if (env->prog->aux->arena) { 17693 verbose(env, "Only one arena per program\n"); 17694 return -EBUSY; 17695 } 17696 if (!env->allow_ptr_leaks || !env->bpf_capable) { 17697 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 17698 return -EPERM; 17699 } 17700 if (!env->prog->jit_requested) { 17701 verbose(env, "JIT is required to use arena\n"); 17702 return -EOPNOTSUPP; 17703 } 17704 if (!bpf_jit_supports_arena()) { 17705 verbose(env, "JIT doesn't support arena\n"); 17706 return -EOPNOTSUPP; 17707 } 17708 env->prog->aux->arena = (void *)map; 17709 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 17710 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 17711 return -EINVAL; 17712 } 17713 } 17714 17715 return 0; 17716 } 17717 17718 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 17719 { 17720 int i, err; 17721 17722 /* check whether we recorded this map already */ 17723 for (i = 0; i < env->used_map_cnt; i++) 17724 if (env->used_maps[i] == map) 17725 return i; 17726 17727 if (env->used_map_cnt >= MAX_USED_MAPS) { 17728 verbose(env, "The total number of maps per program has reached the limit of %u\n", 17729 MAX_USED_MAPS); 17730 return -E2BIG; 17731 } 17732 17733 err = check_map_prog_compatibility(env, map, env->prog); 17734 if (err) 17735 return err; 17736 17737 if (env->prog->sleepable) 17738 atomic64_inc(&map->sleepable_refcnt); 17739 17740 /* hold the map. If the program is rejected by verifier, 17741 * the map will be released by release_maps() or it 17742 * will be used by the valid program until it's unloaded 17743 * and all maps are released in bpf_free_used_maps() 17744 */ 17745 bpf_map_inc(map); 17746 17747 env->used_maps[env->used_map_cnt++] = map; 17748 17749 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 17750 err = bpf_insn_array_init(map, env->prog); 17751 if (err) { 17752 verbose(env, "Failed to properly initialize insn array\n"); 17753 return err; 17754 } 17755 env->insn_array_maps[env->insn_array_map_cnt++] = map; 17756 } 17757 17758 return env->used_map_cnt - 1; 17759 } 17760 17761 /* Add map behind fd to used maps list, if it's not already there, and return 17762 * its index. 17763 * Returns <0 on error, or >= 0 index, on success. 17764 */ 17765 static int add_used_map(struct bpf_verifier_env *env, int fd) 17766 { 17767 struct bpf_map *map; 17768 CLASS(fd, f)(fd); 17769 17770 map = __bpf_map_get(f); 17771 if (IS_ERR(map)) { 17772 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 17773 return PTR_ERR(map); 17774 } 17775 17776 return __add_used_map(env, map); 17777 } 17778 17779 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17780 { 17781 u8 class = BPF_CLASS(insn->code); 17782 u8 opcode = BPF_OP(insn->code); 17783 17784 switch (opcode) { 17785 case BPF_NEG: 17786 if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 || 17787 insn->off != 0 || insn->imm != 0) { 17788 verbose(env, "BPF_NEG uses reserved fields\n"); 17789 return -EINVAL; 17790 } 17791 return 0; 17792 case BPF_END: 17793 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 17794 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 17795 (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) { 17796 verbose(env, "BPF_END uses reserved fields\n"); 17797 return -EINVAL; 17798 } 17799 return 0; 17800 case BPF_MOV: 17801 if (BPF_SRC(insn->code) == BPF_X) { 17802 if (class == BPF_ALU) { 17803 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 17804 insn->imm) { 17805 verbose(env, "BPF_MOV uses reserved fields\n"); 17806 return -EINVAL; 17807 } 17808 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 17809 if (insn->imm != 1 && insn->imm != 1u << 16) { 17810 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 17811 return -EINVAL; 17812 } 17813 } else if ((insn->off != 0 && insn->off != 8 && 17814 insn->off != 16 && insn->off != 32) || insn->imm) { 17815 verbose(env, "BPF_MOV uses reserved fields\n"); 17816 return -EINVAL; 17817 } 17818 } else if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 17819 verbose(env, "BPF_MOV uses reserved fields\n"); 17820 return -EINVAL; 17821 } 17822 return 0; 17823 case BPF_ADD: 17824 case BPF_SUB: 17825 case BPF_AND: 17826 case BPF_OR: 17827 case BPF_XOR: 17828 case BPF_LSH: 17829 case BPF_RSH: 17830 case BPF_ARSH: 17831 case BPF_MUL: 17832 case BPF_DIV: 17833 case BPF_MOD: 17834 if (BPF_SRC(insn->code) == BPF_X) { 17835 if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) || 17836 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 17837 verbose(env, "BPF_ALU uses reserved fields\n"); 17838 return -EINVAL; 17839 } 17840 } else if (insn->src_reg != BPF_REG_0 || 17841 (insn->off != 0 && insn->off != 1) || 17842 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 17843 verbose(env, "BPF_ALU uses reserved fields\n"); 17844 return -EINVAL; 17845 } 17846 return 0; 17847 default: 17848 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 17849 return -EINVAL; 17850 } 17851 } 17852 17853 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17854 { 17855 u8 class = BPF_CLASS(insn->code); 17856 u8 opcode = BPF_OP(insn->code); 17857 17858 switch (opcode) { 17859 case BPF_CALL: 17860 if (BPF_SRC(insn->code) != BPF_K || 17861 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) || 17862 (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL && 17863 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17864 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 17865 verbose(env, "BPF_CALL uses reserved fields\n"); 17866 return -EINVAL; 17867 } 17868 return 0; 17869 case BPF_JA: 17870 if (BPF_SRC(insn->code) == BPF_X) { 17871 if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) { 17872 verbose(env, "BPF_JA|BPF_X uses reserved fields\n"); 17873 return -EINVAL; 17874 } 17875 } else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 17876 (class == BPF_JMP && insn->imm != 0) || 17877 (class == BPF_JMP32 && insn->off != 0)) { 17878 verbose(env, "BPF_JA uses reserved fields\n"); 17879 return -EINVAL; 17880 } 17881 return 0; 17882 case BPF_EXIT: 17883 if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || 17884 insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 17885 class == BPF_JMP32) { 17886 verbose(env, "BPF_EXIT uses reserved fields\n"); 17887 return -EINVAL; 17888 } 17889 return 0; 17890 case BPF_JCOND: 17891 if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO || 17892 insn->dst_reg || insn->imm) { 17893 verbose(env, "invalid may_goto imm %d\n", insn->imm); 17894 return -EINVAL; 17895 } 17896 return 0; 17897 default: 17898 if (BPF_SRC(insn->code) == BPF_X) { 17899 if (insn->imm != 0) { 17900 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 17901 return -EINVAL; 17902 } 17903 } else if (insn->src_reg != BPF_REG_0) { 17904 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 17905 return -EINVAL; 17906 } 17907 return 0; 17908 } 17909 } 17910 17911 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 17912 { 17913 switch (BPF_CLASS(insn->code)) { 17914 case BPF_ALU: 17915 case BPF_ALU64: 17916 return check_alu_fields(env, insn); 17917 case BPF_LDX: 17918 if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 17919 insn->imm != 0) { 17920 verbose(env, "BPF_LDX uses reserved fields\n"); 17921 return -EINVAL; 17922 } 17923 return 0; 17924 case BPF_STX: 17925 if (BPF_MODE(insn->code) == BPF_ATOMIC) 17926 return 0; 17927 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17928 verbose(env, "BPF_STX uses reserved fields\n"); 17929 return -EINVAL; 17930 } 17931 return 0; 17932 case BPF_ST: 17933 if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { 17934 verbose(env, "BPF_ST uses reserved fields\n"); 17935 return -EINVAL; 17936 } 17937 return 0; 17938 case BPF_JMP: 17939 case BPF_JMP32: 17940 return check_jmp_fields(env, insn); 17941 case BPF_LD: { 17942 u8 mode = BPF_MODE(insn->code); 17943 17944 if (mode == BPF_ABS || mode == BPF_IND) { 17945 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 17946 BPF_SIZE(insn->code) == BPF_DW || 17947 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 17948 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 17949 return -EINVAL; 17950 } 17951 } else if (mode != BPF_IMM) { 17952 verbose(env, "invalid BPF_LD mode\n"); 17953 return -EINVAL; 17954 } 17955 return 0; 17956 } 17957 default: 17958 verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code)); 17959 return -EINVAL; 17960 } 17961 } 17962 17963 /* 17964 * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions: 17965 * 17966 * 1. if it accesses map FD, replace it with actual map pointer. 17967 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 17968 * 17969 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 17970 */ 17971 static int check_and_resolve_insns(struct bpf_verifier_env *env) 17972 { 17973 struct bpf_insn *insn = env->prog->insnsi; 17974 int insn_cnt = env->prog->len; 17975 int i, err; 17976 17977 err = bpf_prog_calc_tag(env->prog); 17978 if (err) 17979 return err; 17980 17981 for (i = 0; i < insn_cnt; i++, insn++) { 17982 if (insn->dst_reg >= MAX_BPF_REG && 17983 !is_stack_arg_st(insn) && !is_stack_arg_stx(insn)) { 17984 verbose(env, "R%d is invalid\n", insn->dst_reg); 17985 return -EINVAL; 17986 } 17987 if (insn->src_reg >= MAX_BPF_REG && !is_stack_arg_ldx(insn)) { 17988 verbose(env, "R%d is invalid\n", insn->src_reg); 17989 return -EINVAL; 17990 } 17991 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 17992 struct bpf_insn_aux_data *aux; 17993 struct bpf_map *map; 17994 int map_idx; 17995 u64 addr; 17996 u32 fd; 17997 17998 if (i == insn_cnt - 1 || insn[1].code != 0 || 17999 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18000 insn[1].off != 0) { 18001 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18002 return -EINVAL; 18003 } 18004 18005 if (insn[0].off != 0) { 18006 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 18007 return -EINVAL; 18008 } 18009 18010 if (insn[0].src_reg == 0) 18011 /* valid generic load 64-bit imm */ 18012 goto next_insn; 18013 18014 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18015 aux = &env->insn_aux_data[i]; 18016 err = check_pseudo_btf_id(env, insn, aux); 18017 if (err) 18018 return err; 18019 goto next_insn; 18020 } 18021 18022 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18023 aux = &env->insn_aux_data[i]; 18024 aux->ptr_type = PTR_TO_FUNC; 18025 goto next_insn; 18026 } 18027 18028 /* In final convert_pseudo_ld_imm64() step, this is 18029 * converted into regular 64-bit imm load insn. 18030 */ 18031 switch (insn[0].src_reg) { 18032 case BPF_PSEUDO_MAP_VALUE: 18033 case BPF_PSEUDO_MAP_IDX_VALUE: 18034 break; 18035 case BPF_PSEUDO_MAP_FD: 18036 case BPF_PSEUDO_MAP_IDX: 18037 if (insn[1].imm == 0) 18038 break; 18039 fallthrough; 18040 default: 18041 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18042 return -EINVAL; 18043 } 18044 18045 switch (insn[0].src_reg) { 18046 case BPF_PSEUDO_MAP_IDX_VALUE: 18047 case BPF_PSEUDO_MAP_IDX: 18048 if (bpfptr_is_null(env->fd_array)) { 18049 verbose(env, "fd_idx without fd_array is invalid\n"); 18050 return -EPROTO; 18051 } 18052 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18053 insn[0].imm * sizeof(fd), 18054 sizeof(fd))) 18055 return -EFAULT; 18056 break; 18057 default: 18058 fd = insn[0].imm; 18059 break; 18060 } 18061 18062 map_idx = add_used_map(env, fd); 18063 if (map_idx < 0) 18064 return map_idx; 18065 map = env->used_maps[map_idx]; 18066 18067 aux = &env->insn_aux_data[i]; 18068 aux->map_index = map_idx; 18069 18070 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18071 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18072 addr = (unsigned long)map; 18073 } else { 18074 u32 off = insn[1].imm; 18075 18076 if (!map->ops->map_direct_value_addr) { 18077 verbose(env, "no direct value access support for this map type\n"); 18078 return -EINVAL; 18079 } 18080 18081 err = map->ops->map_direct_value_addr(map, &addr, off); 18082 if (err) { 18083 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18084 map->value_size, off); 18085 return err; 18086 } 18087 18088 aux->map_off = off; 18089 addr += off; 18090 } 18091 18092 insn[0].imm = (u32)addr; 18093 insn[1].imm = addr >> 32; 18094 18095 next_insn: 18096 insn++; 18097 i++; 18098 continue; 18099 } 18100 18101 /* Basic sanity check before we invest more work here. */ 18102 if (!bpf_opcode_in_insntable(insn->code)) { 18103 verbose(env, "unknown opcode %02x\n", insn->code); 18104 return -EINVAL; 18105 } 18106 18107 err = check_insn_fields(env, insn); 18108 if (err) 18109 return err; 18110 } 18111 18112 /* now all pseudo BPF_LD_IMM64 instructions load valid 18113 * 'struct bpf_map *' into a register instead of user map_fd. 18114 * These pointers will be used later by verifier to validate map access. 18115 */ 18116 return 0; 18117 } 18118 18119 /* drop refcnt of maps used by the rejected program */ 18120 static void release_maps(struct bpf_verifier_env *env) 18121 { 18122 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18123 env->used_map_cnt); 18124 } 18125 18126 /* drop refcnt of maps used by the rejected program */ 18127 static void release_btfs(struct bpf_verifier_env *env) 18128 { 18129 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 18130 } 18131 18132 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18133 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18134 { 18135 struct bpf_insn *insn = env->prog->insnsi; 18136 int insn_cnt = env->prog->len; 18137 int i; 18138 18139 for (i = 0; i < insn_cnt; i++, insn++) { 18140 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18141 continue; 18142 if (insn->src_reg == BPF_PSEUDO_FUNC) 18143 continue; 18144 insn->src_reg = 0; 18145 } 18146 } 18147 18148 static void release_insn_arrays(struct bpf_verifier_env *env) 18149 { 18150 int i; 18151 18152 for (i = 0; i < env->insn_array_map_cnt; i++) 18153 bpf_insn_array_release(env->insn_array_maps[i]); 18154 } 18155 18156 18157 18158 /* The verifier does more data flow analysis than llvm and will not 18159 * explore branches that are dead at run time. Malicious programs can 18160 * have dead code too. Therefore replace all dead at-run-time code 18161 * with 'ja -1'. 18162 * 18163 * Just nops are not optimal, e.g. if they would sit at the end of the 18164 * program and through another bug we would manage to jump there, then 18165 * we'd execute beyond program memory otherwise. Returning exception 18166 * code also wouldn't work since we can have subprogs where the dead 18167 * code could be located. 18168 */ 18169 static void sanitize_dead_code(struct bpf_verifier_env *env) 18170 { 18171 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18172 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18173 struct bpf_insn *insn = env->prog->insnsi; 18174 const int insn_cnt = env->prog->len; 18175 int i; 18176 18177 for (i = 0; i < insn_cnt; i++) { 18178 if (aux_data[i].seen) 18179 continue; 18180 memcpy(insn + i, &trap, sizeof(trap)); 18181 aux_data[i].zext_dst = false; 18182 } 18183 } 18184 18185 18186 18187 static void free_states(struct bpf_verifier_env *env) 18188 { 18189 struct bpf_verifier_state_list *sl; 18190 struct list_head *head, *pos, *tmp; 18191 struct bpf_scc_info *info; 18192 int i, j; 18193 18194 bpf_free_verifier_state(env->cur_state, true); 18195 env->cur_state = NULL; 18196 while (!pop_stack(env, NULL, NULL, false)); 18197 18198 list_for_each_safe(pos, tmp, &env->free_list) { 18199 sl = container_of(pos, struct bpf_verifier_state_list, node); 18200 bpf_free_verifier_state(&sl->state, false); 18201 kfree(sl); 18202 } 18203 INIT_LIST_HEAD(&env->free_list); 18204 18205 for (i = 0; i < env->scc_cnt; ++i) { 18206 info = env->scc_info[i]; 18207 if (!info) 18208 continue; 18209 for (j = 0; j < info->num_visits; j++) 18210 bpf_free_backedges(&info->visits[j]); 18211 kvfree(info); 18212 env->scc_info[i] = NULL; 18213 } 18214 18215 if (!env->explored_states) 18216 return; 18217 18218 for (i = 0; i < state_htab_size(env); i++) { 18219 head = &env->explored_states[i]; 18220 18221 list_for_each_safe(pos, tmp, head) { 18222 sl = container_of(pos, struct bpf_verifier_state_list, node); 18223 bpf_free_verifier_state(&sl->state, false); 18224 kfree(sl); 18225 } 18226 INIT_LIST_HEAD(&env->explored_states[i]); 18227 } 18228 } 18229 18230 static int do_check_common(struct bpf_verifier_env *env, int subprog) 18231 { 18232 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18233 struct bpf_subprog_info *sub = subprog_info(env, subprog); 18234 struct bpf_prog_aux *aux = env->prog->aux; 18235 struct bpf_verifier_state *state; 18236 struct bpf_reg_state *regs; 18237 int ret, i; 18238 18239 env->prev_linfo = NULL; 18240 env->pass_cnt++; 18241 18242 state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT); 18243 if (!state) 18244 return -ENOMEM; 18245 state->curframe = 0; 18246 state->speculative = false; 18247 state->branches = 1; 18248 state->in_sleepable = env->prog->sleepable; 18249 state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT); 18250 if (!state->frame[0]) { 18251 kfree(state); 18252 return -ENOMEM; 18253 } 18254 env->cur_state = state; 18255 init_func_state(env, state->frame[0], 18256 BPF_MAIN_FUNC /* callsite */, 18257 0 /* frameno */, 18258 subprog); 18259 state->first_insn_idx = env->subprog_info[subprog].start; 18260 state->last_insn_idx = -1; 18261 18262 regs = state->frame[state->curframe]->regs; 18263 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 18264 const char *sub_name = subprog_name(env, subprog); 18265 struct bpf_subprog_arg_info *arg; 18266 struct bpf_reg_state *reg; 18267 18268 if (env->log.level & BPF_LOG_LEVEL) 18269 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 18270 ret = btf_prepare_func_args(env, subprog); 18271 if (ret) 18272 goto out; 18273 18274 if (subprog_is_exc_cb(env, subprog)) { 18275 state->frame[0]->in_exception_callback_fn = true; 18276 18277 /* 18278 * Global functions are scalar or void, make sure 18279 * we return a scalar. 18280 */ 18281 if (subprog_returns_void(env, subprog)) { 18282 verbose(env, "exception cb cannot return void\n"); 18283 ret = -EINVAL; 18284 goto out; 18285 } 18286 18287 /* Also ensure the callback only has a single scalar argument. */ 18288 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 18289 verbose(env, "exception cb only supports single integer argument\n"); 18290 ret = -EINVAL; 18291 goto out; 18292 } 18293 } 18294 for (i = BPF_REG_1; i <= min_t(u32, sub->arg_cnt, MAX_BPF_FUNC_REG_ARGS); i++) { 18295 arg = &sub->args[i - BPF_REG_1]; 18296 reg = ®s[i]; 18297 18298 if (arg->arg_type == ARG_PTR_TO_CTX) { 18299 reg->type = PTR_TO_CTX; 18300 mark_reg_known_zero(env, regs, i); 18301 } else if (arg->arg_type == ARG_ANYTHING) { 18302 reg->type = SCALAR_VALUE; 18303 mark_reg_unknown(env, regs, i); 18304 } else if (arg->arg_type == ARG_PTR_TO_DYNPTR) { 18305 /* assume unspecial LOCAL dynptr type */ 18306 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen, 0); 18307 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 18308 reg->type = PTR_TO_MEM; 18309 reg->type |= arg->arg_type & 18310 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 18311 mark_reg_known_zero(env, regs, i); 18312 reg->mem_size = arg->mem_size; 18313 if (arg->arg_type & PTR_MAYBE_NULL) 18314 reg->id = ++env->id_gen; 18315 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 18316 reg->type = PTR_TO_BTF_ID; 18317 if (arg->arg_type & PTR_MAYBE_NULL) 18318 reg->type |= PTR_MAYBE_NULL; 18319 if (arg->arg_type & PTR_UNTRUSTED) 18320 reg->type |= PTR_UNTRUSTED; 18321 if (arg->arg_type & PTR_TRUSTED) 18322 reg->type |= PTR_TRUSTED; 18323 mark_reg_known_zero(env, regs, i); 18324 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 18325 reg->btf_id = arg->btf_id; 18326 reg->id = ++env->id_gen; 18327 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 18328 /* caller can pass either PTR_TO_ARENA or SCALAR */ 18329 mark_reg_unknown(env, regs, i); 18330 } else { 18331 verifier_bug(env, "unhandled arg#%d type %d", 18332 i - BPF_REG_1 + 1, arg->arg_type); 18333 ret = -EFAULT; 18334 goto out; 18335 } 18336 } 18337 if (env->prog->type == BPF_PROG_TYPE_EXT && sub->arg_cnt > MAX_BPF_FUNC_REG_ARGS) { 18338 verbose(env, "freplace programs with >%d args not supported yet\n", 18339 MAX_BPF_FUNC_REG_ARGS); 18340 ret = -EINVAL; 18341 goto out; 18342 } 18343 } else { 18344 /* if main BPF program has associated BTF info, validate that 18345 * it's matching expected signature, and otherwise mark BTF 18346 * info for main program as unreliable 18347 */ 18348 if (env->prog->aux->func_info_aux) { 18349 ret = btf_prepare_func_args(env, 0); 18350 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) { 18351 env->prog->aux->func_info_aux[0].unreliable = true; 18352 sub->arg_cnt = 1; 18353 sub->stack_arg_cnt = 0; 18354 } 18355 } 18356 18357 /* 1st arg to a function */ 18358 regs[BPF_REG_1].type = PTR_TO_CTX; 18359 mark_reg_known_zero(env, regs, BPF_REG_1); 18360 } 18361 18362 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 18363 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 18364 for (i = 0; i < aux->ctx_arg_info_size; i++) 18365 aux->ctx_arg_info[i].ref_id = aux->ctx_arg_info[i].refcounted ? 18366 acquire_reference(env, 0, 0) : 0; 18367 } 18368 18369 ret = do_check(env); 18370 out: 18371 if (!ret && pop_log) 18372 bpf_vlog_reset(&env->log, 0); 18373 free_states(env); 18374 return ret; 18375 } 18376 18377 /* Lazily verify all global functions based on their BTF, if they are called 18378 * from main BPF program or any of subprograms transitively. 18379 * BPF global subprogs called from dead code are not validated. 18380 * All callable global functions must pass verification. 18381 * Otherwise the whole program is rejected. 18382 * Consider: 18383 * int bar(int); 18384 * int foo(int f) 18385 * { 18386 * return bar(f); 18387 * } 18388 * int bar(int b) 18389 * { 18390 * ... 18391 * } 18392 * foo() will be verified first for R1=any_scalar_value. During verification it 18393 * will be assumed that bar() already verified successfully and call to bar() 18394 * from foo() will be checked for type match only. Later bar() will be verified 18395 * independently to check that it's safe for R1=any_scalar_value. 18396 */ 18397 static int do_check_subprogs(struct bpf_verifier_env *env) 18398 { 18399 struct bpf_prog_aux *aux = env->prog->aux; 18400 struct bpf_func_info_aux *sub_aux; 18401 int i, ret, new_cnt; 18402 u32 insn_processed; 18403 18404 if (!aux->func_info) 18405 return 0; 18406 18407 /* exception callback is presumed to be always called */ 18408 if (env->exception_callback_subprog) 18409 subprog_aux(env, env->exception_callback_subprog)->called = true; 18410 18411 again: 18412 new_cnt = 0; 18413 for (i = 1; i < env->subprog_cnt; i++) { 18414 if (!bpf_subprog_is_global(env, i)) 18415 continue; 18416 18417 insn_processed = env->insn_processed; 18418 18419 sub_aux = subprog_aux(env, i); 18420 if (!sub_aux->called || sub_aux->verified) 18421 continue; 18422 18423 env->insn_idx = env->subprog_info[i].start; 18424 WARN_ON_ONCE(env->insn_idx == 0); 18425 ret = do_check_common(env, i); 18426 env->subprog_info[i].insn_processed = env->insn_processed - insn_processed; 18427 if (ret) { 18428 return ret; 18429 } else if (env->log.level & BPF_LOG_LEVEL) { 18430 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 18431 i, subprog_name(env, i)); 18432 } 18433 18434 /* We verified new global subprog, it might have called some 18435 * more global subprogs that we haven't verified yet, so we 18436 * need to do another pass over subprogs to verify those. 18437 */ 18438 sub_aux->verified = true; 18439 new_cnt++; 18440 } 18441 18442 /* We can't loop forever as we verify at least one global subprog on 18443 * each pass. 18444 */ 18445 if (new_cnt) 18446 goto again; 18447 18448 return 0; 18449 } 18450 18451 static int do_check_main(struct bpf_verifier_env *env) 18452 { 18453 u32 insn_processed = env->insn_processed; 18454 int ret; 18455 18456 env->insn_idx = 0; 18457 ret = do_check_common(env, 0); 18458 env->subprog_info[0].insn_processed = env->insn_processed - insn_processed; 18459 if (!ret) 18460 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18461 return ret; 18462 } 18463 18464 18465 static void print_verification_stats(struct bpf_verifier_env *env) 18466 { 18467 /* Skip over hidden subprogs which are not verified. */ 18468 int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 18469 18470 if (env->log.level & BPF_LOG_STATS) { 18471 verbose(env, "verification time %lld usec\n", 18472 div_u64(env->verification_time, 1000)); 18473 verbose(env, "stack depth %d", env->subprog_info[0].stack_depth); 18474 for (i = 1; i < subprog_cnt; i++) 18475 verbose(env, "+%d", env->subprog_info[i].stack_depth); 18476 verbose(env, " max %d\n", env->max_stack_depth); 18477 verbose(env, "insns processed %d", env->subprog_info[0].insn_processed); 18478 for (i = 1; i < subprog_cnt; i++) 18479 if (bpf_subprog_is_global(env, i)) 18480 verbose(env, "+%d", env->subprog_info[i].insn_processed); 18481 verbose(env, "\n"); 18482 } 18483 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 18484 "total_states %d peak_states %d mark_read %d\n", 18485 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 18486 env->max_states_per_insn, env->total_states, 18487 env->peak_states, env->longest_mark_read_walk); 18488 } 18489 18490 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 18491 const struct bpf_ctx_arg_aux *info, u32 cnt) 18492 { 18493 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 18494 prog->aux->ctx_arg_info_size = cnt; 18495 18496 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 18497 } 18498 18499 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 18500 { 18501 const struct btf_type *t, *func_proto; 18502 const struct bpf_struct_ops_desc *st_ops_desc; 18503 const struct bpf_struct_ops *st_ops; 18504 const struct btf_member *member; 18505 struct bpf_prog *prog = env->prog; 18506 bool has_refcounted_arg = false; 18507 u32 btf_id, member_idx, member_off; 18508 struct btf *btf; 18509 const char *mname; 18510 int i, err; 18511 18512 if (!prog->gpl_compatible) { 18513 verbose(env, "struct ops programs must have a GPL compatible license\n"); 18514 return -EINVAL; 18515 } 18516 18517 if (!prog->aux->attach_btf_id) 18518 return -ENOTSUPP; 18519 18520 btf = prog->aux->attach_btf; 18521 if (btf_is_module(btf)) { 18522 /* Make sure st_ops is valid through the lifetime of env */ 18523 env->attach_btf_mod = btf_try_get_module(btf); 18524 if (!env->attach_btf_mod) { 18525 verbose(env, "struct_ops module %s is not found\n", 18526 btf_get_name(btf)); 18527 return -ENOTSUPP; 18528 } 18529 } 18530 18531 btf_id = prog->aux->attach_btf_id; 18532 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 18533 if (!st_ops_desc) { 18534 verbose(env, "attach_btf_id %u is not a supported struct\n", 18535 btf_id); 18536 return -ENOTSUPP; 18537 } 18538 st_ops = st_ops_desc->st_ops; 18539 18540 t = st_ops_desc->type; 18541 member_idx = prog->expected_attach_type; 18542 if (member_idx >= btf_type_vlen(t)) { 18543 verbose(env, "attach to invalid member idx %u of struct %s\n", 18544 member_idx, st_ops->name); 18545 return -EINVAL; 18546 } 18547 18548 member = &btf_type_member(t)[member_idx]; 18549 mname = btf_name_by_offset(btf, member->name_off); 18550 func_proto = btf_type_resolve_func_ptr(btf, member->type, 18551 NULL); 18552 if (!func_proto) { 18553 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 18554 mname, member_idx, st_ops->name); 18555 return -EINVAL; 18556 } 18557 18558 member_off = __btf_member_bit_offset(t, member) / 8; 18559 err = bpf_struct_ops_supported(st_ops, member_off); 18560 if (err) { 18561 verbose(env, "attach to unsupported member %s of struct %s\n", 18562 mname, st_ops->name); 18563 return err; 18564 } 18565 18566 if (st_ops->check_member) { 18567 err = st_ops->check_member(t, member, prog); 18568 18569 if (err) { 18570 verbose(env, "attach to unsupported member %s of struct %s\n", 18571 mname, st_ops->name); 18572 return err; 18573 } 18574 } 18575 18576 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 18577 verbose(env, "Private stack not supported by jit\n"); 18578 return -EACCES; 18579 } 18580 18581 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) { 18582 if (st_ops_desc->arg_info[member_idx].info[i].refcounted) { 18583 has_refcounted_arg = true; 18584 break; 18585 } 18586 } 18587 18588 /* Tail call is not allowed for programs with refcounted arguments since we 18589 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 18590 */ 18591 for (i = 0; i < env->subprog_cnt; i++) { 18592 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 18593 verbose(env, "program with __ref argument cannot tail call\n"); 18594 return -EINVAL; 18595 } 18596 } 18597 18598 prog->aux->st_ops = st_ops; 18599 prog->aux->attach_st_ops_member_off = member_off; 18600 18601 prog->aux->attach_func_proto = func_proto; 18602 prog->aux->attach_func_name = mname; 18603 env->ops = st_ops->verifier_ops; 18604 18605 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info, 18606 st_ops_desc->arg_info[member_idx].cnt); 18607 } 18608 #define SECURITY_PREFIX "security_" 18609 18610 #ifdef CONFIG_FUNCTION_ERROR_INJECTION 18611 18612 /* list of non-sleepable functions that are otherwise on 18613 * ALLOW_ERROR_INJECTION list 18614 */ 18615 BTF_SET_START(btf_non_sleepable_error_inject) 18616 /* Three functions below can be called from sleepable and non-sleepable context. 18617 * Assume non-sleepable from bpf safety point of view. 18618 */ 18619 BTF_ID(func, __filemap_add_folio) 18620 #ifdef CONFIG_FAIL_PAGE_ALLOC 18621 BTF_ID(func, should_fail_alloc_page) 18622 #endif 18623 #ifdef CONFIG_FAILSLAB 18624 BTF_ID(func, should_failslab) 18625 #endif 18626 BTF_SET_END(btf_non_sleepable_error_inject) 18627 18628 static int check_non_sleepable_error_inject(u32 btf_id) 18629 { 18630 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 18631 } 18632 18633 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18634 { 18635 /* fentry/fexit/fmod_ret progs can be sleepable if they are 18636 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 18637 */ 18638 if (!check_non_sleepable_error_inject(btf_id) && 18639 within_error_injection_list(addr)) 18640 return 0; 18641 18642 return -EINVAL; 18643 } 18644 18645 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18646 { 18647 if (within_error_injection_list(addr) || 18648 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18649 return 0; 18650 18651 return -EINVAL; 18652 } 18653 18654 #else 18655 18656 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code 18657 * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name() 18658 * but that just compares two concrete function names. 18659 */ 18660 static bool has_arch_syscall_prefix(const char *func_name) 18661 { 18662 #if defined(__x86_64__) 18663 return !strncmp(func_name, "__x64_", 6); 18664 #elif defined(__i386__) 18665 return !strncmp(func_name, "__ia32_", 7); 18666 #elif defined(__s390x__) 18667 return !strncmp(func_name, "__s390x_", 8); 18668 #elif defined(__aarch64__) 18669 return !strncmp(func_name, "__arm64_", 8); 18670 #elif defined(__riscv) 18671 return !strncmp(func_name, "__riscv_", 8); 18672 #elif defined(__powerpc__) || defined(__powerpc64__) 18673 return !strncmp(func_name, "sys_", 4); 18674 #elif defined(__loongarch__) 18675 return !strncmp(func_name, "sys_", 4); 18676 #else 18677 return false; 18678 #endif 18679 } 18680 18681 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */ 18682 18683 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 18684 { 18685 if (has_arch_syscall_prefix(func_name)) 18686 return 0; 18687 18688 return -EINVAL; 18689 } 18690 18691 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18692 { 18693 if (has_arch_syscall_prefix(func_name) || 18694 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18695 return 0; 18696 18697 return -EINVAL; 18698 } 18699 18700 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */ 18701 18702 int bpf_check_attach_target(struct bpf_verifier_log *log, 18703 const struct bpf_prog *prog, 18704 const struct bpf_prog *tgt_prog, 18705 u32 btf_id, 18706 struct bpf_attach_target_info *tgt_info) 18707 { 18708 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 18709 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 18710 char trace_symbol[KSYM_SYMBOL_LEN]; 18711 const char prefix[] = "btf_trace_"; 18712 struct bpf_raw_event_map *btp; 18713 int ret = 0, subprog = -1, i; 18714 const struct btf_type *t; 18715 bool conservative = true; 18716 const char *tname, *fname; 18717 struct btf *btf; 18718 long addr = 0; 18719 struct module *mod = NULL; 18720 18721 if (!btf_id) { 18722 bpf_log(log, "Tracing programs must provide btf_id\n"); 18723 return -EINVAL; 18724 } 18725 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 18726 if (!btf) { 18727 bpf_log(log, 18728 "Tracing program can only be attached to another program annotated with BTF\n"); 18729 return -EINVAL; 18730 } 18731 t = btf_type_by_id(btf, btf_id); 18732 if (!t) { 18733 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 18734 return -EINVAL; 18735 } 18736 tname = btf_name_by_offset(btf, t->name_off); 18737 if (!tname) { 18738 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 18739 return -EINVAL; 18740 } 18741 if (tgt_prog) { 18742 struct bpf_prog_aux *aux = tgt_prog->aux; 18743 bool tgt_changes_pkt_data; 18744 bool tgt_might_sleep; 18745 18746 if (bpf_prog_is_dev_bound(prog->aux) && 18747 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 18748 bpf_log(log, "Target program bound device mismatch"); 18749 return -EINVAL; 18750 } 18751 18752 for (i = 0; i < aux->func_info_cnt; i++) 18753 if (aux->func_info[i].type_id == btf_id) { 18754 subprog = i; 18755 break; 18756 } 18757 if (subprog == -1) { 18758 bpf_log(log, "Subprog %s doesn't exist\n", tname); 18759 return -EINVAL; 18760 } 18761 if (aux->func && aux->func[subprog]->aux->exception_cb) { 18762 bpf_log(log, 18763 "%s programs cannot attach to exception callback\n", 18764 prog_extension ? "Extension" : "Tracing"); 18765 return -EINVAL; 18766 } 18767 conservative = aux->func_info_aux[subprog].unreliable; 18768 if (prog_extension) { 18769 if (conservative) { 18770 bpf_log(log, 18771 "Cannot replace static functions\n"); 18772 return -EINVAL; 18773 } 18774 if (!prog->jit_requested) { 18775 bpf_log(log, 18776 "Extension programs should be JITed\n"); 18777 return -EINVAL; 18778 } 18779 tgt_changes_pkt_data = aux->func 18780 ? aux->func[subprog]->aux->changes_pkt_data 18781 : aux->changes_pkt_data; 18782 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 18783 bpf_log(log, 18784 "Extension program changes packet data, while original does not\n"); 18785 return -EINVAL; 18786 } 18787 18788 tgt_might_sleep = aux->func 18789 ? aux->func[subprog]->aux->might_sleep 18790 : aux->might_sleep; 18791 if (prog->aux->might_sleep && !tgt_might_sleep) { 18792 bpf_log(log, 18793 "Extension program may sleep, while original does not\n"); 18794 return -EINVAL; 18795 } 18796 } 18797 if (!tgt_prog->jited) { 18798 bpf_log(log, "Can attach to only JITed progs\n"); 18799 return -EINVAL; 18800 } 18801 if (prog_tracing) { 18802 if (aux->attach_tracing_prog) { 18803 /* 18804 * Target program is an fentry/fexit which is already attached 18805 * to another tracing program. More levels of nesting 18806 * attachment are not allowed. 18807 */ 18808 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 18809 return -EINVAL; 18810 } 18811 } else if (tgt_prog->type == prog->type) { 18812 /* 18813 * To avoid potential call chain cycles, prevent attaching of a 18814 * program extension to another extension. It's ok to attach 18815 * fentry/fexit to extension program. 18816 */ 18817 bpf_log(log, "Cannot recursively attach\n"); 18818 return -EINVAL; 18819 } 18820 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 18821 prog_extension && 18822 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 18823 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT || 18824 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION)) { 18825 /* Program extensions can extend all program types 18826 * except fentry/fexit. The reason is the following. 18827 * The fentry/fexit programs are used for performance 18828 * analysis, stats and can be attached to any program 18829 * type. When extension program is replacing XDP function 18830 * it is necessary to allow performance analysis of all 18831 * functions. Both original XDP program and its program 18832 * extension. Hence attaching fentry/fexit to 18833 * BPF_PROG_TYPE_EXT is allowed. If extending of 18834 * fentry/fexit was allowed it would be possible to create 18835 * long call chain fentry->extension->fentry->extension 18836 * beyond reasonable stack size. Hence extending fentry 18837 * is not allowed. 18838 */ 18839 bpf_log(log, "Cannot extend fentry/fexit/fsession\n"); 18840 return -EINVAL; 18841 } 18842 } else { 18843 if (prog_extension) { 18844 bpf_log(log, "Cannot replace kernel functions\n"); 18845 return -EINVAL; 18846 } 18847 } 18848 18849 switch (prog->expected_attach_type) { 18850 case BPF_TRACE_RAW_TP: 18851 if (tgt_prog) { 18852 bpf_log(log, 18853 "Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n"); 18854 return -EINVAL; 18855 } 18856 if (!btf_type_is_typedef(t)) { 18857 bpf_log(log, "attach_btf_id %u is not a typedef\n", 18858 btf_id); 18859 return -EINVAL; 18860 } 18861 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 18862 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 18863 btf_id, tname); 18864 return -EINVAL; 18865 } 18866 tname += sizeof(prefix) - 1; 18867 18868 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 18869 * names. Thus using bpf_raw_event_map to get argument names. 18870 */ 18871 btp = bpf_get_raw_tracepoint(tname); 18872 if (!btp) 18873 return -EINVAL; 18874 if (prog->sleepable && !tracepoint_is_faultable(btp->tp)) { 18875 bpf_log(log, "Sleepable program cannot attach to non-faultable tracepoint %s\n", 18876 tname); 18877 bpf_put_raw_tracepoint(btp); 18878 return -EINVAL; 18879 } 18880 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 18881 trace_symbol); 18882 bpf_put_raw_tracepoint(btp); 18883 18884 if (fname) 18885 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 18886 18887 if (!fname || ret < 0) { 18888 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 18889 prefix, tname); 18890 t = btf_type_by_id(btf, t->type); 18891 if (!btf_type_is_ptr(t)) 18892 /* should never happen in valid vmlinux build */ 18893 return -EINVAL; 18894 } else { 18895 t = btf_type_by_id(btf, ret); 18896 if (!btf_type_is_func(t)) 18897 /* should never happen in valid vmlinux build */ 18898 return -EINVAL; 18899 } 18900 18901 t = btf_type_by_id(btf, t->type); 18902 if (!btf_type_is_func_proto(t)) 18903 /* should never happen in valid vmlinux build */ 18904 return -EINVAL; 18905 18906 break; 18907 case BPF_TRACE_ITER: 18908 if (!btf_type_is_func(t)) { 18909 bpf_log(log, "attach_btf_id %u is not a function\n", 18910 btf_id); 18911 return -EINVAL; 18912 } 18913 t = btf_type_by_id(btf, t->type); 18914 if (!btf_type_is_func_proto(t)) 18915 return -EINVAL; 18916 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 18917 if (ret) 18918 return ret; 18919 break; 18920 default: 18921 if (!prog_extension) 18922 return -EINVAL; 18923 fallthrough; 18924 case BPF_MODIFY_RETURN: 18925 case BPF_LSM_MAC: 18926 case BPF_LSM_CGROUP: 18927 case BPF_TRACE_FENTRY: 18928 case BPF_TRACE_FEXIT: 18929 case BPF_TRACE_FSESSION: 18930 if (prog->expected_attach_type == BPF_TRACE_FSESSION && 18931 !bpf_jit_supports_fsession()) { 18932 bpf_log(log, "JIT does not support fsession\n"); 18933 return -EOPNOTSUPP; 18934 } 18935 if (!btf_type_is_func(t)) { 18936 bpf_log(log, "attach_btf_id %u is not a function\n", 18937 btf_id); 18938 return -EINVAL; 18939 } 18940 if (prog_extension && 18941 btf_check_type_match(log, prog, btf, t)) 18942 return -EINVAL; 18943 t = btf_type_by_id(btf, t->type); 18944 if (!btf_type_is_func_proto(t)) 18945 return -EINVAL; 18946 18947 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 18948 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 18949 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 18950 return -EINVAL; 18951 18952 if (tgt_prog && conservative) 18953 t = NULL; 18954 18955 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 18956 if (ret < 0) 18957 return ret; 18958 18959 if (tgt_prog) { 18960 if (subprog == 0) 18961 addr = (long) tgt_prog->bpf_func; 18962 else 18963 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 18964 } else { 18965 if (btf_is_module(btf)) { 18966 mod = btf_try_get_module(btf); 18967 if (mod) 18968 addr = find_kallsyms_symbol_value(mod, tname); 18969 else 18970 addr = 0; 18971 } else { 18972 addr = kallsyms_lookup_name(tname); 18973 } 18974 if (!addr) { 18975 module_put(mod); 18976 bpf_log(log, 18977 "The address of function %s cannot be found\n", 18978 tname); 18979 return -ENOENT; 18980 } 18981 } 18982 18983 if (prog->sleepable) { 18984 ret = -EINVAL; 18985 switch (prog->type) { 18986 case BPF_PROG_TYPE_TRACING: 18987 if (!check_attach_sleepable(btf_id, addr, tname)) 18988 ret = 0; 18989 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 18990 * in the fmodret id set with the KF_SLEEPABLE flag. 18991 */ 18992 else { 18993 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 18994 prog); 18995 18996 if (flags && (*flags & KF_SLEEPABLE)) 18997 ret = 0; 18998 } 18999 break; 19000 case BPF_PROG_TYPE_LSM: 19001 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 19002 * Only some of them are sleepable. 19003 */ 19004 if (bpf_lsm_is_sleepable_hook(btf_id)) 19005 ret = 0; 19006 break; 19007 default: 19008 break; 19009 } 19010 if (ret) { 19011 module_put(mod); 19012 bpf_log(log, "%s is not sleepable\n", tname); 19013 return ret; 19014 } 19015 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19016 if (tgt_prog) { 19017 module_put(mod); 19018 bpf_log(log, "can't modify return codes of BPF programs\n"); 19019 return -EINVAL; 19020 } 19021 ret = -EINVAL; 19022 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19023 !check_attach_modify_return(addr, tname)) 19024 ret = 0; 19025 if (ret) { 19026 module_put(mod); 19027 bpf_log(log, "%s() is not modifiable\n", tname); 19028 return ret; 19029 } 19030 } 19031 19032 break; 19033 } 19034 tgt_info->tgt_addr = addr; 19035 tgt_info->tgt_name = tname; 19036 tgt_info->tgt_type = t; 19037 tgt_info->tgt_mod = mod; 19038 return 0; 19039 } 19040 19041 BTF_SET_START(btf_id_deny) 19042 BTF_ID_UNUSED 19043 #ifdef CONFIG_SMP 19044 BTF_ID(func, ___migrate_enable) 19045 BTF_ID(func, migrate_disable) 19046 BTF_ID(func, migrate_enable) 19047 #endif 19048 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19049 BTF_ID(func, rcu_read_unlock_strict) 19050 #endif 19051 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19052 BTF_ID(func, preempt_count_add) 19053 BTF_ID(func, preempt_count_sub) 19054 #endif 19055 #ifdef CONFIG_PREEMPT_RCU 19056 BTF_ID(func, __rcu_read_lock) 19057 BTF_ID(func, __rcu_read_unlock) 19058 #endif 19059 BTF_SET_END(btf_id_deny) 19060 19061 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 19062 * Currently, we must manually list all __noreturn functions here. Once a more 19063 * robust solution is implemented, this workaround can be removed. 19064 */ 19065 BTF_SET_START(noreturn_deny) 19066 #ifdef CONFIG_IA32_EMULATION 19067 BTF_ID(func, __ia32_sys_exit) 19068 BTF_ID(func, __ia32_sys_exit_group) 19069 #endif 19070 #ifdef CONFIG_KUNIT 19071 BTF_ID(func, __kunit_abort) 19072 BTF_ID(func, kunit_try_catch_throw) 19073 #endif 19074 #ifdef CONFIG_MODULES 19075 BTF_ID(func, __module_put_and_kthread_exit) 19076 #endif 19077 #ifdef CONFIG_X86_64 19078 BTF_ID(func, __x64_sys_exit) 19079 BTF_ID(func, __x64_sys_exit_group) 19080 #endif 19081 BTF_ID(func, do_exit) 19082 BTF_ID(func, do_group_exit) 19083 BTF_ID(func, kthread_complete_and_exit) 19084 BTF_ID(func, make_task_dead) 19085 BTF_SET_END(noreturn_deny) 19086 19087 static bool can_be_sleepable(struct bpf_prog *prog) 19088 { 19089 if (prog->type == BPF_PROG_TYPE_TRACING) { 19090 switch (prog->expected_attach_type) { 19091 case BPF_TRACE_FENTRY: 19092 case BPF_TRACE_FEXIT: 19093 case BPF_MODIFY_RETURN: 19094 case BPF_TRACE_ITER: 19095 case BPF_TRACE_FSESSION: 19096 case BPF_TRACE_RAW_TP: 19097 return true; 19098 default: 19099 return false; 19100 } 19101 } 19102 return prog->type == BPF_PROG_TYPE_LSM || 19103 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 19104 prog->type == BPF_PROG_TYPE_STRUCT_OPS || 19105 prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT || 19106 prog->type == BPF_PROG_TYPE_TRACEPOINT; 19107 } 19108 19109 static int check_attach_btf_id(struct bpf_verifier_env *env) 19110 { 19111 struct bpf_prog *prog = env->prog; 19112 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 19113 struct bpf_attach_target_info tgt_info = {}; 19114 u32 btf_id = prog->aux->attach_btf_id; 19115 struct bpf_trampoline *tr; 19116 int ret; 19117 u64 key; 19118 19119 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 19120 if (prog->sleepable) 19121 /* attach_btf_id checked to be zero already */ 19122 return 0; 19123 verbose(env, "Syscall programs can only be sleepable\n"); 19124 return -EINVAL; 19125 } 19126 19127 if (prog->sleepable && !can_be_sleepable(prog)) { 19128 verbose(env, "Program of this type cannot be sleepable\n"); 19129 return -EINVAL; 19130 } 19131 19132 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 19133 return check_struct_ops_btf_id(env); 19134 19135 if (prog->type != BPF_PROG_TYPE_TRACING && 19136 prog->type != BPF_PROG_TYPE_LSM && 19137 prog->type != BPF_PROG_TYPE_EXT) 19138 return 0; 19139 19140 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 19141 if (ret) 19142 return ret; 19143 19144 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 19145 /* to make freplace equivalent to their targets, they need to 19146 * inherit env->ops and expected_attach_type for the rest of the 19147 * verification 19148 */ 19149 env->ops = bpf_verifier_ops[tgt_prog->type]; 19150 prog->expected_attach_type = tgt_prog->expected_attach_type; 19151 } 19152 19153 /* store info about the attachment target that will be used later */ 19154 prog->aux->attach_func_proto = tgt_info.tgt_type; 19155 prog->aux->attach_func_name = tgt_info.tgt_name; 19156 prog->aux->mod = tgt_info.tgt_mod; 19157 19158 if (tgt_prog) { 19159 prog->aux->saved_dst_prog_type = tgt_prog->type; 19160 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 19161 } 19162 19163 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 19164 prog->aux->attach_btf_trace = true; 19165 return 0; 19166 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 19167 return bpf_iter_prog_supported(prog); 19168 } 19169 19170 if (prog->type == BPF_PROG_TYPE_LSM) { 19171 ret = bpf_lsm_verify_prog(&env->log, prog); 19172 if (ret < 0) 19173 return ret; 19174 } else if (prog->type == BPF_PROG_TYPE_TRACING && 19175 btf_id_set_contains(&btf_id_deny, btf_id)) { 19176 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 19177 tgt_info.tgt_name); 19178 return -EINVAL; 19179 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 19180 prog->expected_attach_type == BPF_TRACE_FSESSION || 19181 prog->expected_attach_type == BPF_MODIFY_RETURN) && 19182 btf_id_set_contains(&noreturn_deny, btf_id)) { 19183 verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n", 19184 tgt_info.tgt_name); 19185 return -EINVAL; 19186 } 19187 19188 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 19189 tr = bpf_trampoline_get(key, &tgt_info); 19190 if (!tr) 19191 return -ENOMEM; 19192 19193 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 19194 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 19195 19196 prog->aux->dst_trampoline = tr; 19197 return 0; 19198 } 19199 19200 struct btf *bpf_get_btf_vmlinux(void) 19201 { 19202 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 19203 mutex_lock(&bpf_verifier_lock); 19204 if (!btf_vmlinux) 19205 btf_vmlinux = btf_parse_vmlinux(); 19206 mutex_unlock(&bpf_verifier_lock); 19207 } 19208 return btf_vmlinux; 19209 } 19210 19211 /* 19212 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 19213 * this case expect that every file descriptor in the array is either a map or 19214 * a BTF. Everything else is considered to be trash. 19215 */ 19216 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) 19217 { 19218 struct bpf_map *map; 19219 struct btf *btf; 19220 CLASS(fd, f)(fd); 19221 int err; 19222 19223 map = __bpf_map_get(f); 19224 if (!IS_ERR(map)) { 19225 err = __add_used_map(env, map); 19226 if (err < 0) 19227 return err; 19228 return 0; 19229 } 19230 19231 btf = __btf_get_by_fd(f); 19232 if (!IS_ERR(btf)) { 19233 btf_get(btf); 19234 return __add_used_btf(env, btf); 19235 } 19236 19237 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 19238 return PTR_ERR(map); 19239 } 19240 19241 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr) 19242 { 19243 size_t size = sizeof(int); 19244 int ret; 19245 int fd; 19246 u32 i; 19247 19248 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 19249 19250 /* 19251 * The only difference between old (no fd_array_cnt is given) and new 19252 * APIs is that in the latter case the fd_array is expected to be 19253 * continuous and is scanned for map fds right away 19254 */ 19255 if (!attr->fd_array_cnt) 19256 return 0; 19257 19258 /* Check for integer overflow */ 19259 if (attr->fd_array_cnt >= (U32_MAX / size)) { 19260 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt); 19261 return -EINVAL; 19262 } 19263 19264 for (i = 0; i < attr->fd_array_cnt; i++) { 19265 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size)) 19266 return -EFAULT; 19267 19268 ret = add_fd_from_fd_array(env, fd); 19269 if (ret) 19270 return ret; 19271 } 19272 19273 return 0; 19274 } 19275 19276 /* replace a generic kfunc with a specialized version if necessary */ 19277 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx) 19278 { 19279 struct bpf_prog *prog = env->prog; 19280 bool seen_direct_write; 19281 void *xdp_kfunc; 19282 bool is_rdonly; 19283 u32 func_id = desc->func_id; 19284 u16 offset = desc->offset; 19285 unsigned long addr = desc->addr; 19286 19287 if (offset) /* return if module BTF is used */ 19288 return 0; 19289 19290 if (bpf_dev_bound_kfunc_id(func_id)) { 19291 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19292 if (xdp_kfunc) 19293 addr = (unsigned long)xdp_kfunc; 19294 /* fallback to default kfunc when not supported by netdev */ 19295 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19296 seen_direct_write = env->seen_direct_write; 19297 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19298 19299 if (is_rdonly) 19300 addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19301 19302 /* restore env->seen_direct_write to its original value, since 19303 * may_access_direct_pkt_data mutates it 19304 */ 19305 env->seen_direct_write = seen_direct_write; 19306 } else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) { 19307 if (bpf_lsm_has_d_inode_locked(prog)) 19308 addr = (unsigned long)bpf_set_dentry_xattr_locked; 19309 } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) { 19310 if (bpf_lsm_has_d_inode_locked(prog)) 19311 addr = (unsigned long)bpf_remove_dentry_xattr_locked; 19312 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 19313 if (!env->insn_aux_data[insn_idx].non_sleepable) 19314 addr = (unsigned long)bpf_dynptr_from_file_sleepable; 19315 } else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) { 19316 if (env->insn_aux_data[insn_idx].non_sleepable) 19317 addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable; 19318 } else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) { 19319 if (env->insn_aux_data[insn_idx].non_sleepable) 19320 addr = (unsigned long)bpf_arena_free_pages_non_sleepable; 19321 } 19322 desc->addr = addr; 19323 return 0; 19324 } 19325 19326 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19327 u16 struct_meta_reg, 19328 u16 node_offset_reg, 19329 struct bpf_insn *insn, 19330 struct bpf_insn *insn_buf, 19331 int *cnt) 19332 { 19333 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19334 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19335 19336 insn_buf[0] = addr[0]; 19337 insn_buf[1] = addr[1]; 19338 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19339 insn_buf[3] = *insn; 19340 *cnt = 4; 19341 } 19342 19343 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19344 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19345 { 19346 struct bpf_kfunc_desc *desc; 19347 int err; 19348 19349 if (!insn->imm) { 19350 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19351 return -EINVAL; 19352 } 19353 19354 *cnt = 0; 19355 19356 /* insn->imm has the btf func_id. Replace it with an offset relative to 19357 * __bpf_call_base, unless the JIT needs to call functions that are 19358 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19359 */ 19360 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19361 if (!desc) { 19362 verifier_bug(env, "kernel function descriptor not found for func_id %u", 19363 insn->imm); 19364 return -EFAULT; 19365 } 19366 19367 err = specialize_kfunc(env, desc, insn_idx); 19368 if (err) 19369 return err; 19370 19371 if (!bpf_jit_supports_far_kfunc_call()) 19372 insn->imm = BPF_CALL_IMM(desc->addr); 19373 19374 if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) { 19375 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19376 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19377 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19378 19379 if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) { 19380 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19381 insn_idx); 19382 return -EFAULT; 19383 } 19384 19385 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19386 insn_buf[1] = addr[0]; 19387 insn_buf[2] = addr[1]; 19388 insn_buf[3] = *insn; 19389 *cnt = 4; 19390 } else if (is_bpf_obj_drop_kfunc(desc->func_id) || 19391 is_bpf_percpu_obj_drop_kfunc(desc->func_id) || 19392 is_bpf_refcount_acquire_kfunc(desc->func_id)) { 19393 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19394 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19395 19396 if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) { 19397 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19398 insn_idx); 19399 return -EFAULT; 19400 } 19401 19402 if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) { 19403 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19404 insn_idx); 19405 return -EFAULT; 19406 } 19407 19408 insn_buf[0] = addr[0]; 19409 insn_buf[1] = addr[1]; 19410 insn_buf[2] = *insn; 19411 *cnt = 3; 19412 } else if (is_bpf_list_push_kfunc(desc->func_id) || 19413 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19414 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19415 int struct_meta_reg = BPF_REG_3; 19416 int node_offset_reg = BPF_REG_4; 19417 19418 /* list_add/rbtree_add have an extra arg (prev/less), 19419 * so args-to-fixup are in diff regs. 19420 */ 19421 if (desc->func_id == special_kfunc_list[KF_bpf_list_add] || 19422 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19423 struct_meta_reg = BPF_REG_4; 19424 node_offset_reg = BPF_REG_5; 19425 } 19426 19427 if (!kptr_struct_meta) { 19428 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19429 insn_idx); 19430 return -EFAULT; 19431 } 19432 19433 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19434 node_offset_reg, insn, insn_buf, cnt); 19435 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19436 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19437 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19438 *cnt = 1; 19439 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] && 19440 env->prog->expected_attach_type == BPF_TRACE_FSESSION) { 19441 /* 19442 * inline the bpf_session_is_return() for fsession: 19443 * bool bpf_session_is_return(void *ctx) 19444 * { 19445 * return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1; 19446 * } 19447 */ 19448 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19449 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT); 19450 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1); 19451 *cnt = 3; 19452 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] && 19453 env->prog->expected_attach_type == BPF_TRACE_FSESSION) { 19454 /* 19455 * inline bpf_session_cookie() for fsession: 19456 * __u64 *bpf_session_cookie(void *ctx) 19457 * { 19458 * u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF; 19459 * return &((u64 *)ctx)[-off]; 19460 * } 19461 */ 19462 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19463 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT); 19464 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF); 19465 insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19466 insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1); 19467 insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0); 19468 *cnt = 6; 19469 } 19470 19471 if (env->insn_aux_data[insn_idx].arg_prog) { 19472 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 19473 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 19474 int idx = *cnt; 19475 19476 insn_buf[idx++] = ld_addrs[0]; 19477 insn_buf[idx++] = ld_addrs[1]; 19478 insn_buf[idx++] = *insn; 19479 *cnt = idx; 19480 } 19481 return 0; 19482 } 19483 19484 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, 19485 struct bpf_log_attr *attr_log) 19486 { 19487 u64 start_time = ktime_get_ns(); 19488 struct bpf_verifier_env *env; 19489 int i, len, ret = -EINVAL, err; 19490 bool is_priv; 19491 19492 BTF_TYPE_EMIT(enum bpf_features); 19493 19494 /* no program is valid */ 19495 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 19496 return -EINVAL; 19497 19498 /* 'struct bpf_verifier_env' can be global, but since it's not small, 19499 * allocate/free it every time bpf_check() is called 19500 */ 19501 env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT); 19502 if (!env) 19503 return -ENOMEM; 19504 19505 env->bt.env = env; 19506 19507 len = (*prog)->len; 19508 env->insn_aux_data = 19509 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 19510 ret = -ENOMEM; 19511 if (!env->insn_aux_data) 19512 goto err_free_env; 19513 for (i = 0; i < len; i++) 19514 env->insn_aux_data[i].orig_idx = i; 19515 env->succ = bpf_iarray_realloc(NULL, 2); 19516 if (!env->succ) 19517 goto err_free_env; 19518 env->prog = *prog; 19519 env->ops = bpf_verifier_ops[env->prog->type]; 19520 19521 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 19522 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 19523 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 19524 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 19525 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 19526 19527 bpf_get_btf_vmlinux(); 19528 19529 /* grab the mutex to protect few globals used by verifier */ 19530 if (!is_priv) 19531 mutex_lock(&bpf_verifier_lock); 19532 19533 /* user could have requested verbose verifier output 19534 * and supplied buffer to store the verification trace 19535 */ 19536 ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size); 19537 if (ret) 19538 goto err_unlock; 19539 19540 ret = process_fd_array(env, attr, uattr); 19541 if (ret) 19542 goto skip_full_check; 19543 19544 mark_verifier_state_clean(env); 19545 19546 if (IS_ERR(btf_vmlinux)) { 19547 /* Either gcc or pahole or kernel are broken. */ 19548 verbose(env, "in-kernel BTF is malformed\n"); 19549 ret = PTR_ERR(btf_vmlinux); 19550 goto skip_full_check; 19551 } 19552 19553 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 19554 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 19555 env->strict_alignment = true; 19556 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 19557 env->strict_alignment = false; 19558 19559 if (is_priv) 19560 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 19561 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 19562 19563 env->explored_states = kvzalloc_objs(struct list_head, 19564 state_htab_size(env), 19565 GFP_KERNEL_ACCOUNT); 19566 ret = -ENOMEM; 19567 if (!env->explored_states) 19568 goto skip_full_check; 19569 19570 for (i = 0; i < state_htab_size(env); i++) 19571 INIT_LIST_HEAD(&env->explored_states[i]); 19572 INIT_LIST_HEAD(&env->free_list); 19573 19574 ret = bpf_check_btf_info_early(env, attr, uattr); 19575 if (ret < 0) 19576 goto skip_full_check; 19577 19578 ret = add_subprog_and_kfunc(env); 19579 if (ret < 0) 19580 goto skip_full_check; 19581 19582 ret = check_subprogs(env); 19583 if (ret < 0) 19584 goto skip_full_check; 19585 19586 ret = bpf_check_btf_info(env, attr, uattr); 19587 if (ret < 0) 19588 goto skip_full_check; 19589 19590 ret = check_and_resolve_insns(env); 19591 if (ret < 0) 19592 goto skip_full_check; 19593 19594 if (bpf_prog_is_offloaded(env->prog->aux)) { 19595 ret = bpf_prog_offload_verifier_prep(env->prog); 19596 if (ret) 19597 goto skip_full_check; 19598 } 19599 19600 ret = bpf_check_cfg(env); 19601 if (ret < 0) 19602 goto skip_full_check; 19603 19604 ret = bpf_compute_postorder(env); 19605 if (ret < 0) 19606 goto skip_full_check; 19607 19608 ret = bpf_stack_liveness_init(env); 19609 if (ret) 19610 goto skip_full_check; 19611 19612 ret = check_attach_btf_id(env); 19613 if (ret) 19614 goto skip_full_check; 19615 19616 ret = bpf_compute_const_regs(env); 19617 if (ret < 0) 19618 goto skip_full_check; 19619 19620 ret = bpf_prune_dead_branches(env); 19621 if (ret < 0) 19622 goto skip_full_check; 19623 19624 ret = sort_subprogs_topo(env); 19625 if (ret < 0) 19626 goto skip_full_check; 19627 19628 ret = bpf_compute_scc(env); 19629 if (ret < 0) 19630 goto skip_full_check; 19631 19632 ret = bpf_compute_live_registers(env); 19633 if (ret < 0) 19634 goto skip_full_check; 19635 19636 ret = mark_fastcall_patterns(env); 19637 if (ret < 0) 19638 goto skip_full_check; 19639 19640 ret = do_check_main(env); 19641 ret = ret ?: do_check_subprogs(env); 19642 19643 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 19644 ret = bpf_prog_offload_finalize(env); 19645 19646 skip_full_check: 19647 kvfree(env->explored_states); 19648 19649 /* might decrease stack depth, keep it before passes that 19650 * allocate additional slots. 19651 */ 19652 if (ret == 0) 19653 ret = bpf_remove_fastcall_spills_fills(env); 19654 19655 if (ret == 0) 19656 ret = check_max_stack_depth(env); 19657 19658 /* instruction rewrites happen after this point */ 19659 if (ret == 0) 19660 ret = bpf_optimize_bpf_loop(env); 19661 19662 if (is_priv) { 19663 if (ret == 0) 19664 bpf_opt_hard_wire_dead_code_branches(env); 19665 if (ret == 0) 19666 ret = bpf_opt_remove_dead_code(env); 19667 if (ret == 0) 19668 ret = bpf_opt_remove_nops(env); 19669 } else { 19670 if (ret == 0) 19671 sanitize_dead_code(env); 19672 } 19673 19674 if (ret == 0) 19675 /* program is valid, convert *(u32*)(ctx + off) accesses */ 19676 ret = bpf_convert_ctx_accesses(env); 19677 19678 if (ret == 0) 19679 ret = bpf_do_misc_fixups(env); 19680 19681 /* do 32-bit optimization after insn patching has done so those patched 19682 * insns could be handled correctly. 19683 */ 19684 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 19685 ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr); 19686 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 19687 : false; 19688 } 19689 19690 if (ret == 0) 19691 ret = bpf_fixup_call_args(env); 19692 19693 env->verification_time = ktime_get_ns() - start_time; 19694 print_verification_stats(env); 19695 env->prog->aux->verified_insns = env->insn_processed; 19696 19697 /* preserve original error even if log finalization is successful */ 19698 err = bpf_log_attr_finalize(attr_log, &env->log); 19699 if (err) 19700 ret = err; 19701 19702 if (ret) 19703 goto err_release_maps; 19704 19705 if (env->used_map_cnt) { 19706 /* if program passed verifier, update used_maps in bpf_prog_info */ 19707 env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0], 19708 env->used_map_cnt, 19709 GFP_KERNEL_ACCOUNT); 19710 19711 if (!env->prog->aux->used_maps) { 19712 ret = -ENOMEM; 19713 goto err_release_maps; 19714 } 19715 19716 memcpy(env->prog->aux->used_maps, env->used_maps, 19717 sizeof(env->used_maps[0]) * env->used_map_cnt); 19718 env->prog->aux->used_map_cnt = env->used_map_cnt; 19719 } 19720 if (env->used_btf_cnt) { 19721 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 19722 env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0], 19723 env->used_btf_cnt, 19724 GFP_KERNEL_ACCOUNT); 19725 if (!env->prog->aux->used_btfs) { 19726 ret = -ENOMEM; 19727 goto err_release_maps; 19728 } 19729 19730 memcpy(env->prog->aux->used_btfs, env->used_btfs, 19731 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 19732 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 19733 } 19734 if (env->used_map_cnt || env->used_btf_cnt) { 19735 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 19736 * bpf_ld_imm64 instructions 19737 */ 19738 convert_pseudo_ld_imm64(env); 19739 } 19740 19741 adjust_btf_func(env); 19742 19743 /* extension progs temporarily inherit the attach_type of their targets 19744 for verification purposes, so set it back to zero before returning 19745 */ 19746 if (env->prog->type == BPF_PROG_TYPE_EXT) 19747 env->prog->expected_attach_type = 0; 19748 19749 env->prog = __bpf_prog_select_runtime(env, env->prog, &ret); 19750 19751 err_release_maps: 19752 if (ret) 19753 release_insn_arrays(env); 19754 if (!env->prog->aux->used_maps) 19755 /* if we didn't copy map pointers into bpf_prog_info, release 19756 * them now. Otherwise free_used_maps() will release them. 19757 */ 19758 release_maps(env); 19759 if (!env->prog->aux->used_btfs) 19760 release_btfs(env); 19761 19762 *prog = env->prog; 19763 19764 module_put(env->attach_btf_mod); 19765 err_unlock: 19766 if (!is_priv) 19767 mutex_unlock(&bpf_verifier_lock); 19768 bpf_clear_insn_aux_data(env, 0, env->prog->len); 19769 vfree(env->insn_aux_data); 19770 err_free_env: 19771 bpf_stack_liveness_free(env); 19772 kvfree(env->cfg.insn_postorder); 19773 kvfree(env->scc_info); 19774 kvfree(env->succ); 19775 kvfree(env->gotox_tmp_buf); 19776 kvfree(env); 19777 return ret; 19778 } 19779