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/bpf_mem_alloc.h> 30 #include <net/xdp.h> 31 #include <linux/trace_events.h> 32 #include <linux/kallsyms.h> 33 34 #include "disasm.h" 35 36 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 37 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 38 [_id] = & _name ## _verifier_ops, 39 #define BPF_MAP_TYPE(_id, _ops) 40 #define BPF_LINK_TYPE(_id, _name) 41 #include <linux/bpf_types.h> 42 #undef BPF_PROG_TYPE 43 #undef BPF_MAP_TYPE 44 #undef BPF_LINK_TYPE 45 }; 46 47 enum bpf_features { 48 BPF_FEAT_RDONLY_CAST_TO_VOID = 0, 49 BPF_FEAT_STREAMS = 1, 50 __MAX_BPF_FEAT, 51 }; 52 53 struct bpf_mem_alloc bpf_global_percpu_ma; 54 static bool bpf_global_percpu_ma_set; 55 56 /* bpf_check() is a static code analyzer that walks eBPF program 57 * instruction by instruction and updates register/stack state. 58 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 59 * 60 * The first pass is depth-first-search to check that the program is a DAG. 61 * It rejects the following programs: 62 * - larger than BPF_MAXINSNS insns 63 * - if loop is present (detected via back-edge) 64 * - unreachable insns exist (shouldn't be a forest. program = one function) 65 * - out of bounds or malformed jumps 66 * The second pass is all possible path descent from the 1st insn. 67 * Since it's analyzing all paths through the program, the length of the 68 * analysis is limited to 64k insn, which may be hit even if total number of 69 * insn is less then 4K, but there are too many branches that change stack/regs. 70 * Number of 'branches to be analyzed' is limited to 1k 71 * 72 * On entry to each instruction, each register has a type, and the instruction 73 * changes the types of the registers depending on instruction semantics. 74 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 75 * copied to R1. 76 * 77 * All registers are 64-bit. 78 * R0 - return register 79 * R1-R5 argument passing registers 80 * R6-R9 callee saved registers 81 * R10 - frame pointer read-only 82 * 83 * At the start of BPF program the register R1 contains a pointer to bpf_context 84 * and has type PTR_TO_CTX. 85 * 86 * Verifier tracks arithmetic operations on pointers in case: 87 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 88 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 89 * 1st insn copies R10 (which has FRAME_PTR) type into R1 90 * and 2nd arithmetic instruction is pattern matched to recognize 91 * that it wants to construct a pointer to some element within stack. 92 * So after 2nd insn, the register R1 has type PTR_TO_STACK 93 * (and -20 constant is saved for further stack bounds checking). 94 * Meaning that this reg is a pointer to stack plus known immediate constant. 95 * 96 * Most of the time the registers have SCALAR_VALUE type, which 97 * means the register has some value, but it's not a valid pointer. 98 * (like pointer plus pointer becomes SCALAR_VALUE type) 99 * 100 * When verifier sees load or store instructions the type of base register 101 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 102 * four pointer types recognized by check_mem_access() function. 103 * 104 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 105 * and the range of [ptr, ptr + map's value_size) is accessible. 106 * 107 * registers used to pass values to function calls are checked against 108 * function argument constraints. 109 * 110 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 111 * It means that the register type passed to this function must be 112 * PTR_TO_STACK and it will be used inside the function as 113 * 'pointer to map element key' 114 * 115 * For example the argument constraints for bpf_map_lookup_elem(): 116 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 117 * .arg1_type = ARG_CONST_MAP_PTR, 118 * .arg2_type = ARG_PTR_TO_MAP_KEY, 119 * 120 * ret_type says that this function returns 'pointer to map elem value or null' 121 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 122 * 2nd argument should be a pointer to stack, which will be used inside 123 * the helper function as a pointer to map element key. 124 * 125 * On the kernel side the helper function looks like: 126 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 127 * { 128 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 129 * void *key = (void *) (unsigned long) r2; 130 * void *value; 131 * 132 * here kernel can access 'key' and 'map' pointers safely, knowing that 133 * [key, key + map->key_size) bytes are valid and were initialized on 134 * the stack of eBPF program. 135 * } 136 * 137 * Corresponding eBPF program may look like: 138 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 139 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 140 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 141 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 142 * here verifier looks at prototype of map_lookup_elem() and sees: 143 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 144 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 145 * 146 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 147 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 148 * and were initialized prior to this call. 149 * If it's ok, then verifier allows this BPF_CALL insn and looks at 150 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 151 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 152 * returns either pointer to map value or NULL. 153 * 154 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 155 * insn, the register holding that pointer in the true branch changes state to 156 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 157 * branch. See check_cond_jmp_op(). 158 * 159 * After the call R0 is set to return type of the function and registers R1-R5 160 * are set to NOT_INIT to indicate that they are no longer readable. 161 * 162 * The following reference types represent a potential reference to a kernel 163 * resource which, after first being allocated, must be checked and freed by 164 * the BPF program: 165 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 166 * 167 * When the verifier sees a helper call return a reference type, it allocates a 168 * pointer id for the reference and stores it in the current function state. 169 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 170 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 171 * passes through a NULL-check conditional. For the branch wherein the state is 172 * changed to CONST_IMM, the verifier releases the reference. 173 * 174 * For each helper function that allocates a reference, such as 175 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 176 * bpf_sk_release(). When a reference type passes into the release function, 177 * the verifier also releases the reference. If any unchecked or unreleased 178 * reference remains at the end of the program, the verifier rejects it. 179 */ 180 181 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 182 struct bpf_verifier_stack_elem { 183 /* verifier state is 'st' 184 * before processing instruction 'insn_idx' 185 * and after processing instruction 'prev_insn_idx' 186 */ 187 struct bpf_verifier_state st; 188 int insn_idx; 189 int prev_insn_idx; 190 struct bpf_verifier_stack_elem *next; 191 /* length of verifier log at the time this state was pushed on stack */ 192 u32 log_pos; 193 }; 194 195 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 196 #define BPF_COMPLEXITY_LIMIT_STATES 64 197 198 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 199 200 #define BPF_PRIV_STACK_MIN_SIZE 64 201 202 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx); 203 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id); 204 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 205 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 206 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 207 static int ref_set_non_owning(struct bpf_verifier_env *env, 208 struct bpf_reg_state *reg); 209 static bool is_trusted_reg(const struct bpf_reg_state *reg); 210 static inline bool in_sleepable_context(struct bpf_verifier_env *env); 211 static const char *non_sleepable_context_description(struct bpf_verifier_env *env); 212 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 213 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, struct bpf_reg_state *src_reg); 214 215 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 216 struct bpf_map *map, 217 bool unpriv, bool poison) 218 { 219 unpriv |= bpf_map_ptr_unpriv(aux); 220 aux->map_ptr_state.unpriv = unpriv; 221 aux->map_ptr_state.poison = poison; 222 aux->map_ptr_state.map_ptr = map; 223 } 224 225 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 226 { 227 bool poisoned = bpf_map_key_poisoned(aux); 228 229 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 230 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 231 } 232 233 struct bpf_call_arg_meta { 234 struct bpf_map_desc map; 235 bool raw_mode; 236 bool pkt_access; 237 u8 release_regno; 238 int regno; 239 int access_size; 240 int mem_size; 241 u64 msize_max_value; 242 int ref_obj_id; 243 int dynptr_id; 244 int func_id; 245 struct btf *btf; 246 u32 btf_id; 247 struct btf *ret_btf; 248 u32 ret_btf_id; 249 u32 subprogno; 250 struct btf_field *kptr_field; 251 s64 const_map_key; 252 }; 253 254 struct bpf_kfunc_meta { 255 struct btf *btf; 256 const struct btf_type *proto; 257 const char *name; 258 const u32 *flags; 259 s32 id; 260 }; 261 262 struct btf *btf_vmlinux; 263 264 static const char *btf_type_name(const struct btf *btf, u32 id) 265 { 266 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 267 } 268 269 static DEFINE_MUTEX(bpf_verifier_lock); 270 static DEFINE_MUTEX(bpf_percpu_ma_lock); 271 272 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 273 { 274 struct bpf_verifier_env *env = private_data; 275 va_list args; 276 277 if (!bpf_verifier_log_needed(&env->log)) 278 return; 279 280 va_start(args, fmt); 281 bpf_verifier_vlog(&env->log, fmt, args); 282 va_end(args); 283 } 284 285 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 286 struct bpf_reg_state *reg, 287 struct bpf_retval_range range, const char *ctx, 288 const char *reg_name) 289 { 290 bool unknown = true; 291 292 verbose(env, "%s the register %s has", ctx, reg_name); 293 if (reg->smin_value > S64_MIN) { 294 verbose(env, " smin=%lld", reg->smin_value); 295 unknown = false; 296 } 297 if (reg->smax_value < S64_MAX) { 298 verbose(env, " smax=%lld", reg->smax_value); 299 unknown = false; 300 } 301 if (unknown) 302 verbose(env, " unknown scalar value"); 303 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 304 } 305 306 static bool reg_not_null(const struct bpf_reg_state *reg) 307 { 308 enum bpf_reg_type type; 309 310 type = reg->type; 311 if (type_may_be_null(type)) 312 return false; 313 314 type = base_type(type); 315 return type == PTR_TO_SOCKET || 316 type == PTR_TO_TCP_SOCK || 317 type == PTR_TO_MAP_VALUE || 318 type == PTR_TO_MAP_KEY || 319 type == PTR_TO_SOCK_COMMON || 320 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 321 (type == PTR_TO_MEM && !(reg->type & PTR_UNTRUSTED)) || 322 type == CONST_PTR_TO_MAP; 323 } 324 325 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 326 { 327 struct btf_record *rec = NULL; 328 struct btf_struct_meta *meta; 329 330 if (reg->type == PTR_TO_MAP_VALUE) { 331 rec = reg->map_ptr->record; 332 } else if (type_is_ptr_alloc_obj(reg->type)) { 333 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 334 if (meta) 335 rec = meta->record; 336 } 337 return rec; 338 } 339 340 bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog) 341 { 342 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 343 344 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 345 } 346 347 static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog) 348 { 349 const struct btf_type *type, *func, *func_proto; 350 const struct btf *btf = env->prog->aux->btf; 351 u32 btf_id; 352 353 btf_id = env->prog->aux->func_info[subprog].type_id; 354 355 func = btf_type_by_id(btf, btf_id); 356 if (verifier_bug_if(!func, env, "btf_id %u not found", btf_id)) 357 return false; 358 359 func_proto = btf_type_by_id(btf, func->type); 360 if (!func_proto) 361 return false; 362 363 type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 364 if (!type) 365 return false; 366 367 return btf_type_is_void(type); 368 } 369 370 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 371 { 372 struct bpf_func_info *info; 373 374 if (!env->prog->aux->func_info) 375 return ""; 376 377 info = &env->prog->aux->func_info[subprog]; 378 return btf_type_name(env->prog->aux->btf, info->type_id); 379 } 380 381 void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 382 { 383 struct bpf_subprog_info *info = subprog_info(env, subprog); 384 385 info->is_cb = true; 386 info->is_async_cb = true; 387 info->is_exception_cb = true; 388 } 389 390 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 391 { 392 return subprog_info(env, subprog)->is_exception_cb; 393 } 394 395 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 396 { 397 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK); 398 } 399 400 static bool type_is_rdonly_mem(u32 type) 401 { 402 return type & MEM_RDONLY; 403 } 404 405 static bool is_acquire_function(enum bpf_func_id func_id, 406 const struct bpf_map *map) 407 { 408 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 409 410 if (func_id == BPF_FUNC_sk_lookup_tcp || 411 func_id == BPF_FUNC_sk_lookup_udp || 412 func_id == BPF_FUNC_skc_lookup_tcp || 413 func_id == BPF_FUNC_ringbuf_reserve || 414 func_id == BPF_FUNC_kptr_xchg) 415 return true; 416 417 if (func_id == BPF_FUNC_map_lookup_elem && 418 (map_type == BPF_MAP_TYPE_SOCKMAP || 419 map_type == BPF_MAP_TYPE_SOCKHASH)) 420 return true; 421 422 return false; 423 } 424 425 static bool is_ptr_cast_function(enum bpf_func_id func_id) 426 { 427 return func_id == BPF_FUNC_tcp_sock || 428 func_id == BPF_FUNC_sk_fullsock || 429 func_id == BPF_FUNC_skc_to_tcp_sock || 430 func_id == BPF_FUNC_skc_to_tcp6_sock || 431 func_id == BPF_FUNC_skc_to_udp6_sock || 432 func_id == BPF_FUNC_skc_to_mptcp_sock || 433 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 434 func_id == BPF_FUNC_skc_to_tcp_request_sock; 435 } 436 437 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 438 { 439 return func_id == BPF_FUNC_dynptr_data; 440 } 441 442 static bool is_sync_callback_calling_kfunc(u32 btf_id); 443 static bool is_async_callback_calling_kfunc(u32 btf_id); 444 static bool is_callback_calling_kfunc(u32 btf_id); 445 446 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id); 447 static bool is_task_work_add_kfunc(u32 func_id); 448 449 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 450 { 451 return func_id == BPF_FUNC_for_each_map_elem || 452 func_id == BPF_FUNC_find_vma || 453 func_id == BPF_FUNC_loop || 454 func_id == BPF_FUNC_user_ringbuf_drain; 455 } 456 457 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 458 { 459 return func_id == BPF_FUNC_timer_set_callback; 460 } 461 462 static bool is_callback_calling_function(enum bpf_func_id func_id) 463 { 464 return is_sync_callback_calling_function(func_id) || 465 is_async_callback_calling_function(func_id); 466 } 467 468 bool bpf_is_sync_callback_calling_insn(struct bpf_insn *insn) 469 { 470 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 471 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 472 } 473 474 bool bpf_is_async_callback_calling_insn(struct bpf_insn *insn) 475 { 476 return (bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm)) || 477 (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm)); 478 } 479 480 static bool is_async_cb_sleepable(struct bpf_verifier_env *env, struct bpf_insn *insn) 481 { 482 /* bpf_timer callbacks are never sleepable. */ 483 if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_timer_set_callback) 484 return false; 485 486 /* bpf_wq and bpf_task_work callbacks are always sleepable. */ 487 if (bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 488 (is_bpf_wq_set_callback_kfunc(insn->imm) || is_task_work_add_kfunc(insn->imm))) 489 return true; 490 491 verifier_bug(env, "unhandled async callback in is_async_cb_sleepable"); 492 return false; 493 } 494 495 bool bpf_is_may_goto_insn(struct bpf_insn *insn) 496 { 497 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 498 } 499 500 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 501 const struct bpf_map *map) 502 { 503 int ref_obj_uses = 0; 504 505 if (is_ptr_cast_function(func_id)) 506 ref_obj_uses++; 507 if (is_acquire_function(func_id, map)) 508 ref_obj_uses++; 509 if (is_dynptr_ref_function(func_id)) 510 ref_obj_uses++; 511 512 return ref_obj_uses > 1; 513 } 514 515 516 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 517 { 518 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 519 520 /* We need to check that slots between [spi - nr_slots + 1, spi] are 521 * within [0, allocated_stack). 522 * 523 * Please note that the spi grows downwards. For example, a dynptr 524 * takes the size of two stack slots; the first slot will be at 525 * spi and the second slot will be at spi - 1. 526 */ 527 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 528 } 529 530 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 531 const char *obj_kind, int nr_slots) 532 { 533 int off, spi; 534 535 if (!tnum_is_const(reg->var_off)) { 536 verbose(env, "%s has to be at a constant offset\n", obj_kind); 537 return -EINVAL; 538 } 539 540 off = reg->var_off.value; 541 if (off % BPF_REG_SIZE) { 542 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 543 return -EINVAL; 544 } 545 546 spi = bpf_get_spi(off); 547 if (spi + 1 < nr_slots) { 548 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 549 return -EINVAL; 550 } 551 552 if (!is_spi_bounds_valid(bpf_func(env, reg), spi, nr_slots)) 553 return -ERANGE; 554 return spi; 555 } 556 557 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 558 { 559 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 560 } 561 562 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 563 { 564 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 565 } 566 567 static int irq_flag_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 568 { 569 return stack_slot_obj_get_spi(env, reg, "irq_flag", 1); 570 } 571 572 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 573 { 574 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 575 case DYNPTR_TYPE_LOCAL: 576 return BPF_DYNPTR_TYPE_LOCAL; 577 case DYNPTR_TYPE_RINGBUF: 578 return BPF_DYNPTR_TYPE_RINGBUF; 579 case DYNPTR_TYPE_SKB: 580 return BPF_DYNPTR_TYPE_SKB; 581 case DYNPTR_TYPE_XDP: 582 return BPF_DYNPTR_TYPE_XDP; 583 case DYNPTR_TYPE_SKB_META: 584 return BPF_DYNPTR_TYPE_SKB_META; 585 case DYNPTR_TYPE_FILE: 586 return BPF_DYNPTR_TYPE_FILE; 587 default: 588 return BPF_DYNPTR_TYPE_INVALID; 589 } 590 } 591 592 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 593 { 594 switch (type) { 595 case BPF_DYNPTR_TYPE_LOCAL: 596 return DYNPTR_TYPE_LOCAL; 597 case BPF_DYNPTR_TYPE_RINGBUF: 598 return DYNPTR_TYPE_RINGBUF; 599 case BPF_DYNPTR_TYPE_SKB: 600 return DYNPTR_TYPE_SKB; 601 case BPF_DYNPTR_TYPE_XDP: 602 return DYNPTR_TYPE_XDP; 603 case BPF_DYNPTR_TYPE_SKB_META: 604 return DYNPTR_TYPE_SKB_META; 605 case BPF_DYNPTR_TYPE_FILE: 606 return DYNPTR_TYPE_FILE; 607 default: 608 return 0; 609 } 610 } 611 612 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 613 { 614 return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE; 615 } 616 617 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 618 enum bpf_dynptr_type type, 619 bool first_slot, int dynptr_id); 620 621 622 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 623 struct bpf_reg_state *sreg1, 624 struct bpf_reg_state *sreg2, 625 enum bpf_dynptr_type type) 626 { 627 int id = ++env->id_gen; 628 629 __mark_dynptr_reg(sreg1, type, true, id); 630 __mark_dynptr_reg(sreg2, type, false, id); 631 } 632 633 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 634 struct bpf_reg_state *reg, 635 enum bpf_dynptr_type type) 636 { 637 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 638 } 639 640 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 641 struct bpf_func_state *state, int spi); 642 643 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 644 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 645 { 646 struct bpf_func_state *state = bpf_func(env, reg); 647 enum bpf_dynptr_type type; 648 int spi, i, err; 649 650 spi = dynptr_get_spi(env, reg); 651 if (spi < 0) 652 return spi; 653 654 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 655 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 656 * to ensure that for the following example: 657 * [d1][d1][d2][d2] 658 * spi 3 2 1 0 659 * So marking spi = 2 should lead to destruction of both d1 and d2. In 660 * case they do belong to same dynptr, second call won't see slot_type 661 * as STACK_DYNPTR and will simply skip destruction. 662 */ 663 err = destroy_if_dynptr_stack_slot(env, state, spi); 664 if (err) 665 return err; 666 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 667 if (err) 668 return err; 669 670 for (i = 0; i < BPF_REG_SIZE; i++) { 671 state->stack[spi].slot_type[i] = STACK_DYNPTR; 672 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 673 } 674 675 type = arg_to_dynptr_type(arg_type); 676 if (type == BPF_DYNPTR_TYPE_INVALID) 677 return -EINVAL; 678 679 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 680 &state->stack[spi - 1].spilled_ptr, type); 681 682 if (dynptr_type_refcounted(type)) { 683 /* The id is used to track proper releasing */ 684 int id; 685 686 if (clone_ref_obj_id) 687 id = clone_ref_obj_id; 688 else 689 id = acquire_reference(env, insn_idx); 690 691 if (id < 0) 692 return id; 693 694 state->stack[spi].spilled_ptr.ref_obj_id = id; 695 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 696 } 697 698 return 0; 699 } 700 701 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 702 { 703 int i; 704 705 for (i = 0; i < BPF_REG_SIZE; i++) { 706 state->stack[spi].slot_type[i] = STACK_INVALID; 707 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 708 } 709 710 bpf_mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 711 bpf_mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 712 } 713 714 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 715 { 716 struct bpf_func_state *state = bpf_func(env, reg); 717 int spi, ref_obj_id, i; 718 719 /* 720 * This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 721 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 722 * is safe to do directly. 723 */ 724 if (reg->type == CONST_PTR_TO_DYNPTR) { 725 verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released"); 726 return -EFAULT; 727 } 728 spi = dynptr_get_spi(env, reg); 729 if (spi < 0) 730 return spi; 731 732 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 733 invalidate_dynptr(env, state, spi); 734 return 0; 735 } 736 737 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 738 739 /* If the dynptr has a ref_obj_id, then we need to invalidate 740 * two things: 741 * 742 * 1) Any dynptrs with a matching ref_obj_id (clones) 743 * 2) Any slices derived from this dynptr. 744 */ 745 746 /* Invalidate any slices associated with this dynptr */ 747 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 748 749 /* Invalidate any dynptr clones */ 750 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 751 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 752 continue; 753 754 /* it should always be the case that if the ref obj id 755 * matches then the stack slot also belongs to a 756 * dynptr 757 */ 758 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 759 verifier_bug(env, "misconfigured ref_obj_id"); 760 return -EFAULT; 761 } 762 if (state->stack[i].spilled_ptr.dynptr.first_slot) 763 invalidate_dynptr(env, state, i); 764 } 765 766 return 0; 767 } 768 769 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 770 struct bpf_reg_state *reg); 771 772 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 773 { 774 if (!env->allow_ptr_leaks) 775 bpf_mark_reg_not_init(env, reg); 776 else 777 __mark_reg_unknown(env, reg); 778 } 779 780 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 781 struct bpf_func_state *state, int spi) 782 { 783 struct bpf_func_state *fstate; 784 struct bpf_reg_state *dreg; 785 int i, dynptr_id; 786 787 /* We always ensure that STACK_DYNPTR is never set partially, 788 * hence just checking for slot_type[0] is enough. This is 789 * different for STACK_SPILL, where it may be only set for 790 * 1 byte, so code has to use is_spilled_reg. 791 */ 792 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 793 return 0; 794 795 /* Reposition spi to first slot */ 796 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 797 spi = spi + 1; 798 799 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 800 int ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 801 int ref_cnt = 0; 802 803 /* 804 * A referenced dynptr can be overwritten only if there is at 805 * least one other dynptr sharing the same ref_obj_id, 806 * ensuring the reference can still be properly released. 807 */ 808 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 809 if (state->stack[i].slot_type[0] != STACK_DYNPTR) 810 continue; 811 if (!state->stack[i].spilled_ptr.dynptr.first_slot) 812 continue; 813 if (state->stack[i].spilled_ptr.ref_obj_id == ref_obj_id) 814 ref_cnt++; 815 } 816 817 if (ref_cnt <= 1) { 818 verbose(env, "cannot overwrite referenced dynptr\n"); 819 return -EINVAL; 820 } 821 } 822 823 mark_stack_slot_scratched(env, spi); 824 mark_stack_slot_scratched(env, spi - 1); 825 826 /* Writing partially to one dynptr stack slot destroys both. */ 827 for (i = 0; i < BPF_REG_SIZE; i++) { 828 state->stack[spi].slot_type[i] = STACK_INVALID; 829 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 830 } 831 832 dynptr_id = state->stack[spi].spilled_ptr.id; 833 /* Invalidate any slices associated with this dynptr */ 834 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 835 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 836 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 837 continue; 838 if (dreg->dynptr_id == dynptr_id) 839 mark_reg_invalid(env, dreg); 840 })); 841 842 /* Do not release reference state, we are destroying dynptr on stack, 843 * not using some helper to release it. Just reset register. 844 */ 845 bpf_mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 846 bpf_mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 847 848 return 0; 849 } 850 851 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 852 { 853 int spi; 854 855 if (reg->type == CONST_PTR_TO_DYNPTR) 856 return false; 857 858 spi = dynptr_get_spi(env, reg); 859 860 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 861 * error because this just means the stack state hasn't been updated yet. 862 * We will do check_mem_access to check and update stack bounds later. 863 */ 864 if (spi < 0 && spi != -ERANGE) 865 return false; 866 867 /* We don't need to check if the stack slots are marked by previous 868 * dynptr initializations because we allow overwriting existing unreferenced 869 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 870 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 871 * touching are completely destructed before we reinitialize them for a new 872 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 873 * instead of delaying it until the end where the user will get "Unreleased 874 * reference" error. 875 */ 876 return true; 877 } 878 879 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 880 { 881 struct bpf_func_state *state = bpf_func(env, reg); 882 int i, spi; 883 884 /* This already represents first slot of initialized bpf_dynptr. 885 * 886 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 887 * check_func_arg_reg_off's logic, so we don't need to check its 888 * offset and alignment. 889 */ 890 if (reg->type == CONST_PTR_TO_DYNPTR) 891 return true; 892 893 spi = dynptr_get_spi(env, reg); 894 if (spi < 0) 895 return false; 896 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 897 return false; 898 899 for (i = 0; i < BPF_REG_SIZE; i++) { 900 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 901 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 902 return false; 903 } 904 905 return true; 906 } 907 908 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 909 enum bpf_arg_type arg_type) 910 { 911 struct bpf_func_state *state = bpf_func(env, reg); 912 enum bpf_dynptr_type dynptr_type; 913 int spi; 914 915 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 916 if (arg_type == ARG_PTR_TO_DYNPTR) 917 return true; 918 919 dynptr_type = arg_to_dynptr_type(arg_type); 920 if (reg->type == CONST_PTR_TO_DYNPTR) { 921 return reg->dynptr.type == dynptr_type; 922 } else { 923 spi = dynptr_get_spi(env, reg); 924 if (spi < 0) 925 return false; 926 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 927 } 928 } 929 930 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 931 932 static bool in_rcu_cs(struct bpf_verifier_env *env); 933 934 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 935 936 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 937 struct bpf_kfunc_call_arg_meta *meta, 938 struct bpf_reg_state *reg, int insn_idx, 939 struct btf *btf, u32 btf_id, int nr_slots) 940 { 941 struct bpf_func_state *state = bpf_func(env, reg); 942 int spi, i, j, id; 943 944 spi = iter_get_spi(env, reg, nr_slots); 945 if (spi < 0) 946 return spi; 947 948 id = acquire_reference(env, insn_idx); 949 if (id < 0) 950 return id; 951 952 for (i = 0; i < nr_slots; i++) { 953 struct bpf_stack_state *slot = &state->stack[spi - i]; 954 struct bpf_reg_state *st = &slot->spilled_ptr; 955 956 __mark_reg_known_zero(st); 957 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 958 if (is_kfunc_rcu_protected(meta)) { 959 if (in_rcu_cs(env)) 960 st->type |= MEM_RCU; 961 else 962 st->type |= PTR_UNTRUSTED; 963 } 964 st->ref_obj_id = i == 0 ? id : 0; 965 st->iter.btf = btf; 966 st->iter.btf_id = btf_id; 967 st->iter.state = BPF_ITER_STATE_ACTIVE; 968 st->iter.depth = 0; 969 970 for (j = 0; j < BPF_REG_SIZE; j++) 971 slot->slot_type[j] = STACK_ITER; 972 973 mark_stack_slot_scratched(env, spi - i); 974 } 975 976 return 0; 977 } 978 979 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 980 struct bpf_reg_state *reg, int nr_slots) 981 { 982 struct bpf_func_state *state = bpf_func(env, reg); 983 int spi, i, j; 984 985 spi = iter_get_spi(env, reg, nr_slots); 986 if (spi < 0) 987 return spi; 988 989 for (i = 0; i < nr_slots; i++) { 990 struct bpf_stack_state *slot = &state->stack[spi - i]; 991 struct bpf_reg_state *st = &slot->spilled_ptr; 992 993 if (i == 0) 994 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 995 996 bpf_mark_reg_not_init(env, st); 997 998 for (j = 0; j < BPF_REG_SIZE; j++) 999 slot->slot_type[j] = STACK_INVALID; 1000 1001 mark_stack_slot_scratched(env, spi - i); 1002 } 1003 1004 return 0; 1005 } 1006 1007 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1008 struct bpf_reg_state *reg, int nr_slots) 1009 { 1010 struct bpf_func_state *state = bpf_func(env, reg); 1011 int spi, i, j; 1012 1013 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1014 * will do check_mem_access to check and update stack bounds later, so 1015 * return true for that case. 1016 */ 1017 spi = iter_get_spi(env, reg, nr_slots); 1018 if (spi == -ERANGE) 1019 return true; 1020 if (spi < 0) 1021 return false; 1022 1023 for (i = 0; i < nr_slots; i++) { 1024 struct bpf_stack_state *slot = &state->stack[spi - i]; 1025 1026 for (j = 0; j < BPF_REG_SIZE; j++) 1027 if (slot->slot_type[j] == STACK_ITER) 1028 return false; 1029 } 1030 1031 return true; 1032 } 1033 1034 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1035 struct btf *btf, u32 btf_id, int nr_slots) 1036 { 1037 struct bpf_func_state *state = bpf_func(env, reg); 1038 int spi, i, j; 1039 1040 spi = iter_get_spi(env, reg, nr_slots); 1041 if (spi < 0) 1042 return -EINVAL; 1043 1044 for (i = 0; i < nr_slots; i++) { 1045 struct bpf_stack_state *slot = &state->stack[spi - i]; 1046 struct bpf_reg_state *st = &slot->spilled_ptr; 1047 1048 if (st->type & PTR_UNTRUSTED) 1049 return -EPROTO; 1050 /* only main (first) slot has ref_obj_id set */ 1051 if (i == 0 && !st->ref_obj_id) 1052 return -EINVAL; 1053 if (i != 0 && st->ref_obj_id) 1054 return -EINVAL; 1055 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1056 return -EINVAL; 1057 1058 for (j = 0; j < BPF_REG_SIZE; j++) 1059 if (slot->slot_type[j] != STACK_ITER) 1060 return -EINVAL; 1061 } 1062 1063 return 0; 1064 } 1065 1066 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx); 1067 static int release_irq_state(struct bpf_verifier_state *state, int id); 1068 1069 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env, 1070 struct bpf_kfunc_call_arg_meta *meta, 1071 struct bpf_reg_state *reg, int insn_idx, 1072 int kfunc_class) 1073 { 1074 struct bpf_func_state *state = bpf_func(env, reg); 1075 struct bpf_stack_state *slot; 1076 struct bpf_reg_state *st; 1077 int spi, i, id; 1078 1079 spi = irq_flag_get_spi(env, reg); 1080 if (spi < 0) 1081 return spi; 1082 1083 id = acquire_irq_state(env, insn_idx); 1084 if (id < 0) 1085 return id; 1086 1087 slot = &state->stack[spi]; 1088 st = &slot->spilled_ptr; 1089 1090 __mark_reg_known_zero(st); 1091 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1092 st->ref_obj_id = id; 1093 st->irq.kfunc_class = kfunc_class; 1094 1095 for (i = 0; i < BPF_REG_SIZE; i++) 1096 slot->slot_type[i] = STACK_IRQ_FLAG; 1097 1098 mark_stack_slot_scratched(env, spi); 1099 return 0; 1100 } 1101 1102 static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1103 int kfunc_class) 1104 { 1105 struct bpf_func_state *state = bpf_func(env, reg); 1106 struct bpf_stack_state *slot; 1107 struct bpf_reg_state *st; 1108 int spi, i, err; 1109 1110 spi = irq_flag_get_spi(env, reg); 1111 if (spi < 0) 1112 return spi; 1113 1114 slot = &state->stack[spi]; 1115 st = &slot->spilled_ptr; 1116 1117 if (st->irq.kfunc_class != kfunc_class) { 1118 const char *flag_kfunc = st->irq.kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1119 const char *used_kfunc = kfunc_class == IRQ_NATIVE_KFUNC ? "native" : "lock"; 1120 1121 verbose(env, "irq flag acquired by %s kfuncs cannot be restored with %s kfuncs\n", 1122 flag_kfunc, used_kfunc); 1123 return -EINVAL; 1124 } 1125 1126 err = release_irq_state(env->cur_state, st->ref_obj_id); 1127 WARN_ON_ONCE(err && err != -EACCES); 1128 if (err) { 1129 int insn_idx = 0; 1130 1131 for (int i = 0; i < env->cur_state->acquired_refs; i++) { 1132 if (env->cur_state->refs[i].id == env->cur_state->active_irq_id) { 1133 insn_idx = env->cur_state->refs[i].insn_idx; 1134 break; 1135 } 1136 } 1137 1138 verbose(env, "cannot restore irq state out of order, expected id=%d acquired at insn_idx=%d\n", 1139 env->cur_state->active_irq_id, insn_idx); 1140 return err; 1141 } 1142 1143 bpf_mark_reg_not_init(env, st); 1144 1145 for (i = 0; i < BPF_REG_SIZE; i++) 1146 slot->slot_type[i] = STACK_INVALID; 1147 1148 mark_stack_slot_scratched(env, spi); 1149 return 0; 1150 } 1151 1152 static bool is_irq_flag_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1153 { 1154 struct bpf_func_state *state = bpf_func(env, reg); 1155 struct bpf_stack_state *slot; 1156 int spi, i; 1157 1158 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1159 * will do check_mem_access to check and update stack bounds later, so 1160 * return true for that case. 1161 */ 1162 spi = irq_flag_get_spi(env, reg); 1163 if (spi == -ERANGE) 1164 return true; 1165 if (spi < 0) 1166 return false; 1167 1168 slot = &state->stack[spi]; 1169 1170 for (i = 0; i < BPF_REG_SIZE; i++) 1171 if (slot->slot_type[i] == STACK_IRQ_FLAG) 1172 return false; 1173 return true; 1174 } 1175 1176 static int is_irq_flag_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1177 { 1178 struct bpf_func_state *state = bpf_func(env, reg); 1179 struct bpf_stack_state *slot; 1180 struct bpf_reg_state *st; 1181 int spi, i; 1182 1183 spi = irq_flag_get_spi(env, reg); 1184 if (spi < 0) 1185 return -EINVAL; 1186 1187 slot = &state->stack[spi]; 1188 st = &slot->spilled_ptr; 1189 1190 if (!st->ref_obj_id) 1191 return -EINVAL; 1192 1193 for (i = 0; i < BPF_REG_SIZE; i++) 1194 if (slot->slot_type[i] != STACK_IRQ_FLAG) 1195 return -EINVAL; 1196 return 0; 1197 } 1198 1199 /* Check if given stack slot is "special": 1200 * - spilled register state (STACK_SPILL); 1201 * - dynptr state (STACK_DYNPTR); 1202 * - iter state (STACK_ITER). 1203 * - irq flag state (STACK_IRQ_FLAG) 1204 */ 1205 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1206 { 1207 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1208 1209 switch (type) { 1210 case STACK_SPILL: 1211 case STACK_DYNPTR: 1212 case STACK_ITER: 1213 case STACK_IRQ_FLAG: 1214 return true; 1215 case STACK_INVALID: 1216 case STACK_POISON: 1217 case STACK_MISC: 1218 case STACK_ZERO: 1219 return false; 1220 default: 1221 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1222 return true; 1223 } 1224 } 1225 1226 /* The reg state of a pointer or a bounded scalar was saved when 1227 * it was spilled to the stack. 1228 */ 1229 1230 /* 1231 * Mark stack slot as STACK_MISC, unless it is already: 1232 * - STACK_INVALID, in which case they are equivalent. 1233 * - STACK_ZERO, in which case we preserve more precise STACK_ZERO. 1234 * - STACK_POISON, which truly forbids access to the slot. 1235 * Regardless of allow_ptr_leaks setting (i.e., privileged or unprivileged 1236 * mode), we won't promote STACK_INVALID to STACK_MISC. In privileged case it is 1237 * unnecessary as both are considered equivalent when loading data and pruning, 1238 * in case of unprivileged mode it will be incorrect to allow reads of invalid 1239 * slots. 1240 */ 1241 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1242 { 1243 if (*stype == STACK_ZERO) 1244 return; 1245 if (*stype == STACK_INVALID || *stype == STACK_POISON) 1246 return; 1247 *stype = STACK_MISC; 1248 } 1249 1250 static void scrub_spilled_slot(u8 *stype) 1251 { 1252 if (*stype != STACK_INVALID && *stype != STACK_POISON) 1253 *stype = STACK_MISC; 1254 } 1255 1256 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1257 * small to hold src. This is different from krealloc since we don't want to preserve 1258 * the contents of dst. 1259 * 1260 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1261 * not be allocated. 1262 */ 1263 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1264 { 1265 size_t alloc_bytes; 1266 void *orig = dst; 1267 size_t bytes; 1268 1269 if (ZERO_OR_NULL_PTR(src)) 1270 goto out; 1271 1272 if (unlikely(check_mul_overflow(n, size, &bytes))) 1273 return NULL; 1274 1275 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1276 dst = krealloc(orig, alloc_bytes, flags); 1277 if (!dst) { 1278 kfree(orig); 1279 return NULL; 1280 } 1281 1282 memcpy(dst, src, bytes); 1283 out: 1284 return dst ? dst : ZERO_SIZE_PTR; 1285 } 1286 1287 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1288 * small to hold new_n items. new items are zeroed out if the array grows. 1289 * 1290 * Contrary to krealloc_array, does not free arr if new_n is zero. 1291 */ 1292 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1293 { 1294 size_t alloc_size; 1295 void *new_arr; 1296 1297 if (!new_n || old_n == new_n) 1298 goto out; 1299 1300 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1301 new_arr = krealloc(arr, alloc_size, GFP_KERNEL_ACCOUNT); 1302 if (!new_arr) { 1303 kfree(arr); 1304 return NULL; 1305 } 1306 arr = new_arr; 1307 1308 if (new_n > old_n) 1309 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1310 1311 out: 1312 return arr ? arr : ZERO_SIZE_PTR; 1313 } 1314 1315 static int copy_reference_state(struct bpf_verifier_state *dst, const struct bpf_verifier_state *src) 1316 { 1317 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1318 sizeof(struct bpf_reference_state), GFP_KERNEL_ACCOUNT); 1319 if (!dst->refs) 1320 return -ENOMEM; 1321 1322 dst->acquired_refs = src->acquired_refs; 1323 dst->active_locks = src->active_locks; 1324 dst->active_preempt_locks = src->active_preempt_locks; 1325 dst->active_rcu_locks = src->active_rcu_locks; 1326 dst->active_irq_id = src->active_irq_id; 1327 dst->active_lock_id = src->active_lock_id; 1328 dst->active_lock_ptr = src->active_lock_ptr; 1329 return 0; 1330 } 1331 1332 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1333 { 1334 size_t n = src->allocated_stack / BPF_REG_SIZE; 1335 1336 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1337 GFP_KERNEL_ACCOUNT); 1338 if (!dst->stack) 1339 return -ENOMEM; 1340 1341 dst->allocated_stack = src->allocated_stack; 1342 return 0; 1343 } 1344 1345 static int resize_reference_state(struct bpf_verifier_state *state, size_t n) 1346 { 1347 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1348 sizeof(struct bpf_reference_state)); 1349 if (!state->refs) 1350 return -ENOMEM; 1351 1352 state->acquired_refs = n; 1353 return 0; 1354 } 1355 1356 /* Possibly update state->allocated_stack to be at least size bytes. Also 1357 * possibly update the function's high-water mark in its bpf_subprog_info. 1358 */ 1359 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1360 { 1361 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1362 1363 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1364 size = round_up(size, BPF_REG_SIZE); 1365 n = size / BPF_REG_SIZE; 1366 1367 if (old_n >= n) 1368 return 0; 1369 1370 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1371 if (!state->stack) 1372 return -ENOMEM; 1373 1374 state->allocated_stack = size; 1375 1376 /* update known max for given subprogram */ 1377 if (env->subprog_info[state->subprogno].stack_depth < size) 1378 env->subprog_info[state->subprogno].stack_depth = size; 1379 1380 return 0; 1381 } 1382 1383 /* Acquire a pointer id from the env and update the state->refs to include 1384 * this new pointer reference. 1385 * On success, returns a valid pointer id to associate with the register 1386 * On failure, returns a negative errno. 1387 */ 1388 static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1389 { 1390 struct bpf_verifier_state *state = env->cur_state; 1391 int new_ofs = state->acquired_refs; 1392 int err; 1393 1394 err = resize_reference_state(state, state->acquired_refs + 1); 1395 if (err) 1396 return NULL; 1397 state->refs[new_ofs].insn_idx = insn_idx; 1398 1399 return &state->refs[new_ofs]; 1400 } 1401 1402 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx) 1403 { 1404 struct bpf_reference_state *s; 1405 1406 s = acquire_reference_state(env, insn_idx); 1407 if (!s) 1408 return -ENOMEM; 1409 s->type = REF_TYPE_PTR; 1410 s->id = ++env->id_gen; 1411 return s->id; 1412 } 1413 1414 static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum ref_state_type type, 1415 int id, void *ptr) 1416 { 1417 struct bpf_verifier_state *state = env->cur_state; 1418 struct bpf_reference_state *s; 1419 1420 s = acquire_reference_state(env, insn_idx); 1421 if (!s) 1422 return -ENOMEM; 1423 s->type = type; 1424 s->id = id; 1425 s->ptr = ptr; 1426 1427 state->active_locks++; 1428 state->active_lock_id = id; 1429 state->active_lock_ptr = ptr; 1430 return 0; 1431 } 1432 1433 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx) 1434 { 1435 struct bpf_verifier_state *state = env->cur_state; 1436 struct bpf_reference_state *s; 1437 1438 s = acquire_reference_state(env, insn_idx); 1439 if (!s) 1440 return -ENOMEM; 1441 s->type = REF_TYPE_IRQ; 1442 s->id = ++env->id_gen; 1443 1444 state->active_irq_id = s->id; 1445 return s->id; 1446 } 1447 1448 static void release_reference_state(struct bpf_verifier_state *state, int idx) 1449 { 1450 int last_idx; 1451 size_t rem; 1452 1453 /* IRQ state requires the relative ordering of elements remaining the 1454 * same, since it relies on the refs array to behave as a stack, so that 1455 * it can detect out-of-order IRQ restore. Hence use memmove to shift 1456 * the array instead of swapping the final element into the deleted idx. 1457 */ 1458 last_idx = state->acquired_refs - 1; 1459 rem = state->acquired_refs - idx - 1; 1460 if (last_idx && idx != last_idx) 1461 memmove(&state->refs[idx], &state->refs[idx + 1], sizeof(*state->refs) * rem); 1462 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1463 state->acquired_refs--; 1464 return; 1465 } 1466 1467 static bool find_reference_state(struct bpf_verifier_state *state, int ptr_id) 1468 { 1469 int i; 1470 1471 for (i = 0; i < state->acquired_refs; i++) 1472 if (state->refs[i].id == ptr_id) 1473 return true; 1474 1475 return false; 1476 } 1477 1478 static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr) 1479 { 1480 void *prev_ptr = NULL; 1481 u32 prev_id = 0; 1482 int i; 1483 1484 for (i = 0; i < state->acquired_refs; i++) { 1485 if (state->refs[i].type == type && state->refs[i].id == id && 1486 state->refs[i].ptr == ptr) { 1487 release_reference_state(state, i); 1488 state->active_locks--; 1489 /* Reassign active lock (id, ptr). */ 1490 state->active_lock_id = prev_id; 1491 state->active_lock_ptr = prev_ptr; 1492 return 0; 1493 } 1494 if (state->refs[i].type & REF_TYPE_LOCK_MASK) { 1495 prev_id = state->refs[i].id; 1496 prev_ptr = state->refs[i].ptr; 1497 } 1498 } 1499 return -EINVAL; 1500 } 1501 1502 static int release_irq_state(struct bpf_verifier_state *state, int id) 1503 { 1504 u32 prev_id = 0; 1505 int i; 1506 1507 if (id != state->active_irq_id) 1508 return -EACCES; 1509 1510 for (i = 0; i < state->acquired_refs; i++) { 1511 if (state->refs[i].type != REF_TYPE_IRQ) 1512 continue; 1513 if (state->refs[i].id == id) { 1514 release_reference_state(state, i); 1515 state->active_irq_id = prev_id; 1516 return 0; 1517 } else { 1518 prev_id = state->refs[i].id; 1519 } 1520 } 1521 return -EINVAL; 1522 } 1523 1524 static struct bpf_reference_state *find_lock_state(struct bpf_verifier_state *state, enum ref_state_type type, 1525 int id, void *ptr) 1526 { 1527 int i; 1528 1529 for (i = 0; i < state->acquired_refs; i++) { 1530 struct bpf_reference_state *s = &state->refs[i]; 1531 1532 if (!(s->type & type)) 1533 continue; 1534 1535 if (s->id == id && s->ptr == ptr) 1536 return s; 1537 } 1538 return NULL; 1539 } 1540 1541 static void free_func_state(struct bpf_func_state *state) 1542 { 1543 if (!state) 1544 return; 1545 kfree(state->stack); 1546 kfree(state); 1547 } 1548 1549 void bpf_clear_jmp_history(struct bpf_verifier_state *state) 1550 { 1551 kfree(state->jmp_history); 1552 state->jmp_history = NULL; 1553 state->jmp_history_cnt = 0; 1554 } 1555 1556 void bpf_free_verifier_state(struct bpf_verifier_state *state, 1557 bool free_self) 1558 { 1559 int i; 1560 1561 for (i = 0; i <= state->curframe; i++) { 1562 free_func_state(state->frame[i]); 1563 state->frame[i] = NULL; 1564 } 1565 kfree(state->refs); 1566 bpf_clear_jmp_history(state); 1567 if (free_self) 1568 kfree(state); 1569 } 1570 1571 /* copy verifier state from src to dst growing dst stack space 1572 * when necessary to accommodate larger src stack 1573 */ 1574 static int copy_func_state(struct bpf_func_state *dst, 1575 const struct bpf_func_state *src) 1576 { 1577 memcpy(dst, src, offsetof(struct bpf_func_state, stack)); 1578 return copy_stack_state(dst, src); 1579 } 1580 1581 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state, 1582 const struct bpf_verifier_state *src) 1583 { 1584 struct bpf_func_state *dst; 1585 int i, err; 1586 1587 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1588 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1589 GFP_KERNEL_ACCOUNT); 1590 if (!dst_state->jmp_history) 1591 return -ENOMEM; 1592 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1593 1594 /* if dst has more stack frames then src frame, free them, this is also 1595 * necessary in case of exceptional exits using bpf_throw. 1596 */ 1597 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1598 free_func_state(dst_state->frame[i]); 1599 dst_state->frame[i] = NULL; 1600 } 1601 err = copy_reference_state(dst_state, src); 1602 if (err) 1603 return err; 1604 dst_state->speculative = src->speculative; 1605 dst_state->in_sleepable = src->in_sleepable; 1606 dst_state->curframe = src->curframe; 1607 dst_state->branches = src->branches; 1608 dst_state->parent = src->parent; 1609 dst_state->first_insn_idx = src->first_insn_idx; 1610 dst_state->last_insn_idx = src->last_insn_idx; 1611 dst_state->dfs_depth = src->dfs_depth; 1612 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1613 dst_state->may_goto_depth = src->may_goto_depth; 1614 dst_state->equal_state = src->equal_state; 1615 for (i = 0; i <= src->curframe; i++) { 1616 dst = dst_state->frame[i]; 1617 if (!dst) { 1618 dst = kzalloc_obj(*dst, GFP_KERNEL_ACCOUNT); 1619 if (!dst) 1620 return -ENOMEM; 1621 dst_state->frame[i] = dst; 1622 } 1623 err = copy_func_state(dst, src->frame[i]); 1624 if (err) 1625 return err; 1626 } 1627 return 0; 1628 } 1629 1630 static u32 state_htab_size(struct bpf_verifier_env *env) 1631 { 1632 return env->prog->len; 1633 } 1634 1635 struct list_head *bpf_explored_state(struct bpf_verifier_env *env, int idx) 1636 { 1637 struct bpf_verifier_state *cur = env->cur_state; 1638 struct bpf_func_state *state = cur->frame[cur->curframe]; 1639 1640 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1641 } 1642 1643 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1644 { 1645 int fr; 1646 1647 if (a->curframe != b->curframe) 1648 return false; 1649 1650 for (fr = a->curframe; fr >= 0; fr--) 1651 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1652 return false; 1653 1654 return true; 1655 } 1656 1657 1658 void bpf_free_backedges(struct bpf_scc_visit *visit) 1659 { 1660 struct bpf_scc_backedge *backedge, *next; 1661 1662 for (backedge = visit->backedges; backedge; backedge = next) { 1663 bpf_free_verifier_state(&backedge->state, false); 1664 next = backedge->next; 1665 kfree(backedge); 1666 } 1667 visit->backedges = NULL; 1668 } 1669 1670 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1671 int *insn_idx, bool pop_log) 1672 { 1673 struct bpf_verifier_state *cur = env->cur_state; 1674 struct bpf_verifier_stack_elem *elem, *head = env->head; 1675 int err; 1676 1677 if (env->head == NULL) 1678 return -ENOENT; 1679 1680 if (cur) { 1681 err = bpf_copy_verifier_state(cur, &head->st); 1682 if (err) 1683 return err; 1684 } 1685 if (pop_log) 1686 bpf_vlog_reset(&env->log, head->log_pos); 1687 if (insn_idx) 1688 *insn_idx = head->insn_idx; 1689 if (prev_insn_idx) 1690 *prev_insn_idx = head->prev_insn_idx; 1691 elem = head->next; 1692 bpf_free_verifier_state(&head->st, false); 1693 kfree(head); 1694 env->head = elem; 1695 env->stack_size--; 1696 return 0; 1697 } 1698 1699 static bool error_recoverable_with_nospec(int err) 1700 { 1701 /* Should only return true for non-fatal errors that are allowed to 1702 * occur during speculative verification. For these we can insert a 1703 * nospec and the program might still be accepted. Do not include 1704 * something like ENOMEM because it is likely to re-occur for the next 1705 * architectural path once it has been recovered-from in all speculative 1706 * paths. 1707 */ 1708 return err == -EPERM || err == -EACCES || err == -EINVAL; 1709 } 1710 1711 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1712 int insn_idx, int prev_insn_idx, 1713 bool speculative) 1714 { 1715 struct bpf_verifier_state *cur = env->cur_state; 1716 struct bpf_verifier_stack_elem *elem; 1717 int err; 1718 1719 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 1720 if (!elem) 1721 return ERR_PTR(-ENOMEM); 1722 1723 elem->insn_idx = insn_idx; 1724 elem->prev_insn_idx = prev_insn_idx; 1725 elem->next = env->head; 1726 elem->log_pos = env->log.end_pos; 1727 env->head = elem; 1728 env->stack_size++; 1729 err = bpf_copy_verifier_state(&elem->st, cur); 1730 if (err) 1731 return ERR_PTR(-ENOMEM); 1732 elem->st.speculative |= speculative; 1733 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1734 verbose(env, "The sequence of %d jumps is too complex.\n", 1735 env->stack_size); 1736 return ERR_PTR(-E2BIG); 1737 } 1738 if (elem->st.parent) { 1739 ++elem->st.parent->branches; 1740 /* WARN_ON(branches > 2) technically makes sense here, 1741 * but 1742 * 1. speculative states will bump 'branches' for non-branch 1743 * instructions 1744 * 2. is_state_visited() heuristics may decide not to create 1745 * a new state for a sequence of branches and all such current 1746 * and cloned states will be pointing to a single parent state 1747 * which might have large 'branches' count. 1748 */ 1749 } 1750 return &elem->st; 1751 } 1752 1753 static const int caller_saved[CALLER_SAVED_REGS] = { 1754 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1755 }; 1756 1757 /* This helper doesn't clear reg->id */ 1758 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1759 { 1760 reg->var_off = tnum_const(imm); 1761 reg->smin_value = (s64)imm; 1762 reg->smax_value = (s64)imm; 1763 reg->umin_value = imm; 1764 reg->umax_value = imm; 1765 1766 reg->s32_min_value = (s32)imm; 1767 reg->s32_max_value = (s32)imm; 1768 reg->u32_min_value = (u32)imm; 1769 reg->u32_max_value = (u32)imm; 1770 } 1771 1772 /* Mark the unknown part of a register (variable offset or scalar value) as 1773 * known to have the value @imm. 1774 */ 1775 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1776 { 1777 /* Clear off and union(map_ptr, range) */ 1778 memset(((u8 *)reg) + sizeof(reg->type), 0, 1779 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1780 reg->id = 0; 1781 reg->ref_obj_id = 0; 1782 ___mark_reg_known(reg, imm); 1783 } 1784 1785 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1786 { 1787 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1788 reg->s32_min_value = (s32)imm; 1789 reg->s32_max_value = (s32)imm; 1790 reg->u32_min_value = (u32)imm; 1791 reg->u32_max_value = (u32)imm; 1792 } 1793 1794 /* Mark the 'variable offset' part of a register as zero. This should be 1795 * used only on registers holding a pointer type. 1796 */ 1797 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1798 { 1799 __mark_reg_known(reg, 0); 1800 } 1801 1802 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1803 { 1804 __mark_reg_known(reg, 0); 1805 reg->type = SCALAR_VALUE; 1806 /* all scalars are assumed imprecise initially (unless unprivileged, 1807 * in which case everything is forced to be precise) 1808 */ 1809 reg->precise = !env->bpf_capable; 1810 } 1811 1812 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1813 struct bpf_reg_state *regs, u32 regno) 1814 { 1815 __mark_reg_known_zero(regs + regno); 1816 } 1817 1818 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1819 bool first_slot, int dynptr_id) 1820 { 1821 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1822 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1823 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1824 */ 1825 __mark_reg_known_zero(reg); 1826 reg->type = CONST_PTR_TO_DYNPTR; 1827 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1828 reg->id = dynptr_id; 1829 reg->dynptr.type = type; 1830 reg->dynptr.first_slot = first_slot; 1831 } 1832 1833 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1834 { 1835 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1836 const struct bpf_map *map = reg->map_ptr; 1837 1838 if (map->inner_map_meta) { 1839 reg->type = CONST_PTR_TO_MAP; 1840 reg->map_ptr = map->inner_map_meta; 1841 /* transfer reg's id which is unique for every map_lookup_elem 1842 * as UID of the inner map. 1843 */ 1844 if (btf_record_has_field(map->inner_map_meta->record, 1845 BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK)) { 1846 reg->map_uid = reg->id; 1847 } 1848 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1849 reg->type = PTR_TO_XDP_SOCK; 1850 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1851 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1852 reg->type = PTR_TO_SOCKET; 1853 } else { 1854 reg->type = PTR_TO_MAP_VALUE; 1855 } 1856 return; 1857 } 1858 1859 reg->type &= ~PTR_MAYBE_NULL; 1860 } 1861 1862 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1863 struct btf_field_graph_root *ds_head) 1864 { 1865 __mark_reg_known(®s[regno], ds_head->node_offset); 1866 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1867 regs[regno].btf = ds_head->btf; 1868 regs[regno].btf_id = ds_head->value_btf_id; 1869 } 1870 1871 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1872 { 1873 return type_is_pkt_pointer(reg->type); 1874 } 1875 1876 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1877 { 1878 return reg_is_pkt_pointer(reg) || 1879 reg->type == PTR_TO_PACKET_END; 1880 } 1881 1882 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1883 { 1884 return base_type(reg->type) == PTR_TO_MEM && 1885 (reg->type & 1886 (DYNPTR_TYPE_SKB | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META)); 1887 } 1888 1889 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1890 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1891 enum bpf_reg_type which) 1892 { 1893 /* The register can already have a range from prior markings. 1894 * This is fine as long as it hasn't been advanced from its 1895 * origin. 1896 */ 1897 return reg->type == which && 1898 reg->id == 0 && 1899 tnum_equals_const(reg->var_off, 0); 1900 } 1901 1902 /* Reset the min/max bounds of a register */ 1903 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1904 { 1905 reg->smin_value = S64_MIN; 1906 reg->smax_value = S64_MAX; 1907 reg->umin_value = 0; 1908 reg->umax_value = U64_MAX; 1909 1910 reg->s32_min_value = S32_MIN; 1911 reg->s32_max_value = S32_MAX; 1912 reg->u32_min_value = 0; 1913 reg->u32_max_value = U32_MAX; 1914 } 1915 1916 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1917 { 1918 reg->smin_value = S64_MIN; 1919 reg->smax_value = S64_MAX; 1920 reg->umin_value = 0; 1921 reg->umax_value = U64_MAX; 1922 } 1923 1924 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1925 { 1926 reg->s32_min_value = S32_MIN; 1927 reg->s32_max_value = S32_MAX; 1928 reg->u32_min_value = 0; 1929 reg->u32_max_value = U32_MAX; 1930 } 1931 1932 static void reset_reg64_and_tnum(struct bpf_reg_state *reg) 1933 { 1934 __mark_reg64_unbounded(reg); 1935 reg->var_off = tnum_unknown; 1936 } 1937 1938 static void reset_reg32_and_tnum(struct bpf_reg_state *reg) 1939 { 1940 __mark_reg32_unbounded(reg); 1941 reg->var_off = tnum_unknown; 1942 } 1943 1944 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1945 { 1946 struct tnum var32_off = tnum_subreg(reg->var_off); 1947 1948 /* min signed is max(sign bit) | min(other bits) */ 1949 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1950 var32_off.value | (var32_off.mask & S32_MIN)); 1951 /* max signed is min(sign bit) | max(other bits) */ 1952 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1953 var32_off.value | (var32_off.mask & S32_MAX)); 1954 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1955 reg->u32_max_value = min(reg->u32_max_value, 1956 (u32)(var32_off.value | var32_off.mask)); 1957 } 1958 1959 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1960 { 1961 u64 tnum_next, tmax; 1962 bool umin_in_tnum; 1963 1964 /* min signed is max(sign bit) | min(other bits) */ 1965 reg->smin_value = max_t(s64, reg->smin_value, 1966 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1967 /* max signed is min(sign bit) | max(other bits) */ 1968 reg->smax_value = min_t(s64, reg->smax_value, 1969 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1970 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1971 reg->umax_value = min(reg->umax_value, 1972 reg->var_off.value | reg->var_off.mask); 1973 1974 /* Check if u64 and tnum overlap in a single value */ 1975 tnum_next = tnum_step(reg->var_off, reg->umin_value); 1976 umin_in_tnum = (reg->umin_value & ~reg->var_off.mask) == reg->var_off.value; 1977 tmax = reg->var_off.value | reg->var_off.mask; 1978 if (umin_in_tnum && tnum_next > reg->umax_value) { 1979 /* The u64 range and the tnum only overlap in umin. 1980 * u64: ---[xxxxxx]----- 1981 * tnum: --xx----------x- 1982 */ 1983 ___mark_reg_known(reg, reg->umin_value); 1984 } else if (!umin_in_tnum && tnum_next == tmax) { 1985 /* The u64 range and the tnum only overlap in the maximum value 1986 * represented by the tnum, called tmax. 1987 * u64: ---[xxxxxx]----- 1988 * tnum: xx-----x-------- 1989 */ 1990 ___mark_reg_known(reg, tmax); 1991 } else if (!umin_in_tnum && tnum_next <= reg->umax_value && 1992 tnum_step(reg->var_off, tnum_next) > reg->umax_value) { 1993 /* The u64 range and the tnum only overlap in between umin 1994 * (excluded) and umax. 1995 * u64: ---[xxxxxx]----- 1996 * tnum: xx----x-------x- 1997 */ 1998 ___mark_reg_known(reg, tnum_next); 1999 } 2000 } 2001 2002 static void __update_reg_bounds(struct bpf_reg_state *reg) 2003 { 2004 __update_reg32_bounds(reg); 2005 __update_reg64_bounds(reg); 2006 } 2007 2008 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2009 static void deduce_bounds_32_from_64(struct bpf_reg_state *reg) 2010 { 2011 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 2012 * bits to improve our u32/s32 boundaries. 2013 * 2014 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 2015 * u64) is pretty trivial, it's obvious that in u32 we'll also have 2016 * [10, 20] range. But this property holds for any 64-bit range as 2017 * long as upper 32 bits in that entire range of values stay the same. 2018 * 2019 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 2020 * in decimal) has the same upper 32 bits throughout all the values in 2021 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 2022 * range. 2023 * 2024 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 2025 * following the rules outlined below about u64/s64 correspondence 2026 * (which equally applies to u32 vs s32 correspondence). In general it 2027 * depends on actual hexadecimal values of 32-bit range. They can form 2028 * only valid u32, or only valid s32 ranges in some cases. 2029 * 2030 * So we use all these insights to derive bounds for subregisters here. 2031 */ 2032 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 2033 /* u64 to u32 casting preserves validity of low 32 bits as 2034 * a range, if upper 32 bits are the same 2035 */ 2036 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 2037 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 2038 2039 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 2040 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2041 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2042 } 2043 } 2044 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 2045 /* low 32 bits should form a proper u32 range */ 2046 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 2047 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 2048 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 2049 } 2050 /* low 32 bits should form a proper s32 range */ 2051 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 2052 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2053 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2054 } 2055 } 2056 /* Special case where upper bits form a small sequence of two 2057 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 2058 * 0x00000000 is also valid), while lower bits form a proper s32 range 2059 * going from negative numbers to positive numbers. E.g., let's say we 2060 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 2061 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 2062 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 2063 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 2064 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 2065 * upper 32 bits. As a random example, s64 range 2066 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2067 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2068 */ 2069 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2070 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 2071 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2072 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2073 } 2074 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2075 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2076 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2077 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2078 } 2079 } 2080 2081 static void deduce_bounds_32_from_32(struct bpf_reg_state *reg) 2082 { 2083 /* if u32 range forms a valid s32 range (due to matching sign bit), 2084 * try to learn from that 2085 */ 2086 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2087 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2088 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2089 } 2090 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2091 * are the same, so combine. This works even in the negative case, e.g. 2092 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2093 */ 2094 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2095 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2096 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2097 } else { 2098 if (reg->u32_max_value < (u32)reg->s32_min_value) { 2099 /* See __reg64_deduce_bounds() for detailed explanation. 2100 * Refine ranges in the following situation: 2101 * 2102 * 0 U32_MAX 2103 * | [xxxxxxxxxxxxxx u32 range xxxxxxxxxxxxxx] | 2104 * |----------------------------|----------------------------| 2105 * |xxxxx s32 range xxxxxxxxx] [xxxxxxx| 2106 * 0 S32_MAX S32_MIN -1 2107 */ 2108 reg->s32_min_value = (s32)reg->u32_min_value; 2109 reg->u32_max_value = min_t(u32, reg->u32_max_value, reg->s32_max_value); 2110 } else if ((u32)reg->s32_max_value < reg->u32_min_value) { 2111 /* 2112 * 0 U32_MAX 2113 * | [xxxxxxxxxxxxxx u32 range xxxxxxxxxxxxxx] | 2114 * |----------------------------|----------------------------| 2115 * |xxxxxxxxx] [xxxxxxxxxxxx s32 range | 2116 * 0 S32_MAX S32_MIN -1 2117 */ 2118 reg->s32_max_value = (s32)reg->u32_max_value; 2119 reg->u32_min_value = max_t(u32, reg->u32_min_value, reg->s32_min_value); 2120 } 2121 } 2122 } 2123 2124 static void deduce_bounds_64_from_64(struct bpf_reg_state *reg) 2125 { 2126 /* If u64 range forms a valid s64 range (due to matching sign bit), 2127 * try to learn from that. Let's do a bit of ASCII art to see when 2128 * this is happening. Let's take u64 range first: 2129 * 2130 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2131 * |-------------------------------|--------------------------------| 2132 * 2133 * Valid u64 range is formed when umin and umax are anywhere in the 2134 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2135 * straightforward. Let's see how s64 range maps onto the same range 2136 * of values, annotated below the line for comparison: 2137 * 2138 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2139 * |-------------------------------|--------------------------------| 2140 * 0 S64_MAX S64_MIN -1 2141 * 2142 * So s64 values basically start in the middle and they are logically 2143 * contiguous to the right of it, wrapping around from -1 to 0, and 2144 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2145 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2146 * more visually as mapped to sign-agnostic range of hex values. 2147 * 2148 * u64 start u64 end 2149 * _______________________________________________________________ 2150 * / \ 2151 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2152 * |-------------------------------|--------------------------------| 2153 * 0 S64_MAX S64_MIN -1 2154 * / \ 2155 * >------------------------------ -------------------------------> 2156 * s64 continues... s64 end s64 start s64 "midpoint" 2157 * 2158 * What this means is that, in general, we can't always derive 2159 * something new about u64 from any random s64 range, and vice versa. 2160 * 2161 * But we can do that in two particular cases. One is when entire 2162 * u64/s64 range is *entirely* contained within left half of the above 2163 * diagram or when it is *entirely* contained in the right half. I.e.: 2164 * 2165 * |-------------------------------|--------------------------------| 2166 * ^ ^ ^ ^ 2167 * A B C D 2168 * 2169 * [A, B] and [C, D] are contained entirely in their respective halves 2170 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2171 * will be non-negative both as u64 and s64 (and in fact it will be 2172 * identical ranges no matter the signedness). [C, D] treated as s64 2173 * will be a range of negative values, while in u64 it will be 2174 * non-negative range of values larger than 0x8000000000000000. 2175 * 2176 * Now, any other range here can't be represented in both u64 and s64 2177 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2178 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2179 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2180 * for example. Similarly, valid s64 range [D, A] (going from negative 2181 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2182 * ranges as u64. Currently reg_state can't represent two segments per 2183 * numeric domain, so in such situations we can only derive maximal 2184 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2185 * 2186 * So we use these facts to derive umin/umax from smin/smax and vice 2187 * versa only if they stay within the same "half". This is equivalent 2188 * to checking sign bit: lower half will have sign bit as zero, upper 2189 * half have sign bit 1. Below in code we simplify this by just 2190 * casting umin/umax as smin/smax and checking if they form valid 2191 * range, and vice versa. Those are equivalent checks. 2192 */ 2193 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2194 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2195 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2196 } 2197 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2198 * are the same, so combine. This works even in the negative case, e.g. 2199 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2200 */ 2201 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2202 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2203 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2204 } else { 2205 /* If the s64 range crosses the sign boundary, then it's split 2206 * between the beginning and end of the U64 domain. In that 2207 * case, we can derive new bounds if the u64 range overlaps 2208 * with only one end of the s64 range. 2209 * 2210 * In the following example, the u64 range overlaps only with 2211 * positive portion of the s64 range. 2212 * 2213 * 0 U64_MAX 2214 * | [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx] | 2215 * |----------------------------|----------------------------| 2216 * |xxxxx s64 range xxxxxxxxx] [xxxxxxx| 2217 * 0 S64_MAX S64_MIN -1 2218 * 2219 * We can thus derive the following new s64 and u64 ranges. 2220 * 2221 * 0 U64_MAX 2222 * | [xxxxxx u64 range xxxxx] | 2223 * |----------------------------|----------------------------| 2224 * | [xxxxxx s64 range xxxxx] | 2225 * 0 S64_MAX S64_MIN -1 2226 * 2227 * If they overlap in two places, we can't derive anything 2228 * because reg_state can't represent two ranges per numeric 2229 * domain. 2230 * 2231 * 0 U64_MAX 2232 * | [xxxxxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxxxxx] | 2233 * |----------------------------|----------------------------| 2234 * |xxxxx s64 range xxxxxxxxx] [xxxxxxxxxx| 2235 * 0 S64_MAX S64_MIN -1 2236 * 2237 * The first condition below corresponds to the first diagram 2238 * above. 2239 */ 2240 if (reg->umax_value < (u64)reg->smin_value) { 2241 reg->smin_value = (s64)reg->umin_value; 2242 reg->umax_value = min_t(u64, reg->umax_value, reg->smax_value); 2243 } else if ((u64)reg->smax_value < reg->umin_value) { 2244 /* This second condition considers the case where the u64 range 2245 * overlaps with the negative portion of the s64 range: 2246 * 2247 * 0 U64_MAX 2248 * | [xxxxxxxxxxxxxx u64 range xxxxxxxxxxxxxx] | 2249 * |----------------------------|----------------------------| 2250 * |xxxxxxxxx] [xxxxxxxxxxxx s64 range | 2251 * 0 S64_MAX S64_MIN -1 2252 */ 2253 reg->smax_value = (s64)reg->umax_value; 2254 reg->umin_value = max_t(u64, reg->umin_value, reg->smin_value); 2255 } 2256 } 2257 } 2258 2259 static void deduce_bounds_64_from_32(struct bpf_reg_state *reg) 2260 { 2261 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2262 * values on both sides of 64-bit range in hope to have tighter range. 2263 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2264 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2265 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2266 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2267 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2268 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2269 * We just need to make sure that derived bounds we are intersecting 2270 * with are well-formed ranges in respective s64 or u64 domain, just 2271 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2272 */ 2273 __u64 new_umin, new_umax; 2274 __s64 new_smin, new_smax; 2275 2276 /* u32 -> u64 tightening, it's always well-formed */ 2277 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2278 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2279 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2280 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2281 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2282 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2283 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2284 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2285 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2286 2287 /* Here we would like to handle a special case after sign extending load, 2288 * when upper bits for a 64-bit range are all 1s or all 0s. 2289 * 2290 * Upper bits are all 1s when register is in a range: 2291 * [0xffff_ffff_0000_0000, 0xffff_ffff_ffff_ffff] 2292 * Upper bits are all 0s when register is in a range: 2293 * [0x0000_0000_0000_0000, 0x0000_0000_ffff_ffff] 2294 * Together this forms are continuous range: 2295 * [0xffff_ffff_0000_0000, 0x0000_0000_ffff_ffff] 2296 * 2297 * Now, suppose that register range is in fact tighter: 2298 * [0xffff_ffff_8000_0000, 0x0000_0000_ffff_ffff] (R) 2299 * Also suppose that it's 32-bit range is positive, 2300 * meaning that lower 32-bits of the full 64-bit register 2301 * are in the range: 2302 * [0x0000_0000, 0x7fff_ffff] (W) 2303 * 2304 * If this happens, then any value in a range: 2305 * [0xffff_ffff_0000_0000, 0xffff_ffff_7fff_ffff] 2306 * is smaller than a lowest bound of the range (R): 2307 * 0xffff_ffff_8000_0000 2308 * which means that upper bits of the full 64-bit register 2309 * can't be all 1s, when lower bits are in range (W). 2310 * 2311 * Note that: 2312 * - 0xffff_ffff_8000_0000 == (s64)S32_MIN 2313 * - 0x0000_0000_7fff_ffff == (s64)S32_MAX 2314 * These relations are used in the conditions below. 2315 */ 2316 if (reg->s32_min_value >= 0 && reg->smin_value >= S32_MIN && reg->smax_value <= S32_MAX) { 2317 reg->smin_value = reg->s32_min_value; 2318 reg->smax_value = reg->s32_max_value; 2319 reg->umin_value = reg->s32_min_value; 2320 reg->umax_value = reg->s32_max_value; 2321 reg->var_off = tnum_intersect(reg->var_off, 2322 tnum_range(reg->smin_value, reg->smax_value)); 2323 } 2324 } 2325 2326 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2327 { 2328 deduce_bounds_64_from_64(reg); 2329 deduce_bounds_32_from_64(reg); 2330 deduce_bounds_32_from_32(reg); 2331 deduce_bounds_64_from_32(reg); 2332 } 2333 2334 /* Attempts to improve var_off based on unsigned min/max information */ 2335 static void __reg_bound_offset(struct bpf_reg_state *reg) 2336 { 2337 struct tnum var64_off = tnum_intersect(reg->var_off, 2338 tnum_range(reg->umin_value, 2339 reg->umax_value)); 2340 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2341 tnum_range(reg->u32_min_value, 2342 reg->u32_max_value)); 2343 2344 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2345 } 2346 2347 static bool range_bounds_violation(struct bpf_reg_state *reg); 2348 2349 static void reg_bounds_sync(struct bpf_reg_state *reg) 2350 { 2351 /* If the input reg_state is invalid, we can exit early */ 2352 if (range_bounds_violation(reg)) 2353 return; 2354 /* We might have learned new bounds from the var_off. */ 2355 __update_reg_bounds(reg); 2356 /* We might have learned something about the sign bit. */ 2357 __reg_deduce_bounds(reg); 2358 __reg_deduce_bounds(reg); 2359 /* We might have learned some bits from the bounds. */ 2360 __reg_bound_offset(reg); 2361 /* Intersecting with the old var_off might have improved our bounds 2362 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2363 * then new var_off is (0; 0x7f...fc) which improves our umax. 2364 */ 2365 __update_reg_bounds(reg); 2366 } 2367 2368 static bool range_bounds_violation(struct bpf_reg_state *reg) 2369 { 2370 return (reg->umin_value > reg->umax_value || reg->smin_value > reg->smax_value || 2371 reg->u32_min_value > reg->u32_max_value || 2372 reg->s32_min_value > reg->s32_max_value); 2373 } 2374 2375 static bool const_tnum_range_mismatch(struct bpf_reg_state *reg) 2376 { 2377 u64 uval = reg->var_off.value; 2378 s64 sval = (s64)uval; 2379 2380 if (!tnum_is_const(reg->var_off)) 2381 return false; 2382 2383 return reg->umin_value != uval || reg->umax_value != uval || 2384 reg->smin_value != sval || reg->smax_value != sval; 2385 } 2386 2387 static bool const_tnum_range_mismatch_32(struct bpf_reg_state *reg) 2388 { 2389 u32 uval32 = tnum_subreg(reg->var_off).value; 2390 s32 sval32 = (s32)uval32; 2391 2392 if (!tnum_subreg_is_const(reg->var_off)) 2393 return false; 2394 2395 return reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2396 reg->s32_min_value != sval32 || reg->s32_max_value != sval32; 2397 } 2398 2399 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2400 struct bpf_reg_state *reg, const char *ctx) 2401 { 2402 const char *msg; 2403 2404 if (range_bounds_violation(reg)) { 2405 msg = "range bounds violation"; 2406 goto out; 2407 } 2408 2409 if (const_tnum_range_mismatch(reg)) { 2410 msg = "const tnum out of sync with range bounds"; 2411 goto out; 2412 } 2413 2414 if (const_tnum_range_mismatch_32(reg)) { 2415 msg = "const subreg tnum out of sync with range bounds"; 2416 goto out; 2417 } 2418 2419 return 0; 2420 out: 2421 verifier_bug(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2422 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)", 2423 ctx, msg, reg->umin_value, reg->umax_value, 2424 reg->smin_value, reg->smax_value, 2425 reg->u32_min_value, reg->u32_max_value, 2426 reg->s32_min_value, reg->s32_max_value, 2427 reg->var_off.value, reg->var_off.mask); 2428 if (env->test_reg_invariants) 2429 return -EFAULT; 2430 __mark_reg_unbounded(reg); 2431 return 0; 2432 } 2433 2434 static bool __reg32_bound_s64(s32 a) 2435 { 2436 return a >= 0 && a <= S32_MAX; 2437 } 2438 2439 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2440 { 2441 reg->umin_value = reg->u32_min_value; 2442 reg->umax_value = reg->u32_max_value; 2443 2444 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2445 * be positive otherwise set to worse case bounds and refine later 2446 * from tnum. 2447 */ 2448 if (__reg32_bound_s64(reg->s32_min_value) && 2449 __reg32_bound_s64(reg->s32_max_value)) { 2450 reg->smin_value = reg->s32_min_value; 2451 reg->smax_value = reg->s32_max_value; 2452 } else { 2453 reg->smin_value = 0; 2454 reg->smax_value = U32_MAX; 2455 } 2456 } 2457 2458 /* Mark a register as having a completely unknown (scalar) value. */ 2459 void bpf_mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2460 { 2461 /* 2462 * Clear type, off, and union(map_ptr, range) and 2463 * padding between 'type' and union 2464 */ 2465 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2466 reg->type = SCALAR_VALUE; 2467 reg->id = 0; 2468 reg->ref_obj_id = 0; 2469 reg->var_off = tnum_unknown; 2470 reg->frameno = 0; 2471 reg->precise = false; 2472 __mark_reg_unbounded(reg); 2473 } 2474 2475 /* Mark a register as having a completely unknown (scalar) value, 2476 * initialize .precise as true when not bpf capable. 2477 */ 2478 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2479 struct bpf_reg_state *reg) 2480 { 2481 bpf_mark_reg_unknown_imprecise(reg); 2482 reg->precise = !env->bpf_capable; 2483 } 2484 2485 static void mark_reg_unknown(struct bpf_verifier_env *env, 2486 struct bpf_reg_state *regs, u32 regno) 2487 { 2488 __mark_reg_unknown(env, regs + regno); 2489 } 2490 2491 static int __mark_reg_s32_range(struct bpf_verifier_env *env, 2492 struct bpf_reg_state *regs, 2493 u32 regno, 2494 s32 s32_min, 2495 s32 s32_max) 2496 { 2497 struct bpf_reg_state *reg = regs + regno; 2498 2499 reg->s32_min_value = max_t(s32, reg->s32_min_value, s32_min); 2500 reg->s32_max_value = min_t(s32, reg->s32_max_value, s32_max); 2501 2502 reg->smin_value = max_t(s64, reg->smin_value, s32_min); 2503 reg->smax_value = min_t(s64, reg->smax_value, s32_max); 2504 2505 reg_bounds_sync(reg); 2506 2507 return reg_bounds_sanity_check(env, reg, "s32_range"); 2508 } 2509 2510 void bpf_mark_reg_not_init(const struct bpf_verifier_env *env, 2511 struct bpf_reg_state *reg) 2512 { 2513 __mark_reg_unknown(env, reg); 2514 reg->type = NOT_INIT; 2515 } 2516 2517 static int mark_btf_ld_reg(struct bpf_verifier_env *env, 2518 struct bpf_reg_state *regs, u32 regno, 2519 enum bpf_reg_type reg_type, 2520 struct btf *btf, u32 btf_id, 2521 enum bpf_type_flag flag) 2522 { 2523 switch (reg_type) { 2524 case SCALAR_VALUE: 2525 mark_reg_unknown(env, regs, regno); 2526 return 0; 2527 case PTR_TO_BTF_ID: 2528 mark_reg_known_zero(env, regs, regno); 2529 regs[regno].type = PTR_TO_BTF_ID | flag; 2530 regs[regno].btf = btf; 2531 regs[regno].btf_id = btf_id; 2532 if (type_may_be_null(flag)) 2533 regs[regno].id = ++env->id_gen; 2534 return 0; 2535 case PTR_TO_MEM: 2536 mark_reg_known_zero(env, regs, regno); 2537 regs[regno].type = PTR_TO_MEM | flag; 2538 regs[regno].mem_size = 0; 2539 return 0; 2540 default: 2541 verifier_bug(env, "unexpected reg_type %d in %s\n", reg_type, __func__); 2542 return -EFAULT; 2543 } 2544 } 2545 2546 #define DEF_NOT_SUBREG (0) 2547 static void init_reg_state(struct bpf_verifier_env *env, 2548 struct bpf_func_state *state) 2549 { 2550 struct bpf_reg_state *regs = state->regs; 2551 int i; 2552 2553 for (i = 0; i < MAX_BPF_REG; i++) { 2554 bpf_mark_reg_not_init(env, ®s[i]); 2555 regs[i].subreg_def = DEF_NOT_SUBREG; 2556 } 2557 2558 /* frame pointer */ 2559 regs[BPF_REG_FP].type = PTR_TO_STACK; 2560 mark_reg_known_zero(env, regs, BPF_REG_FP); 2561 regs[BPF_REG_FP].frameno = state->frameno; 2562 } 2563 2564 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2565 { 2566 /* 2567 * return_32bit is set to false by default and set explicitly 2568 * by the caller when necessary. 2569 */ 2570 return (struct bpf_retval_range){ minval, maxval, false }; 2571 } 2572 2573 static void init_func_state(struct bpf_verifier_env *env, 2574 struct bpf_func_state *state, 2575 int callsite, int frameno, int subprogno) 2576 { 2577 state->callsite = callsite; 2578 state->frameno = frameno; 2579 state->subprogno = subprogno; 2580 state->callback_ret_range = retval_range(0, 0); 2581 init_reg_state(env, state); 2582 mark_verifier_state_scratched(env); 2583 } 2584 2585 /* Similar to push_stack(), but for async callbacks */ 2586 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2587 int insn_idx, int prev_insn_idx, 2588 int subprog, bool is_sleepable) 2589 { 2590 struct bpf_verifier_stack_elem *elem; 2591 struct bpf_func_state *frame; 2592 2593 elem = kzalloc_obj(struct bpf_verifier_stack_elem, GFP_KERNEL_ACCOUNT); 2594 if (!elem) 2595 return ERR_PTR(-ENOMEM); 2596 2597 elem->insn_idx = insn_idx; 2598 elem->prev_insn_idx = prev_insn_idx; 2599 elem->next = env->head; 2600 elem->log_pos = env->log.end_pos; 2601 env->head = elem; 2602 env->stack_size++; 2603 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2604 verbose(env, 2605 "The sequence of %d jumps is too complex for async cb.\n", 2606 env->stack_size); 2607 return ERR_PTR(-E2BIG); 2608 } 2609 /* Unlike push_stack() do not bpf_copy_verifier_state(). 2610 * The caller state doesn't matter. 2611 * This is async callback. It starts in a fresh stack. 2612 * Initialize it similar to do_check_common(). 2613 */ 2614 elem->st.branches = 1; 2615 elem->st.in_sleepable = is_sleepable; 2616 frame = kzalloc_obj(*frame, GFP_KERNEL_ACCOUNT); 2617 if (!frame) 2618 return ERR_PTR(-ENOMEM); 2619 init_func_state(env, frame, 2620 BPF_MAIN_FUNC /* callsite */, 2621 0 /* frameno within this callchain */, 2622 subprog /* subprog number within this prog */); 2623 elem->st.frame[0] = frame; 2624 return &elem->st; 2625 } 2626 2627 2628 static int cmp_subprogs(const void *a, const void *b) 2629 { 2630 return ((struct bpf_subprog_info *)a)->start - 2631 ((struct bpf_subprog_info *)b)->start; 2632 } 2633 2634 /* Find subprogram that contains instruction at 'off' */ 2635 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off) 2636 { 2637 struct bpf_subprog_info *vals = env->subprog_info; 2638 int l, r, m; 2639 2640 if (off >= env->prog->len || off < 0 || env->subprog_cnt == 0) 2641 return NULL; 2642 2643 l = 0; 2644 r = env->subprog_cnt - 1; 2645 while (l < r) { 2646 m = l + (r - l + 1) / 2; 2647 if (vals[m].start <= off) 2648 l = m; 2649 else 2650 r = m - 1; 2651 } 2652 return &vals[l]; 2653 } 2654 2655 /* Find subprogram that starts exactly at 'off' */ 2656 int bpf_find_subprog(struct bpf_verifier_env *env, int off) 2657 { 2658 struct bpf_subprog_info *p; 2659 2660 p = bpf_find_containing_subprog(env, off); 2661 if (!p || p->start != off) 2662 return -ENOENT; 2663 return p - env->subprog_info; 2664 } 2665 2666 static int add_subprog(struct bpf_verifier_env *env, int off) 2667 { 2668 int insn_cnt = env->prog->len; 2669 int ret; 2670 2671 if (off >= insn_cnt || off < 0) { 2672 verbose(env, "call to invalid destination\n"); 2673 return -EINVAL; 2674 } 2675 ret = bpf_find_subprog(env, off); 2676 if (ret >= 0) 2677 return ret; 2678 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2679 verbose(env, "too many subprograms\n"); 2680 return -E2BIG; 2681 } 2682 /* determine subprog starts. The end is one before the next starts */ 2683 env->subprog_info[env->subprog_cnt++].start = off; 2684 sort(env->subprog_info, env->subprog_cnt, 2685 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2686 return env->subprog_cnt - 1; 2687 } 2688 2689 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2690 { 2691 struct bpf_prog_aux *aux = env->prog->aux; 2692 struct btf *btf = aux->btf; 2693 const struct btf_type *t; 2694 u32 main_btf_id, id; 2695 const char *name; 2696 int ret, i; 2697 2698 /* Non-zero func_info_cnt implies valid btf */ 2699 if (!aux->func_info_cnt) 2700 return 0; 2701 main_btf_id = aux->func_info[0].type_id; 2702 2703 t = btf_type_by_id(btf, main_btf_id); 2704 if (!t) { 2705 verbose(env, "invalid btf id for main subprog in func_info\n"); 2706 return -EINVAL; 2707 } 2708 2709 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2710 if (IS_ERR(name)) { 2711 ret = PTR_ERR(name); 2712 /* If there is no tag present, there is no exception callback */ 2713 if (ret == -ENOENT) 2714 ret = 0; 2715 else if (ret == -EEXIST) 2716 verbose(env, "multiple exception callback tags for main subprog\n"); 2717 return ret; 2718 } 2719 2720 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2721 if (ret < 0) { 2722 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2723 return ret; 2724 } 2725 id = ret; 2726 t = btf_type_by_id(btf, id); 2727 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2728 verbose(env, "exception callback '%s' must have global linkage\n", name); 2729 return -EINVAL; 2730 } 2731 ret = 0; 2732 for (i = 0; i < aux->func_info_cnt; i++) { 2733 if (aux->func_info[i].type_id != id) 2734 continue; 2735 ret = aux->func_info[i].insn_off; 2736 /* Further func_info and subprog checks will also happen 2737 * later, so assume this is the right insn_off for now. 2738 */ 2739 if (!ret) { 2740 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2741 ret = -EINVAL; 2742 } 2743 } 2744 if (!ret) { 2745 verbose(env, "exception callback type id not found in func_info\n"); 2746 ret = -EINVAL; 2747 } 2748 return ret; 2749 } 2750 2751 #define MAX_KFUNC_BTFS 256 2752 2753 struct bpf_kfunc_btf { 2754 struct btf *btf; 2755 struct module *module; 2756 u16 offset; 2757 }; 2758 2759 struct bpf_kfunc_btf_tab { 2760 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2761 u32 nr_descs; 2762 }; 2763 2764 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2765 { 2766 const struct bpf_kfunc_desc *d0 = a; 2767 const struct bpf_kfunc_desc *d1 = b; 2768 2769 /* func_id is not greater than BTF_MAX_TYPE */ 2770 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2771 } 2772 2773 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2774 { 2775 const struct bpf_kfunc_btf *d0 = a; 2776 const struct bpf_kfunc_btf *d1 = b; 2777 2778 return d0->offset - d1->offset; 2779 } 2780 2781 static struct bpf_kfunc_desc * 2782 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2783 { 2784 struct bpf_kfunc_desc desc = { 2785 .func_id = func_id, 2786 .offset = offset, 2787 }; 2788 struct bpf_kfunc_desc_tab *tab; 2789 2790 tab = prog->aux->kfunc_tab; 2791 return bsearch(&desc, tab->descs, tab->nr_descs, 2792 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2793 } 2794 2795 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2796 u16 btf_fd_idx, u8 **func_addr) 2797 { 2798 const struct bpf_kfunc_desc *desc; 2799 2800 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2801 if (!desc) 2802 return -EFAULT; 2803 2804 *func_addr = (u8 *)desc->addr; 2805 return 0; 2806 } 2807 2808 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2809 s16 offset) 2810 { 2811 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2812 struct bpf_kfunc_btf_tab *tab; 2813 struct bpf_kfunc_btf *b; 2814 struct module *mod; 2815 struct btf *btf; 2816 int btf_fd; 2817 2818 tab = env->prog->aux->kfunc_btf_tab; 2819 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2820 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2821 if (!b) { 2822 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2823 verbose(env, "too many different module BTFs\n"); 2824 return ERR_PTR(-E2BIG); 2825 } 2826 2827 if (bpfptr_is_null(env->fd_array)) { 2828 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2829 return ERR_PTR(-EPROTO); 2830 } 2831 2832 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2833 offset * sizeof(btf_fd), 2834 sizeof(btf_fd))) 2835 return ERR_PTR(-EFAULT); 2836 2837 btf = btf_get_by_fd(btf_fd); 2838 if (IS_ERR(btf)) { 2839 verbose(env, "invalid module BTF fd specified\n"); 2840 return btf; 2841 } 2842 2843 if (!btf_is_module(btf)) { 2844 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2845 btf_put(btf); 2846 return ERR_PTR(-EINVAL); 2847 } 2848 2849 mod = btf_try_get_module(btf); 2850 if (!mod) { 2851 btf_put(btf); 2852 return ERR_PTR(-ENXIO); 2853 } 2854 2855 b = &tab->descs[tab->nr_descs++]; 2856 b->btf = btf; 2857 b->module = mod; 2858 b->offset = offset; 2859 2860 /* sort() reorders entries by value, so b may no longer point 2861 * to the right entry after this 2862 */ 2863 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2864 kfunc_btf_cmp_by_off, NULL); 2865 } else { 2866 btf = b->btf; 2867 } 2868 2869 return btf; 2870 } 2871 2872 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2873 { 2874 if (!tab) 2875 return; 2876 2877 while (tab->nr_descs--) { 2878 module_put(tab->descs[tab->nr_descs].module); 2879 btf_put(tab->descs[tab->nr_descs].btf); 2880 } 2881 kfree(tab); 2882 } 2883 2884 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2885 { 2886 if (offset) { 2887 if (offset < 0) { 2888 /* In the future, this can be allowed to increase limit 2889 * of fd index into fd_array, interpreted as u16. 2890 */ 2891 verbose(env, "negative offset disallowed for kernel module function call\n"); 2892 return ERR_PTR(-EINVAL); 2893 } 2894 2895 return __find_kfunc_desc_btf(env, offset); 2896 } 2897 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2898 } 2899 2900 #define KF_IMPL_SUFFIX "_impl" 2901 2902 static const struct btf_type *find_kfunc_impl_proto(struct bpf_verifier_env *env, 2903 struct btf *btf, 2904 const char *func_name) 2905 { 2906 char *buf = env->tmp_str_buf; 2907 const struct btf_type *func; 2908 s32 impl_id; 2909 int len; 2910 2911 len = snprintf(buf, TMP_STR_BUF_LEN, "%s%s", func_name, KF_IMPL_SUFFIX); 2912 if (len < 0 || len >= TMP_STR_BUF_LEN) { 2913 verbose(env, "function name %s%s is too long\n", func_name, KF_IMPL_SUFFIX); 2914 return NULL; 2915 } 2916 2917 impl_id = btf_find_by_name_kind(btf, buf, BTF_KIND_FUNC); 2918 if (impl_id <= 0) { 2919 verbose(env, "cannot find function %s in BTF\n", buf); 2920 return NULL; 2921 } 2922 2923 func = btf_type_by_id(btf, impl_id); 2924 2925 return btf_type_by_id(btf, func->type); 2926 } 2927 2928 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 2929 s32 func_id, 2930 s16 offset, 2931 struct bpf_kfunc_meta *kfunc) 2932 { 2933 const struct btf_type *func, *func_proto; 2934 const char *func_name; 2935 u32 *kfunc_flags; 2936 struct btf *btf; 2937 2938 if (func_id <= 0) { 2939 verbose(env, "invalid kernel function btf_id %d\n", func_id); 2940 return -EINVAL; 2941 } 2942 2943 btf = find_kfunc_desc_btf(env, offset); 2944 if (IS_ERR(btf)) { 2945 verbose(env, "failed to find BTF for kernel function\n"); 2946 return PTR_ERR(btf); 2947 } 2948 2949 /* 2950 * Note that kfunc_flags may be NULL at this point, which 2951 * means that we couldn't find func_id in any relevant 2952 * kfunc_id_set. This most likely indicates an invalid kfunc 2953 * call. However we don't fail with an error here, 2954 * and let the caller decide what to do with NULL kfunc->flags. 2955 */ 2956 kfunc_flags = btf_kfunc_flags(btf, func_id, env->prog); 2957 2958 func = btf_type_by_id(btf, func_id); 2959 if (!func || !btf_type_is_func(func)) { 2960 verbose(env, "kernel btf_id %d is not a function\n", func_id); 2961 return -EINVAL; 2962 } 2963 2964 func_name = btf_name_by_offset(btf, func->name_off); 2965 2966 /* 2967 * An actual prototype of a kfunc with KF_IMPLICIT_ARGS flag 2968 * can be found through the counterpart _impl kfunc. 2969 */ 2970 if (kfunc_flags && (*kfunc_flags & KF_IMPLICIT_ARGS)) 2971 func_proto = find_kfunc_impl_proto(env, btf, func_name); 2972 else 2973 func_proto = btf_type_by_id(btf, func->type); 2974 2975 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2976 verbose(env, "kernel function btf_id %d does not have a valid func_proto\n", 2977 func_id); 2978 return -EINVAL; 2979 } 2980 2981 memset(kfunc, 0, sizeof(*kfunc)); 2982 kfunc->btf = btf; 2983 kfunc->id = func_id; 2984 kfunc->name = func_name; 2985 kfunc->proto = func_proto; 2986 kfunc->flags = kfunc_flags; 2987 2988 return 0; 2989 } 2990 2991 int bpf_add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, u16 offset) 2992 { 2993 struct bpf_kfunc_btf_tab *btf_tab; 2994 struct btf_func_model func_model; 2995 struct bpf_kfunc_desc_tab *tab; 2996 struct bpf_prog_aux *prog_aux; 2997 struct bpf_kfunc_meta kfunc; 2998 struct bpf_kfunc_desc *desc; 2999 unsigned long addr; 3000 int err; 3001 3002 prog_aux = env->prog->aux; 3003 tab = prog_aux->kfunc_tab; 3004 btf_tab = prog_aux->kfunc_btf_tab; 3005 if (!tab) { 3006 if (!btf_vmlinux) { 3007 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 3008 return -ENOTSUPP; 3009 } 3010 3011 if (!env->prog->jit_requested) { 3012 verbose(env, "JIT is required for calling kernel function\n"); 3013 return -ENOTSUPP; 3014 } 3015 3016 if (!bpf_jit_supports_kfunc_call()) { 3017 verbose(env, "JIT does not support calling kernel function\n"); 3018 return -ENOTSUPP; 3019 } 3020 3021 if (!env->prog->gpl_compatible) { 3022 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 3023 return -EINVAL; 3024 } 3025 3026 tab = kzalloc_obj(*tab, GFP_KERNEL_ACCOUNT); 3027 if (!tab) 3028 return -ENOMEM; 3029 prog_aux->kfunc_tab = tab; 3030 } 3031 3032 /* func_id == 0 is always invalid, but instead of returning an error, be 3033 * conservative and wait until the code elimination pass before returning 3034 * error, so that invalid calls that get pruned out can be in BPF programs 3035 * loaded from userspace. It is also required that offset be untouched 3036 * for such calls. 3037 */ 3038 if (!func_id && !offset) 3039 return 0; 3040 3041 if (!btf_tab && offset) { 3042 btf_tab = kzalloc_obj(*btf_tab, GFP_KERNEL_ACCOUNT); 3043 if (!btf_tab) 3044 return -ENOMEM; 3045 prog_aux->kfunc_btf_tab = btf_tab; 3046 } 3047 3048 if (find_kfunc_desc(env->prog, func_id, offset)) 3049 return 0; 3050 3051 if (tab->nr_descs == MAX_KFUNC_DESCS) { 3052 verbose(env, "too many different kernel function calls\n"); 3053 return -E2BIG; 3054 } 3055 3056 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 3057 if (err) 3058 return err; 3059 3060 addr = kallsyms_lookup_name(kfunc.name); 3061 if (!addr) { 3062 verbose(env, "cannot find address for kernel function %s\n", kfunc.name); 3063 return -EINVAL; 3064 } 3065 3066 if (bpf_dev_bound_kfunc_id(func_id)) { 3067 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 3068 if (err) 3069 return err; 3070 } 3071 3072 err = btf_distill_func_proto(&env->log, kfunc.btf, kfunc.proto, kfunc.name, &func_model); 3073 if (err) 3074 return err; 3075 3076 desc = &tab->descs[tab->nr_descs++]; 3077 desc->func_id = func_id; 3078 desc->offset = offset; 3079 desc->addr = addr; 3080 desc->func_model = func_model; 3081 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 3082 kfunc_desc_cmp_by_id_off, NULL); 3083 return 0; 3084 } 3085 3086 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 3087 { 3088 return !!prog->aux->kfunc_tab; 3089 } 3090 3091 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 3092 { 3093 struct bpf_subprog_info *subprog = env->subprog_info; 3094 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 3095 struct bpf_insn *insn = env->prog->insnsi; 3096 3097 /* Add entry function. */ 3098 ret = add_subprog(env, 0); 3099 if (ret) 3100 return ret; 3101 3102 for (i = 0; i < insn_cnt; i++, insn++) { 3103 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 3104 !bpf_pseudo_kfunc_call(insn)) 3105 continue; 3106 3107 if (!env->bpf_capable) { 3108 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 3109 return -EPERM; 3110 } 3111 3112 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 3113 ret = add_subprog(env, i + insn->imm + 1); 3114 else 3115 ret = bpf_add_kfunc_call(env, insn->imm, insn->off); 3116 3117 if (ret < 0) 3118 return ret; 3119 } 3120 3121 ret = bpf_find_exception_callback_insn_off(env); 3122 if (ret < 0) 3123 return ret; 3124 ex_cb_insn = ret; 3125 3126 /* If ex_cb_insn > 0, this means that the main program has a subprog 3127 * marked using BTF decl tag to serve as the exception callback. 3128 */ 3129 if (ex_cb_insn) { 3130 ret = add_subprog(env, ex_cb_insn); 3131 if (ret < 0) 3132 return ret; 3133 for (i = 1; i < env->subprog_cnt; i++) { 3134 if (env->subprog_info[i].start != ex_cb_insn) 3135 continue; 3136 env->exception_callback_subprog = i; 3137 bpf_mark_subprog_exc_cb(env, i); 3138 break; 3139 } 3140 } 3141 3142 /* Add a fake 'exit' subprog which could simplify subprog iteration 3143 * logic. 'subprog_cnt' should not be increased. 3144 */ 3145 subprog[env->subprog_cnt].start = insn_cnt; 3146 3147 if (env->log.level & BPF_LOG_LEVEL2) 3148 for (i = 0; i < env->subprog_cnt; i++) 3149 verbose(env, "func#%d @%d\n", i, subprog[i].start); 3150 3151 return 0; 3152 } 3153 3154 static int check_subprogs(struct bpf_verifier_env *env) 3155 { 3156 int i, subprog_start, subprog_end, off, cur_subprog = 0; 3157 struct bpf_subprog_info *subprog = env->subprog_info; 3158 struct bpf_insn *insn = env->prog->insnsi; 3159 int insn_cnt = env->prog->len; 3160 3161 /* now check that all jumps are within the same subprog */ 3162 subprog_start = subprog[cur_subprog].start; 3163 subprog_end = subprog[cur_subprog + 1].start; 3164 for (i = 0; i < insn_cnt; i++) { 3165 u8 code = insn[i].code; 3166 3167 if (code == (BPF_JMP | BPF_CALL) && 3168 insn[i].src_reg == 0 && 3169 insn[i].imm == BPF_FUNC_tail_call) { 3170 subprog[cur_subprog].has_tail_call = true; 3171 subprog[cur_subprog].tail_call_reachable = true; 3172 } 3173 if (BPF_CLASS(code) == BPF_LD && 3174 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 3175 subprog[cur_subprog].has_ld_abs = true; 3176 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 3177 goto next; 3178 if (BPF_OP(code) == BPF_CALL) 3179 goto next; 3180 if (BPF_OP(code) == BPF_EXIT) { 3181 subprog[cur_subprog].exit_idx = i; 3182 goto next; 3183 } 3184 off = i + bpf_jmp_offset(&insn[i]) + 1; 3185 if (off < subprog_start || off >= subprog_end) { 3186 verbose(env, "jump out of range from insn %d to %d\n", i, off); 3187 return -EINVAL; 3188 } 3189 next: 3190 if (i == subprog_end - 1) { 3191 /* to avoid fall-through from one subprog into another 3192 * the last insn of the subprog should be either exit 3193 * or unconditional jump back or bpf_throw call 3194 */ 3195 if (code != (BPF_JMP | BPF_EXIT) && 3196 code != (BPF_JMP32 | BPF_JA) && 3197 code != (BPF_JMP | BPF_JA)) { 3198 verbose(env, "last insn is not an exit or jmp\n"); 3199 return -EINVAL; 3200 } 3201 subprog_start = subprog_end; 3202 cur_subprog++; 3203 if (cur_subprog < env->subprog_cnt) 3204 subprog_end = subprog[cur_subprog + 1].start; 3205 } 3206 } 3207 return 0; 3208 } 3209 3210 /* 3211 * Sort subprogs in topological order so that leaf subprogs come first and 3212 * their callers come later. This is a DFS post-order traversal of the call 3213 * graph. Scan only reachable instructions (those in the computed postorder) of 3214 * the current subprog to discover callees (direct subprogs and sync 3215 * callbacks). 3216 */ 3217 static int sort_subprogs_topo(struct bpf_verifier_env *env) 3218 { 3219 struct bpf_subprog_info *si = env->subprog_info; 3220 int *insn_postorder = env->cfg.insn_postorder; 3221 struct bpf_insn *insn = env->prog->insnsi; 3222 int cnt = env->subprog_cnt; 3223 int *dfs_stack = NULL; 3224 int top = 0, order = 0; 3225 int i, ret = 0; 3226 u8 *color = NULL; 3227 3228 color = kvzalloc_objs(*color, cnt, GFP_KERNEL_ACCOUNT); 3229 dfs_stack = kvmalloc_objs(*dfs_stack, cnt, GFP_KERNEL_ACCOUNT); 3230 if (!color || !dfs_stack) { 3231 ret = -ENOMEM; 3232 goto out; 3233 } 3234 3235 /* 3236 * DFS post-order traversal. 3237 * Color values: 0 = unvisited, 1 = on stack, 2 = done. 3238 */ 3239 for (i = 0; i < cnt; i++) { 3240 if (color[i]) 3241 continue; 3242 color[i] = 1; 3243 dfs_stack[top++] = i; 3244 3245 while (top > 0) { 3246 int cur = dfs_stack[top - 1]; 3247 int po_start = si[cur].postorder_start; 3248 int po_end = si[cur + 1].postorder_start; 3249 bool pushed = false; 3250 int j; 3251 3252 for (j = po_start; j < po_end; j++) { 3253 int idx = insn_postorder[j]; 3254 int callee; 3255 3256 if (!bpf_pseudo_call(&insn[idx]) && !bpf_pseudo_func(&insn[idx])) 3257 continue; 3258 callee = bpf_find_subprog(env, idx + insn[idx].imm + 1); 3259 if (callee < 0) { 3260 ret = -EFAULT; 3261 goto out; 3262 } 3263 if (color[callee] == 2) 3264 continue; 3265 if (color[callee] == 1) { 3266 if (bpf_pseudo_func(&insn[idx])) 3267 continue; 3268 verbose(env, "recursive call from %s() to %s()\n", 3269 subprog_name(env, cur), 3270 subprog_name(env, callee)); 3271 ret = -EINVAL; 3272 goto out; 3273 } 3274 color[callee] = 1; 3275 dfs_stack[top++] = callee; 3276 pushed = true; 3277 break; 3278 } 3279 3280 if (!pushed) { 3281 color[cur] = 2; 3282 env->subprog_topo_order[order++] = cur; 3283 top--; 3284 } 3285 } 3286 } 3287 3288 if (env->log.level & BPF_LOG_LEVEL2) 3289 for (i = 0; i < cnt; i++) 3290 verbose(env, "topo_order[%d] = %s\n", 3291 i, subprog_name(env, env->subprog_topo_order[i])); 3292 out: 3293 kvfree(dfs_stack); 3294 kvfree(color); 3295 return ret; 3296 } 3297 3298 static int mark_stack_slot_obj_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3299 int spi, int nr_slots) 3300 { 3301 int i; 3302 3303 for (i = 0; i < nr_slots; i++) 3304 mark_stack_slot_scratched(env, spi - i); 3305 return 0; 3306 } 3307 3308 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3309 { 3310 int spi; 3311 3312 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3313 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3314 * check_kfunc_call. 3315 */ 3316 if (reg->type == CONST_PTR_TO_DYNPTR) 3317 return 0; 3318 spi = dynptr_get_spi(env, reg); 3319 if (spi < 0) 3320 return spi; 3321 /* Caller ensures dynptr is valid and initialized, which means spi is in 3322 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3323 * read. 3324 */ 3325 return mark_stack_slot_obj_read(env, reg, spi, BPF_DYNPTR_NR_SLOTS); 3326 } 3327 3328 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3329 int spi, int nr_slots) 3330 { 3331 return mark_stack_slot_obj_read(env, reg, spi, nr_slots); 3332 } 3333 3334 static int mark_irq_flag_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3335 { 3336 int spi; 3337 3338 spi = irq_flag_get_spi(env, reg); 3339 if (spi < 0) 3340 return spi; 3341 return mark_stack_slot_obj_read(env, reg, spi, 1); 3342 } 3343 3344 /* This function is supposed to be used by the following 32-bit optimization 3345 * code only. It returns TRUE if the source or destination register operates 3346 * on 64-bit, otherwise return FALSE. 3347 */ 3348 bool bpf_is_reg64(struct bpf_insn *insn, 3349 u32 regno, struct bpf_reg_state *reg, enum bpf_reg_arg_type t) 3350 { 3351 u8 code, class, op; 3352 3353 code = insn->code; 3354 class = BPF_CLASS(code); 3355 op = BPF_OP(code); 3356 if (class == BPF_JMP) { 3357 /* BPF_EXIT for "main" will reach here. Return TRUE 3358 * conservatively. 3359 */ 3360 if (op == BPF_EXIT) 3361 return true; 3362 if (op == BPF_CALL) { 3363 /* BPF to BPF call will reach here because of marking 3364 * caller saved clobber with DST_OP_NO_MARK for which we 3365 * don't care the register def because they are anyway 3366 * marked as NOT_INIT already. 3367 */ 3368 if (insn->src_reg == BPF_PSEUDO_CALL) 3369 return false; 3370 /* Helper call will reach here because of arg type 3371 * check, conservatively return TRUE. 3372 */ 3373 if (t == SRC_OP) 3374 return true; 3375 3376 return false; 3377 } 3378 } 3379 3380 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3381 return false; 3382 3383 if (class == BPF_ALU64 || class == BPF_JMP || 3384 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3385 return true; 3386 3387 if (class == BPF_ALU || class == BPF_JMP32) 3388 return false; 3389 3390 if (class == BPF_LDX) { 3391 if (t != SRC_OP) 3392 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3393 /* LDX source must be ptr. */ 3394 return true; 3395 } 3396 3397 if (class == BPF_STX) { 3398 /* BPF_STX (including atomic variants) has one or more source 3399 * operands, one of which is a ptr. Check whether the caller is 3400 * asking about it. 3401 */ 3402 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3403 return true; 3404 return BPF_SIZE(code) == BPF_DW; 3405 } 3406 3407 if (class == BPF_LD) { 3408 u8 mode = BPF_MODE(code); 3409 3410 /* LD_IMM64 */ 3411 if (mode == BPF_IMM) 3412 return true; 3413 3414 /* Both LD_IND and LD_ABS return 32-bit data. */ 3415 if (t != SRC_OP) 3416 return false; 3417 3418 /* Implicit ctx ptr. */ 3419 if (regno == BPF_REG_6) 3420 return true; 3421 3422 /* Explicit source could be any width. */ 3423 return true; 3424 } 3425 3426 if (class == BPF_ST) 3427 /* The only source register for BPF_ST is a ptr. */ 3428 return true; 3429 3430 /* Conservatively return true at default. */ 3431 return true; 3432 } 3433 3434 static void mark_insn_zext(struct bpf_verifier_env *env, 3435 struct bpf_reg_state *reg) 3436 { 3437 s32 def_idx = reg->subreg_def; 3438 3439 if (def_idx == DEF_NOT_SUBREG) 3440 return; 3441 3442 env->insn_aux_data[def_idx - 1].zext_dst = true; 3443 /* The dst will be zero extended, so won't be sub-register anymore. */ 3444 reg->subreg_def = DEF_NOT_SUBREG; 3445 } 3446 3447 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3448 enum bpf_reg_arg_type t) 3449 { 3450 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3451 struct bpf_reg_state *reg; 3452 bool rw64; 3453 3454 mark_reg_scratched(env, regno); 3455 3456 reg = ®s[regno]; 3457 rw64 = bpf_is_reg64(insn, regno, reg, t); 3458 if (t == SRC_OP) { 3459 /* check whether register used as source operand can be read */ 3460 if (reg->type == NOT_INIT) { 3461 verbose(env, "R%d !read_ok\n", regno); 3462 return -EACCES; 3463 } 3464 /* We don't need to worry about FP liveness because it's read-only */ 3465 if (regno == BPF_REG_FP) 3466 return 0; 3467 3468 if (rw64) 3469 mark_insn_zext(env, reg); 3470 3471 return 0; 3472 } else { 3473 /* check whether register used as dest operand can be written to */ 3474 if (regno == BPF_REG_FP) { 3475 verbose(env, "frame pointer is read only\n"); 3476 return -EACCES; 3477 } 3478 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3479 if (t == DST_OP) 3480 mark_reg_unknown(env, regs, regno); 3481 } 3482 return 0; 3483 } 3484 3485 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3486 enum bpf_reg_arg_type t) 3487 { 3488 struct bpf_verifier_state *vstate = env->cur_state; 3489 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3490 3491 return __check_reg_arg(env, state->regs, regno, t); 3492 } 3493 3494 static int insn_stack_access_flags(int frameno, int spi) 3495 { 3496 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3497 } 3498 3499 static void mark_indirect_target(struct bpf_verifier_env *env, int idx) 3500 { 3501 env->insn_aux_data[idx].indirect_target = true; 3502 } 3503 3504 #define LR_FRAMENO_BITS 3 3505 #define LR_SPI_BITS 6 3506 #define LR_ENTRY_BITS (LR_SPI_BITS + LR_FRAMENO_BITS + 1) 3507 #define LR_SIZE_BITS 4 3508 #define LR_FRAMENO_MASK ((1ull << LR_FRAMENO_BITS) - 1) 3509 #define LR_SPI_MASK ((1ull << LR_SPI_BITS) - 1) 3510 #define LR_SIZE_MASK ((1ull << LR_SIZE_BITS) - 1) 3511 #define LR_SPI_OFF LR_FRAMENO_BITS 3512 #define LR_IS_REG_OFF (LR_SPI_BITS + LR_FRAMENO_BITS) 3513 #define LINKED_REGS_MAX 6 3514 3515 struct linked_reg { 3516 u8 frameno; 3517 union { 3518 u8 spi; 3519 u8 regno; 3520 }; 3521 bool is_reg; 3522 }; 3523 3524 struct linked_regs { 3525 int cnt; 3526 struct linked_reg entries[LINKED_REGS_MAX]; 3527 }; 3528 3529 static struct linked_reg *linked_regs_push(struct linked_regs *s) 3530 { 3531 if (s->cnt < LINKED_REGS_MAX) 3532 return &s->entries[s->cnt++]; 3533 3534 return NULL; 3535 } 3536 3537 /* Use u64 as a vector of 6 10-bit values, use first 4-bits to track 3538 * number of elements currently in stack. 3539 * Pack one history entry for linked registers as 10 bits in the following format: 3540 * - 3-bits frameno 3541 * - 6-bits spi_or_reg 3542 * - 1-bit is_reg 3543 */ 3544 static u64 linked_regs_pack(struct linked_regs *s) 3545 { 3546 u64 val = 0; 3547 int i; 3548 3549 for (i = 0; i < s->cnt; ++i) { 3550 struct linked_reg *e = &s->entries[i]; 3551 u64 tmp = 0; 3552 3553 tmp |= e->frameno; 3554 tmp |= e->spi << LR_SPI_OFF; 3555 tmp |= (e->is_reg ? 1 : 0) << LR_IS_REG_OFF; 3556 3557 val <<= LR_ENTRY_BITS; 3558 val |= tmp; 3559 } 3560 val <<= LR_SIZE_BITS; 3561 val |= s->cnt; 3562 return val; 3563 } 3564 3565 static void linked_regs_unpack(u64 val, struct linked_regs *s) 3566 { 3567 int i; 3568 3569 s->cnt = val & LR_SIZE_MASK; 3570 val >>= LR_SIZE_BITS; 3571 3572 for (i = 0; i < s->cnt; ++i) { 3573 struct linked_reg *e = &s->entries[i]; 3574 3575 e->frameno = val & LR_FRAMENO_MASK; 3576 e->spi = (val >> LR_SPI_OFF) & LR_SPI_MASK; 3577 e->is_reg = (val >> LR_IS_REG_OFF) & 0x1; 3578 val >>= LR_ENTRY_BITS; 3579 } 3580 } 3581 3582 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3583 { 3584 const struct btf_type *func; 3585 struct btf *desc_btf; 3586 3587 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3588 return NULL; 3589 3590 desc_btf = find_kfunc_desc_btf(data, insn->off); 3591 if (IS_ERR(desc_btf)) 3592 return "<error>"; 3593 3594 func = btf_type_by_id(desc_btf, insn->imm); 3595 return btf_name_by_offset(desc_btf, func->name_off); 3596 } 3597 3598 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn) 3599 { 3600 const struct bpf_insn_cbs cbs = { 3601 .cb_call = disasm_kfunc_name, 3602 .cb_print = verbose, 3603 .private_data = env, 3604 }; 3605 3606 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3607 } 3608 3609 /* If any register R in hist->linked_regs is marked as precise in bt, 3610 * do bt_set_frame_{reg,slot}(bt, R) for all registers in hist->linked_regs. 3611 */ 3612 void bpf_bt_sync_linked_regs(struct backtrack_state *bt, struct bpf_jmp_history_entry *hist) 3613 { 3614 struct linked_regs linked_regs; 3615 bool some_precise = false; 3616 int i; 3617 3618 if (!hist || hist->linked_regs == 0) 3619 return; 3620 3621 linked_regs_unpack(hist->linked_regs, &linked_regs); 3622 for (i = 0; i < linked_regs.cnt; ++i) { 3623 struct linked_reg *e = &linked_regs.entries[i]; 3624 3625 if ((e->is_reg && bt_is_frame_reg_set(bt, e->frameno, e->regno)) || 3626 (!e->is_reg && bt_is_frame_slot_set(bt, e->frameno, e->spi))) { 3627 some_precise = true; 3628 break; 3629 } 3630 } 3631 3632 if (!some_precise) 3633 return; 3634 3635 for (i = 0; i < linked_regs.cnt; ++i) { 3636 struct linked_reg *e = &linked_regs.entries[i]; 3637 3638 if (e->is_reg) 3639 bpf_bt_set_frame_reg(bt, e->frameno, e->regno); 3640 else 3641 bpf_bt_set_frame_slot(bt, e->frameno, e->spi); 3642 } 3643 } 3644 3645 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3646 { 3647 return bpf_mark_chain_precision(env, env->cur_state, regno, NULL); 3648 } 3649 3650 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 3651 * desired reg and stack masks across all relevant frames 3652 */ 3653 static int mark_chain_precision_batch(struct bpf_verifier_env *env, 3654 struct bpf_verifier_state *starting_state) 3655 { 3656 return bpf_mark_chain_precision(env, starting_state, -1, NULL); 3657 } 3658 3659 static bool is_spillable_regtype(enum bpf_reg_type type) 3660 { 3661 switch (base_type(type)) { 3662 case PTR_TO_MAP_VALUE: 3663 case PTR_TO_STACK: 3664 case PTR_TO_CTX: 3665 case PTR_TO_PACKET: 3666 case PTR_TO_PACKET_META: 3667 case PTR_TO_PACKET_END: 3668 case PTR_TO_FLOW_KEYS: 3669 case CONST_PTR_TO_MAP: 3670 case PTR_TO_SOCKET: 3671 case PTR_TO_SOCK_COMMON: 3672 case PTR_TO_TCP_SOCK: 3673 case PTR_TO_XDP_SOCK: 3674 case PTR_TO_BTF_ID: 3675 case PTR_TO_BUF: 3676 case PTR_TO_MEM: 3677 case PTR_TO_FUNC: 3678 case PTR_TO_MAP_KEY: 3679 case PTR_TO_ARENA: 3680 return true; 3681 default: 3682 return false; 3683 } 3684 } 3685 3686 3687 /* check if register is a constant scalar value */ 3688 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 3689 { 3690 return reg->type == SCALAR_VALUE && 3691 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 3692 } 3693 3694 /* assuming is_reg_const() is true, return constant value of a register */ 3695 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 3696 { 3697 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 3698 } 3699 3700 static bool __is_pointer_value(bool allow_ptr_leaks, 3701 const struct bpf_reg_state *reg) 3702 { 3703 if (allow_ptr_leaks) 3704 return false; 3705 3706 return reg->type != SCALAR_VALUE; 3707 } 3708 3709 static void clear_scalar_id(struct bpf_reg_state *reg) 3710 { 3711 reg->id = 0; 3712 reg->delta = 0; 3713 } 3714 3715 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 3716 struct bpf_reg_state *src_reg) 3717 { 3718 if (src_reg->type != SCALAR_VALUE) 3719 return; 3720 /* 3721 * The verifier is processing rX = rY insn and 3722 * rY->id has special linked register already. 3723 * Cleared it, since multiple rX += const are not supported. 3724 */ 3725 if (src_reg->id & BPF_ADD_CONST) 3726 clear_scalar_id(src_reg); 3727 /* 3728 * Ensure that src_reg has a valid ID that will be copied to 3729 * dst_reg and then will be used by sync_linked_regs() to 3730 * propagate min/max range. 3731 */ 3732 if (!src_reg->id && !tnum_is_const(src_reg->var_off)) 3733 src_reg->id = ++env->id_gen; 3734 } 3735 3736 /* Copy src state preserving dst->parent and dst->live fields */ 3737 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 3738 { 3739 *dst = *src; 3740 } 3741 3742 static void save_register_state(struct bpf_verifier_env *env, 3743 struct bpf_func_state *state, 3744 int spi, struct bpf_reg_state *reg, 3745 int size) 3746 { 3747 int i; 3748 3749 copy_register_state(&state->stack[spi].spilled_ptr, reg); 3750 3751 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3752 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 3753 3754 /* size < 8 bytes spill */ 3755 for (; i; i--) 3756 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 3757 } 3758 3759 static bool is_bpf_st_mem(struct bpf_insn *insn) 3760 { 3761 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 3762 } 3763 3764 static int get_reg_width(struct bpf_reg_state *reg) 3765 { 3766 return fls64(reg->umax_value); 3767 } 3768 3769 /* See comment for mark_fastcall_pattern_for_call() */ 3770 static void check_fastcall_stack_contract(struct bpf_verifier_env *env, 3771 struct bpf_func_state *state, int insn_idx, int off) 3772 { 3773 struct bpf_subprog_info *subprog = &env->subprog_info[state->subprogno]; 3774 struct bpf_insn_aux_data *aux = env->insn_aux_data; 3775 int i; 3776 3777 if (subprog->fastcall_stack_off <= off || aux[insn_idx].fastcall_pattern) 3778 return; 3779 /* access to the region [max_stack_depth .. fastcall_stack_off) 3780 * from something that is not a part of the fastcall pattern, 3781 * disable fastcall rewrites for current subprogram by setting 3782 * fastcall_stack_off to a value smaller than any possible offset. 3783 */ 3784 subprog->fastcall_stack_off = S16_MIN; 3785 /* reset fastcall aux flags within subprogram, 3786 * happens at most once per subprogram 3787 */ 3788 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 3789 aux[i].fastcall_spills_num = 0; 3790 aux[i].fastcall_pattern = 0; 3791 } 3792 } 3793 3794 static void scrub_special_slot(struct bpf_func_state *state, int spi) 3795 { 3796 int i; 3797 3798 /* regular write of data into stack destroys any spilled ptr */ 3799 state->stack[spi].spilled_ptr.type = NOT_INIT; 3800 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 3801 if (is_stack_slot_special(&state->stack[spi])) 3802 for (i = 0; i < BPF_REG_SIZE; i++) 3803 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 3804 } 3805 3806 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3807 * stack boundary and alignment are checked in check_mem_access() 3808 */ 3809 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3810 /* stack frame we're writing to */ 3811 struct bpf_func_state *state, 3812 int off, int size, int value_regno, 3813 int insn_idx) 3814 { 3815 struct bpf_func_state *cur; /* state of the current function */ 3816 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3817 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3818 struct bpf_reg_state *reg = NULL; 3819 int insn_flags = insn_stack_access_flags(state->frameno, spi); 3820 3821 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 3822 * so it's aligned access and [off, off + size) are within stack limits 3823 */ 3824 if (!env->allow_ptr_leaks && 3825 bpf_is_spilled_reg(&state->stack[spi]) && 3826 !bpf_is_spilled_scalar_reg(&state->stack[spi]) && 3827 size != BPF_REG_SIZE) { 3828 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3829 return -EACCES; 3830 } 3831 3832 cur = env->cur_state->frame[env->cur_state->curframe]; 3833 if (value_regno >= 0) 3834 reg = &cur->regs[value_regno]; 3835 if (!env->bypass_spec_v4) { 3836 bool sanitize = reg && is_spillable_regtype(reg->type); 3837 3838 for (i = 0; i < size; i++) { 3839 u8 type = state->stack[spi].slot_type[i]; 3840 3841 if (type != STACK_MISC && type != STACK_ZERO) { 3842 sanitize = true; 3843 break; 3844 } 3845 } 3846 3847 if (sanitize) 3848 env->insn_aux_data[insn_idx].nospec_result = true; 3849 } 3850 3851 err = destroy_if_dynptr_stack_slot(env, state, spi); 3852 if (err) 3853 return err; 3854 3855 check_fastcall_stack_contract(env, state, insn_idx, off); 3856 mark_stack_slot_scratched(env, spi); 3857 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 3858 bool reg_value_fits; 3859 3860 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 3861 /* Make sure that reg had an ID to build a relation on spill. */ 3862 if (reg_value_fits) 3863 assign_scalar_id_before_mov(env, reg); 3864 save_register_state(env, state, spi, reg, size); 3865 /* Break the relation on a narrowing spill. */ 3866 if (!reg_value_fits) 3867 state->stack[spi].spilled_ptr.id = 0; 3868 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 3869 env->bpf_capable) { 3870 struct bpf_reg_state *tmp_reg = &env->fake_reg[0]; 3871 3872 memset(tmp_reg, 0, sizeof(*tmp_reg)); 3873 __mark_reg_known(tmp_reg, insn->imm); 3874 tmp_reg->type = SCALAR_VALUE; 3875 save_register_state(env, state, spi, tmp_reg, size); 3876 } else if (reg && is_spillable_regtype(reg->type)) { 3877 /* register containing pointer is being spilled into stack */ 3878 if (size != BPF_REG_SIZE) { 3879 verbose_linfo(env, insn_idx, "; "); 3880 verbose(env, "invalid size of register spill\n"); 3881 return -EACCES; 3882 } 3883 if (state != cur && reg->type == PTR_TO_STACK) { 3884 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 3885 return -EINVAL; 3886 } 3887 save_register_state(env, state, spi, reg, size); 3888 } else { 3889 u8 type = STACK_MISC; 3890 3891 scrub_special_slot(state, spi); 3892 3893 /* when we zero initialize stack slots mark them as such */ 3894 if ((reg && bpf_register_is_null(reg)) || 3895 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 3896 /* STACK_ZERO case happened because register spill 3897 * wasn't properly aligned at the stack slot boundary, 3898 * so it's not a register spill anymore; force 3899 * originating register to be precise to make 3900 * STACK_ZERO correct for subsequent states 3901 */ 3902 err = mark_chain_precision(env, value_regno); 3903 if (err) 3904 return err; 3905 type = STACK_ZERO; 3906 } 3907 3908 /* Mark slots affected by this stack write. */ 3909 for (i = 0; i < size; i++) 3910 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 3911 insn_flags = 0; /* not a register spill */ 3912 } 3913 3914 if (insn_flags) 3915 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 0); 3916 return 0; 3917 } 3918 3919 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 3920 * known to contain a variable offset. 3921 * This function checks whether the write is permitted and conservatively 3922 * tracks the effects of the write, considering that each stack slot in the 3923 * dynamic range is potentially written to. 3924 * 3925 * 'value_regno' can be -1, meaning that an unknown value is being written to 3926 * the stack. 3927 * 3928 * Spilled pointers in range are not marked as written because we don't know 3929 * what's going to be actually written. This means that read propagation for 3930 * future reads cannot be terminated by this write. 3931 * 3932 * For privileged programs, uninitialized stack slots are considered 3933 * initialized by this write (even though we don't know exactly what offsets 3934 * are going to be written to). The idea is that we don't want the verifier to 3935 * reject future reads that access slots written to through variable offsets. 3936 */ 3937 static int check_stack_write_var_off(struct bpf_verifier_env *env, 3938 /* func where register points to */ 3939 struct bpf_func_state *state, 3940 int ptr_regno, int off, int size, 3941 int value_regno, int insn_idx) 3942 { 3943 struct bpf_func_state *cur; /* state of the current function */ 3944 int min_off, max_off; 3945 int i, err; 3946 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 3947 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3948 bool writing_zero = false; 3949 /* set if the fact that we're writing a zero is used to let any 3950 * stack slots remain STACK_ZERO 3951 */ 3952 bool zero_used = false; 3953 3954 cur = env->cur_state->frame[env->cur_state->curframe]; 3955 ptr_reg = &cur->regs[ptr_regno]; 3956 min_off = ptr_reg->smin_value + off; 3957 max_off = ptr_reg->smax_value + off + size; 3958 if (value_regno >= 0) 3959 value_reg = &cur->regs[value_regno]; 3960 if ((value_reg && bpf_register_is_null(value_reg)) || 3961 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 3962 writing_zero = true; 3963 3964 for (i = min_off; i < max_off; i++) { 3965 int spi; 3966 3967 spi = bpf_get_spi(i); 3968 err = destroy_if_dynptr_stack_slot(env, state, spi); 3969 if (err) 3970 return err; 3971 } 3972 3973 check_fastcall_stack_contract(env, state, insn_idx, min_off); 3974 /* Variable offset writes destroy any spilled pointers in range. */ 3975 for (i = min_off; i < max_off; i++) { 3976 u8 new_type, *stype; 3977 int slot, spi; 3978 3979 slot = -i - 1; 3980 spi = slot / BPF_REG_SIZE; 3981 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 3982 mark_stack_slot_scratched(env, spi); 3983 3984 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 3985 /* Reject the write if range we may write to has not 3986 * been initialized beforehand. If we didn't reject 3987 * here, the ptr status would be erased below (even 3988 * though not all slots are actually overwritten), 3989 * possibly opening the door to leaks. 3990 * 3991 * We do however catch STACK_INVALID case below, and 3992 * only allow reading possibly uninitialized memory 3993 * later for CAP_PERFMON, as the write may not happen to 3994 * that slot. 3995 */ 3996 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 3997 insn_idx, i); 3998 return -EINVAL; 3999 } 4000 4001 /* If writing_zero and the spi slot contains a spill of value 0, 4002 * maintain the spill type. 4003 */ 4004 if (writing_zero && *stype == STACK_SPILL && 4005 bpf_is_spilled_scalar_reg(&state->stack[spi])) { 4006 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 4007 4008 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 4009 zero_used = true; 4010 continue; 4011 } 4012 } 4013 4014 /* 4015 * Scrub slots if variable-offset stack write goes over spilled pointers. 4016 * Otherwise bpf_is_spilled_reg() may == true && spilled_ptr.type == NOT_INIT 4017 * and valid program is rejected by check_stack_read_fixed_off() 4018 * with obscure "invalid size of register fill" message. 4019 */ 4020 scrub_special_slot(state, spi); 4021 4022 /* Update the slot type. */ 4023 new_type = STACK_MISC; 4024 if (writing_zero && *stype == STACK_ZERO) { 4025 new_type = STACK_ZERO; 4026 zero_used = true; 4027 } 4028 /* If the slot is STACK_INVALID, we check whether it's OK to 4029 * pretend that it will be initialized by this write. The slot 4030 * might not actually be written to, and so if we mark it as 4031 * initialized future reads might leak uninitialized memory. 4032 * For privileged programs, we will accept such reads to slots 4033 * that may or may not be written because, if we're reject 4034 * them, the error would be too confusing. 4035 * Conservatively, treat STACK_POISON in a similar way. 4036 */ 4037 if ((*stype == STACK_INVALID || *stype == STACK_POISON) && 4038 !env->allow_uninit_stack) { 4039 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4040 insn_idx, i); 4041 return -EINVAL; 4042 } 4043 *stype = new_type; 4044 } 4045 if (zero_used) { 4046 /* backtracking doesn't work for STACK_ZERO yet. */ 4047 err = mark_chain_precision(env, value_regno); 4048 if (err) 4049 return err; 4050 } 4051 return 0; 4052 } 4053 4054 /* When register 'dst_regno' is assigned some values from stack[min_off, 4055 * max_off), we set the register's type according to the types of the 4056 * respective stack slots. If all the stack values are known to be zeros, then 4057 * so is the destination reg. Otherwise, the register is considered to be 4058 * SCALAR. This function does not deal with register filling; the caller must 4059 * ensure that all spilled registers in the stack range have been marked as 4060 * read. 4061 */ 4062 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4063 /* func where src register points to */ 4064 struct bpf_func_state *ptr_state, 4065 int min_off, int max_off, int dst_regno) 4066 { 4067 struct bpf_verifier_state *vstate = env->cur_state; 4068 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4069 int i, slot, spi; 4070 u8 *stype; 4071 int zeros = 0; 4072 4073 for (i = min_off; i < max_off; i++) { 4074 slot = -i - 1; 4075 spi = slot / BPF_REG_SIZE; 4076 mark_stack_slot_scratched(env, spi); 4077 stype = ptr_state->stack[spi].slot_type; 4078 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4079 break; 4080 zeros++; 4081 } 4082 if (zeros == max_off - min_off) { 4083 /* Any access_size read into register is zero extended, 4084 * so the whole register == const_zero. 4085 */ 4086 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4087 } else { 4088 /* have read misc data from the stack */ 4089 mark_reg_unknown(env, state->regs, dst_regno); 4090 } 4091 } 4092 4093 /* Read the stack at 'off' and put the results into the register indicated by 4094 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4095 * spilled reg. 4096 * 4097 * 'dst_regno' can be -1, meaning that the read value is not going to a 4098 * register. 4099 * 4100 * The access is assumed to be within the current stack bounds. 4101 */ 4102 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4103 /* func where src register points to */ 4104 struct bpf_func_state *reg_state, 4105 int off, int size, int dst_regno) 4106 { 4107 struct bpf_verifier_state *vstate = env->cur_state; 4108 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4109 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4110 struct bpf_reg_state *reg; 4111 u8 *stype, type; 4112 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4113 4114 stype = reg_state->stack[spi].slot_type; 4115 reg = ®_state->stack[spi].spilled_ptr; 4116 4117 mark_stack_slot_scratched(env, spi); 4118 check_fastcall_stack_contract(env, state, env->insn_idx, off); 4119 4120 if (bpf_is_spilled_reg(®_state->stack[spi])) { 4121 u8 spill_size = 1; 4122 4123 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4124 spill_size++; 4125 4126 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4127 if (reg->type != SCALAR_VALUE) { 4128 verbose_linfo(env, env->insn_idx, "; "); 4129 verbose(env, "invalid size of register fill\n"); 4130 return -EACCES; 4131 } 4132 4133 if (dst_regno < 0) 4134 return 0; 4135 4136 if (size <= spill_size && 4137 bpf_stack_narrow_access_ok(off, size, spill_size)) { 4138 /* The earlier check_reg_arg() has decided the 4139 * subreg_def for this insn. Save it first. 4140 */ 4141 s32 subreg_def = state->regs[dst_regno].subreg_def; 4142 4143 if (env->bpf_capable && size == 4 && spill_size == 4 && 4144 get_reg_width(reg) <= 32) 4145 /* Ensure stack slot has an ID to build a relation 4146 * with the destination register on fill. 4147 */ 4148 assign_scalar_id_before_mov(env, reg); 4149 copy_register_state(&state->regs[dst_regno], reg); 4150 state->regs[dst_regno].subreg_def = subreg_def; 4151 4152 /* Break the relation on a narrowing fill. 4153 * coerce_reg_to_size will adjust the boundaries. 4154 */ 4155 if (get_reg_width(reg) > size * BITS_PER_BYTE) 4156 clear_scalar_id(&state->regs[dst_regno]); 4157 } else { 4158 int spill_cnt = 0, zero_cnt = 0; 4159 4160 for (i = 0; i < size; i++) { 4161 type = stype[(slot - i) % BPF_REG_SIZE]; 4162 if (type == STACK_SPILL) { 4163 spill_cnt++; 4164 continue; 4165 } 4166 if (type == STACK_MISC) 4167 continue; 4168 if (type == STACK_ZERO) { 4169 zero_cnt++; 4170 continue; 4171 } 4172 if (type == STACK_INVALID && env->allow_uninit_stack) 4173 continue; 4174 if (type == STACK_POISON) { 4175 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 4176 off, i, size); 4177 } else { 4178 verbose(env, "invalid read from stack off %d+%d size %d\n", 4179 off, i, size); 4180 } 4181 return -EACCES; 4182 } 4183 4184 if (spill_cnt == size && 4185 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4186 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4187 /* this IS register fill, so keep insn_flags */ 4188 } else if (zero_cnt == size) { 4189 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4190 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4191 insn_flags = 0; /* not restoring original register state */ 4192 } else { 4193 mark_reg_unknown(env, state->regs, dst_regno); 4194 insn_flags = 0; /* not restoring original register state */ 4195 } 4196 } 4197 } else if (dst_regno >= 0) { 4198 /* restore register state from stack */ 4199 if (env->bpf_capable) 4200 /* Ensure stack slot has an ID to build a relation 4201 * with the destination register on fill. 4202 */ 4203 assign_scalar_id_before_mov(env, reg); 4204 copy_register_state(&state->regs[dst_regno], reg); 4205 /* mark reg as written since spilled pointer state likely 4206 * has its liveness marks cleared by is_state_visited() 4207 * which resets stack/reg liveness for state transitions 4208 */ 4209 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4210 /* If dst_regno==-1, the caller is asking us whether 4211 * it is acceptable to use this value as a SCALAR_VALUE 4212 * (e.g. for XADD). 4213 * We must not allow unprivileged callers to do that 4214 * with spilled pointers. 4215 */ 4216 verbose(env, "leaking pointer from stack off %d\n", 4217 off); 4218 return -EACCES; 4219 } 4220 } else { 4221 for (i = 0; i < size; i++) { 4222 type = stype[(slot - i) % BPF_REG_SIZE]; 4223 if (type == STACK_MISC) 4224 continue; 4225 if (type == STACK_ZERO) 4226 continue; 4227 if (type == STACK_INVALID && env->allow_uninit_stack) 4228 continue; 4229 if (type == STACK_POISON) { 4230 verbose(env, "reading from stack off %d+%d size %d, slot poisoned by dead code elimination\n", 4231 off, i, size); 4232 } else { 4233 verbose(env, "invalid read from stack off %d+%d size %d\n", 4234 off, i, size); 4235 } 4236 return -EACCES; 4237 } 4238 if (dst_regno >= 0) 4239 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4240 insn_flags = 0; /* we are not restoring spilled register */ 4241 } 4242 if (insn_flags) 4243 return bpf_push_jmp_history(env, env->cur_state, insn_flags, 0); 4244 return 0; 4245 } 4246 4247 enum bpf_access_src { 4248 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4249 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4250 }; 4251 4252 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4253 int regno, int off, int access_size, 4254 bool zero_size_allowed, 4255 enum bpf_access_type type, 4256 struct bpf_call_arg_meta *meta); 4257 4258 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4259 { 4260 return cur_regs(env) + regno; 4261 } 4262 4263 /* Read the stack at 'ptr_regno + off' and put the result into the register 4264 * 'dst_regno'. 4265 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4266 * but not its variable offset. 4267 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4268 * 4269 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4270 * filling registers (i.e. reads of spilled register cannot be detected when 4271 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4272 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4273 * offset; for a fixed offset check_stack_read_fixed_off should be used 4274 * instead. 4275 */ 4276 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4277 int ptr_regno, int off, int size, int dst_regno) 4278 { 4279 /* The state of the source register. */ 4280 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4281 struct bpf_func_state *ptr_state = bpf_func(env, reg); 4282 int err; 4283 int min_off, max_off; 4284 4285 /* Note that we pass a NULL meta, so raw access will not be permitted. 4286 */ 4287 err = check_stack_range_initialized(env, ptr_regno, off, size, 4288 false, BPF_READ, NULL); 4289 if (err) 4290 return err; 4291 4292 min_off = reg->smin_value + off; 4293 max_off = reg->smax_value + off; 4294 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4295 check_fastcall_stack_contract(env, ptr_state, env->insn_idx, min_off); 4296 return 0; 4297 } 4298 4299 /* check_stack_read dispatches to check_stack_read_fixed_off or 4300 * check_stack_read_var_off. 4301 * 4302 * The caller must ensure that the offset falls within the allocated stack 4303 * bounds. 4304 * 4305 * 'dst_regno' is a register which will receive the value from the stack. It 4306 * can be -1, meaning that the read value is not going to a register. 4307 */ 4308 static int check_stack_read(struct bpf_verifier_env *env, 4309 int ptr_regno, int off, int size, 4310 int dst_regno) 4311 { 4312 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4313 struct bpf_func_state *state = bpf_func(env, reg); 4314 int err; 4315 /* Some accesses are only permitted with a static offset. */ 4316 bool var_off = !tnum_is_const(reg->var_off); 4317 4318 /* The offset is required to be static when reads don't go to a 4319 * register, in order to not leak pointers (see 4320 * check_stack_read_fixed_off). 4321 */ 4322 if (dst_regno < 0 && var_off) { 4323 char tn_buf[48]; 4324 4325 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4326 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4327 tn_buf, off, size); 4328 return -EACCES; 4329 } 4330 /* Variable offset is prohibited for unprivileged mode for simplicity 4331 * since it requires corresponding support in Spectre masking for stack 4332 * ALU. See also retrieve_ptr_limit(). The check in 4333 * check_stack_access_for_ptr_arithmetic() called by 4334 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4335 * with variable offsets, therefore no check is required here. Further, 4336 * just checking it here would be insufficient as speculative stack 4337 * writes could still lead to unsafe speculative behaviour. 4338 */ 4339 if (!var_off) { 4340 off += reg->var_off.value; 4341 err = check_stack_read_fixed_off(env, state, off, size, 4342 dst_regno); 4343 } else { 4344 /* Variable offset stack reads need more conservative handling 4345 * than fixed offset ones. Note that dst_regno >= 0 on this 4346 * branch. 4347 */ 4348 err = check_stack_read_var_off(env, ptr_regno, off, size, 4349 dst_regno); 4350 } 4351 return err; 4352 } 4353 4354 4355 /* check_stack_write dispatches to check_stack_write_fixed_off or 4356 * check_stack_write_var_off. 4357 * 4358 * 'ptr_regno' is the register used as a pointer into the stack. 4359 * 'value_regno' is the register whose value we're writing to the stack. It can 4360 * be -1, meaning that we're not writing from a register. 4361 * 4362 * The caller must ensure that the offset falls within the maximum stack size. 4363 */ 4364 static int check_stack_write(struct bpf_verifier_env *env, 4365 int ptr_regno, int off, int size, 4366 int value_regno, int insn_idx) 4367 { 4368 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4369 struct bpf_func_state *state = bpf_func(env, reg); 4370 int err; 4371 4372 if (tnum_is_const(reg->var_off)) { 4373 off += reg->var_off.value; 4374 err = check_stack_write_fixed_off(env, state, off, size, 4375 value_regno, insn_idx); 4376 } else { 4377 /* Variable offset stack reads need more conservative handling 4378 * than fixed offset ones. 4379 */ 4380 err = check_stack_write_var_off(env, state, 4381 ptr_regno, off, size, 4382 value_regno, insn_idx); 4383 } 4384 return err; 4385 } 4386 4387 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4388 int off, int size, enum bpf_access_type type) 4389 { 4390 struct bpf_reg_state *reg = reg_state(env, regno); 4391 struct bpf_map *map = reg->map_ptr; 4392 u32 cap = bpf_map_flags_to_cap(map); 4393 4394 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4395 verbose(env, "write into map forbidden, value_size=%d off=%lld size=%d\n", 4396 map->value_size, reg->smin_value + off, size); 4397 return -EACCES; 4398 } 4399 4400 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4401 verbose(env, "read from map forbidden, value_size=%d off=%lld size=%d\n", 4402 map->value_size, reg->smin_value + off, size); 4403 return -EACCES; 4404 } 4405 4406 return 0; 4407 } 4408 4409 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4410 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 4411 int off, int size, u32 mem_size, 4412 bool zero_size_allowed) 4413 { 4414 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4415 struct bpf_reg_state *reg; 4416 4417 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4418 return 0; 4419 4420 reg = &cur_regs(env)[regno]; 4421 switch (reg->type) { 4422 case PTR_TO_MAP_KEY: 4423 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4424 mem_size, off, size); 4425 break; 4426 case PTR_TO_MAP_VALUE: 4427 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4428 mem_size, off, size); 4429 break; 4430 case PTR_TO_PACKET: 4431 case PTR_TO_PACKET_META: 4432 case PTR_TO_PACKET_END: 4433 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 4434 off, size, regno, reg->id, off, mem_size); 4435 break; 4436 case PTR_TO_CTX: 4437 verbose(env, "invalid access to context, ctx_size=%d off=%d size=%d\n", 4438 mem_size, off, size); 4439 break; 4440 case PTR_TO_MEM: 4441 default: 4442 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4443 mem_size, off, size); 4444 } 4445 4446 return -EACCES; 4447 } 4448 4449 /* check read/write into a memory region with possible variable offset */ 4450 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 4451 int off, int size, u32 mem_size, 4452 bool zero_size_allowed) 4453 { 4454 struct bpf_verifier_state *vstate = env->cur_state; 4455 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4456 struct bpf_reg_state *reg = &state->regs[regno]; 4457 int err; 4458 4459 /* We may have adjusted the register pointing to memory region, so we 4460 * need to try adding each of min_value and max_value to off 4461 * to make sure our theoretical access will be safe. 4462 * 4463 * The minimum value is only important with signed 4464 * comparisons where we can't assume the floor of a 4465 * value is 0. If we are using signed variables for our 4466 * index'es we need to make sure that whatever we use 4467 * will have a set floor within our range. 4468 */ 4469 if (reg->smin_value < 0 && 4470 (reg->smin_value == S64_MIN || 4471 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 4472 reg->smin_value + off < 0)) { 4473 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4474 regno); 4475 return -EACCES; 4476 } 4477 err = __check_mem_access(env, regno, reg->smin_value + off, size, 4478 mem_size, zero_size_allowed); 4479 if (err) { 4480 verbose(env, "R%d min value is outside of the allowed memory range\n", 4481 regno); 4482 return err; 4483 } 4484 4485 /* If we haven't set a max value then we need to bail since we can't be 4486 * sure we won't do bad things. 4487 * If reg->umax_value + off could overflow, treat that as unbounded too. 4488 */ 4489 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 4490 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 4491 regno); 4492 return -EACCES; 4493 } 4494 err = __check_mem_access(env, regno, reg->umax_value + off, size, 4495 mem_size, zero_size_allowed); 4496 if (err) { 4497 verbose(env, "R%d max value is outside of the allowed memory range\n", 4498 regno); 4499 return err; 4500 } 4501 4502 return 0; 4503 } 4504 4505 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4506 const struct bpf_reg_state *reg, int regno, 4507 bool fixed_off_ok) 4508 { 4509 /* Access to this pointer-typed register or passing it to a helper 4510 * is only allowed in its original, unmodified form. 4511 */ 4512 4513 if (!tnum_is_const(reg->var_off)) { 4514 char tn_buf[48]; 4515 4516 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4517 verbose(env, "variable %s access var_off=%s disallowed\n", 4518 reg_type_str(env, reg->type), tn_buf); 4519 return -EACCES; 4520 } 4521 4522 if (reg->smin_value < 0) { 4523 verbose(env, "negative offset %s ptr R%d off=%lld disallowed\n", 4524 reg_type_str(env, reg->type), regno, reg->var_off.value); 4525 return -EACCES; 4526 } 4527 4528 if (!fixed_off_ok && reg->var_off.value != 0) { 4529 verbose(env, "dereference of modified %s ptr R%d off=%lld disallowed\n", 4530 reg_type_str(env, reg->type), regno, reg->var_off.value); 4531 return -EACCES; 4532 } 4533 4534 return 0; 4535 } 4536 4537 static int check_ptr_off_reg(struct bpf_verifier_env *env, 4538 const struct bpf_reg_state *reg, int regno) 4539 { 4540 return __check_ptr_off_reg(env, reg, regno, false); 4541 } 4542 4543 static int map_kptr_match_type(struct bpf_verifier_env *env, 4544 struct btf_field *kptr_field, 4545 struct bpf_reg_state *reg, u32 regno) 4546 { 4547 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4548 int perm_flags; 4549 const char *reg_name = ""; 4550 4551 if (base_type(reg->type) != PTR_TO_BTF_ID) 4552 goto bad_type; 4553 4554 if (btf_is_kernel(reg->btf)) { 4555 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 4556 4557 /* Only unreferenced case accepts untrusted pointers */ 4558 if (kptr_field->type == BPF_KPTR_UNREF) 4559 perm_flags |= PTR_UNTRUSTED; 4560 } else { 4561 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 4562 if (kptr_field->type == BPF_KPTR_PERCPU) 4563 perm_flags |= MEM_PERCPU; 4564 } 4565 4566 if (type_flag(reg->type) & ~perm_flags) 4567 goto bad_type; 4568 4569 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4570 reg_name = btf_type_name(reg->btf, reg->btf_id); 4571 4572 /* For ref_ptr case, release function check should ensure we get one 4573 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4574 * normal store of unreferenced kptr, we must ensure var_off is zero. 4575 * Since ref_ptr cannot be accessed directly by BPF insns, check for 4576 * reg->ref_obj_id is not needed here. 4577 */ 4578 if (__check_ptr_off_reg(env, reg, regno, true)) 4579 return -EACCES; 4580 4581 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 4582 * we also need to take into account the reg->var_off. 4583 * 4584 * We want to support cases like: 4585 * 4586 * struct foo { 4587 * struct bar br; 4588 * struct baz bz; 4589 * }; 4590 * 4591 * struct foo *v; 4592 * v = func(); // PTR_TO_BTF_ID 4593 * val->foo = v; // reg->var_off is zero, btf and btf_id match type 4594 * val->bar = &v->br; // reg->var_off is still zero, but we need to retry with 4595 * // first member type of struct after comparison fails 4596 * val->baz = &v->bz; // reg->var_off is non-zero, so struct needs to be walked 4597 * // to match type 4598 * 4599 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->var_off 4600 * is zero. We must also ensure that btf_struct_ids_match does not walk 4601 * the struct to match type against first member of struct, i.e. reject 4602 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4603 * strict mode to true for type match. 4604 */ 4605 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->var_off.value, 4606 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4607 kptr_field->type != BPF_KPTR_UNREF)) 4608 goto bad_type; 4609 return 0; 4610 bad_type: 4611 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4612 reg_type_str(env, reg->type), reg_name); 4613 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4614 if (kptr_field->type == BPF_KPTR_UNREF) 4615 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4616 targ_name); 4617 else 4618 verbose(env, "\n"); 4619 return -EINVAL; 4620 } 4621 4622 static bool in_sleepable(struct bpf_verifier_env *env) 4623 { 4624 return env->cur_state->in_sleepable; 4625 } 4626 4627 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 4628 * can dereference RCU protected pointers and result is PTR_TRUSTED. 4629 */ 4630 static bool in_rcu_cs(struct bpf_verifier_env *env) 4631 { 4632 return env->cur_state->active_rcu_locks || 4633 env->cur_state->active_locks || 4634 !in_sleepable(env); 4635 } 4636 4637 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 4638 BTF_SET_START(rcu_protected_types) 4639 #ifdef CONFIG_NET 4640 BTF_ID(struct, prog_test_ref_kfunc) 4641 #endif 4642 #ifdef CONFIG_CGROUPS 4643 BTF_ID(struct, cgroup) 4644 #endif 4645 #ifdef CONFIG_BPF_JIT 4646 BTF_ID(struct, bpf_cpumask) 4647 #endif 4648 BTF_ID(struct, task_struct) 4649 #ifdef CONFIG_CRYPTO 4650 BTF_ID(struct, bpf_crypto_ctx) 4651 #endif 4652 BTF_SET_END(rcu_protected_types) 4653 4654 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 4655 { 4656 if (!btf_is_kernel(btf)) 4657 return true; 4658 return btf_id_set_contains(&rcu_protected_types, btf_id); 4659 } 4660 4661 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 4662 { 4663 struct btf_struct_meta *meta; 4664 4665 if (btf_is_kernel(kptr_field->kptr.btf)) 4666 return NULL; 4667 4668 meta = btf_find_struct_meta(kptr_field->kptr.btf, 4669 kptr_field->kptr.btf_id); 4670 4671 return meta ? meta->record : NULL; 4672 } 4673 4674 static bool rcu_safe_kptr(const struct btf_field *field) 4675 { 4676 const struct btf_field_kptr *kptr = &field->kptr; 4677 4678 return field->type == BPF_KPTR_PERCPU || 4679 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 4680 } 4681 4682 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 4683 { 4684 struct btf_record *rec; 4685 u32 ret; 4686 4687 ret = PTR_MAYBE_NULL; 4688 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 4689 ret |= MEM_RCU; 4690 if (kptr_field->type == BPF_KPTR_PERCPU) 4691 ret |= MEM_PERCPU; 4692 else if (!btf_is_kernel(kptr_field->kptr.btf)) 4693 ret |= MEM_ALLOC; 4694 4695 rec = kptr_pointee_btf_record(kptr_field); 4696 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 4697 ret |= NON_OWN_REF; 4698 } else { 4699 ret |= PTR_UNTRUSTED; 4700 } 4701 4702 return ret; 4703 } 4704 4705 static int mark_uptr_ld_reg(struct bpf_verifier_env *env, u32 regno, 4706 struct btf_field *field) 4707 { 4708 struct bpf_reg_state *reg; 4709 const struct btf_type *t; 4710 4711 t = btf_type_by_id(field->kptr.btf, field->kptr.btf_id); 4712 mark_reg_known_zero(env, cur_regs(env), regno); 4713 reg = reg_state(env, regno); 4714 reg->type = PTR_TO_MEM | PTR_MAYBE_NULL; 4715 reg->mem_size = t->size; 4716 reg->id = ++env->id_gen; 4717 4718 return 0; 4719 } 4720 4721 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 4722 int value_regno, int insn_idx, 4723 struct btf_field *kptr_field) 4724 { 4725 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4726 int class = BPF_CLASS(insn->code); 4727 struct bpf_reg_state *val_reg; 4728 int ret; 4729 4730 /* Things we already checked for in check_map_access and caller: 4731 * - Reject cases where variable offset may touch kptr 4732 * - size of access (must be BPF_DW) 4733 * - tnum_is_const(reg->var_off) 4734 * - kptr_field->offset == off + reg->var_off.value 4735 */ 4736 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4737 if (BPF_MODE(insn->code) != BPF_MEM) { 4738 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4739 return -EACCES; 4740 } 4741 4742 /* We only allow loading referenced kptr, since it will be marked as 4743 * untrusted, similar to unreferenced kptr. 4744 */ 4745 if (class != BPF_LDX && 4746 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 4747 verbose(env, "store to referenced kptr disallowed\n"); 4748 return -EACCES; 4749 } 4750 if (class != BPF_LDX && kptr_field->type == BPF_UPTR) { 4751 verbose(env, "store to uptr disallowed\n"); 4752 return -EACCES; 4753 } 4754 4755 if (class == BPF_LDX) { 4756 if (kptr_field->type == BPF_UPTR) 4757 return mark_uptr_ld_reg(env, value_regno, kptr_field); 4758 4759 /* We can simply mark the value_regno receiving the pointer 4760 * value from map as PTR_TO_BTF_ID, with the correct type. 4761 */ 4762 ret = mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, 4763 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4764 btf_ld_kptr_type(env, kptr_field)); 4765 if (ret < 0) 4766 return ret; 4767 } else if (class == BPF_STX) { 4768 val_reg = reg_state(env, value_regno); 4769 if (!bpf_register_is_null(val_reg) && 4770 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4771 return -EACCES; 4772 } else if (class == BPF_ST) { 4773 if (insn->imm) { 4774 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4775 kptr_field->offset); 4776 return -EACCES; 4777 } 4778 } else { 4779 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4780 return -EACCES; 4781 } 4782 return 0; 4783 } 4784 4785 /* 4786 * Return the size of the memory region accessible from a pointer to map value. 4787 * For INSN_ARRAY maps whole bpf_insn_array->ips array is accessible. 4788 */ 4789 static u32 map_mem_size(const struct bpf_map *map) 4790 { 4791 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) 4792 return map->max_entries * sizeof(long); 4793 4794 return map->value_size; 4795 } 4796 4797 /* check read/write into a map element with possible variable offset */ 4798 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 4799 int off, int size, bool zero_size_allowed, 4800 enum bpf_access_src src) 4801 { 4802 struct bpf_verifier_state *vstate = env->cur_state; 4803 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4804 struct bpf_reg_state *reg = &state->regs[regno]; 4805 struct bpf_map *map = reg->map_ptr; 4806 u32 mem_size = map_mem_size(map); 4807 struct btf_record *rec; 4808 int err, i; 4809 4810 err = check_mem_region_access(env, regno, off, size, mem_size, zero_size_allowed); 4811 if (err) 4812 return err; 4813 4814 if (IS_ERR_OR_NULL(map->record)) 4815 return 0; 4816 rec = map->record; 4817 for (i = 0; i < rec->cnt; i++) { 4818 struct btf_field *field = &rec->fields[i]; 4819 u32 p = field->offset; 4820 4821 /* If any part of a field can be touched by load/store, reject 4822 * this program. To check that [x1, x2) overlaps with [y1, y2), 4823 * it is sufficient to check x1 < y2 && y1 < x2. 4824 */ 4825 if (reg->smin_value + off < p + field->size && 4826 p < reg->umax_value + off + size) { 4827 switch (field->type) { 4828 case BPF_KPTR_UNREF: 4829 case BPF_KPTR_REF: 4830 case BPF_KPTR_PERCPU: 4831 case BPF_UPTR: 4832 if (src != ACCESS_DIRECT) { 4833 verbose(env, "%s cannot be accessed indirectly by helper\n", 4834 btf_field_type_name(field->type)); 4835 return -EACCES; 4836 } 4837 if (!tnum_is_const(reg->var_off)) { 4838 verbose(env, "%s access cannot have variable offset\n", 4839 btf_field_type_name(field->type)); 4840 return -EACCES; 4841 } 4842 if (p != off + reg->var_off.value) { 4843 verbose(env, "%s access misaligned expected=%u off=%llu\n", 4844 btf_field_type_name(field->type), 4845 p, off + reg->var_off.value); 4846 return -EACCES; 4847 } 4848 if (size != bpf_size_to_bytes(BPF_DW)) { 4849 verbose(env, "%s access size must be BPF_DW\n", 4850 btf_field_type_name(field->type)); 4851 return -EACCES; 4852 } 4853 break; 4854 default: 4855 verbose(env, "%s cannot be accessed directly by load/store\n", 4856 btf_field_type_name(field->type)); 4857 return -EACCES; 4858 } 4859 } 4860 } 4861 return 0; 4862 } 4863 4864 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4865 const struct bpf_call_arg_meta *meta, 4866 enum bpf_access_type t) 4867 { 4868 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4869 4870 switch (prog_type) { 4871 /* Program types only with direct read access go here! */ 4872 case BPF_PROG_TYPE_LWT_IN: 4873 case BPF_PROG_TYPE_LWT_OUT: 4874 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4875 case BPF_PROG_TYPE_SK_REUSEPORT: 4876 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4877 case BPF_PROG_TYPE_CGROUP_SKB: 4878 if (t == BPF_WRITE) 4879 return false; 4880 fallthrough; 4881 4882 /* Program types with direct read + write access go here! */ 4883 case BPF_PROG_TYPE_SCHED_CLS: 4884 case BPF_PROG_TYPE_SCHED_ACT: 4885 case BPF_PROG_TYPE_XDP: 4886 case BPF_PROG_TYPE_LWT_XMIT: 4887 case BPF_PROG_TYPE_SK_SKB: 4888 case BPF_PROG_TYPE_SK_MSG: 4889 if (meta) 4890 return meta->pkt_access; 4891 4892 env->seen_direct_write = true; 4893 return true; 4894 4895 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4896 if (t == BPF_WRITE) 4897 env->seen_direct_write = true; 4898 4899 return true; 4900 4901 default: 4902 return false; 4903 } 4904 } 4905 4906 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 4907 int size, bool zero_size_allowed) 4908 { 4909 struct bpf_reg_state *reg = reg_state(env, regno); 4910 int err; 4911 4912 if (reg->range < 0) { 4913 verbose(env, "R%d offset is outside of the packet\n", regno); 4914 return -EINVAL; 4915 } 4916 4917 err = check_mem_region_access(env, regno, off, size, reg->range, zero_size_allowed); 4918 if (err) 4919 return err; 4920 4921 /* __check_mem_access has made sure "off + size - 1" is within u16. 4922 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 4923 * otherwise find_good_pkt_pointers would have refused to set range info 4924 * that __check_mem_access would have rejected this pkt access. 4925 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 4926 */ 4927 env->prog->aux->max_pkt_offset = 4928 max_t(u32, env->prog->aux->max_pkt_offset, 4929 off + reg->umax_value + size - 1); 4930 4931 return 0; 4932 } 4933 4934 static bool is_var_ctx_off_allowed(struct bpf_prog *prog) 4935 { 4936 return resolve_prog_type(prog) == BPF_PROG_TYPE_SYSCALL; 4937 } 4938 4939 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 4940 static int __check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 4941 enum bpf_access_type t, struct bpf_insn_access_aux *info) 4942 { 4943 if (env->ops->is_valid_access && 4944 env->ops->is_valid_access(off, size, t, env->prog, info)) { 4945 /* A non zero info.ctx_field_size indicates that this field is a 4946 * candidate for later verifier transformation to load the whole 4947 * field and then apply a mask when accessed with a narrower 4948 * access than actual ctx access size. A zero info.ctx_field_size 4949 * will only allow for whole field access and rejects any other 4950 * type of narrower access. 4951 */ 4952 if (base_type(info->reg_type) == PTR_TO_BTF_ID) { 4953 if (info->ref_obj_id && 4954 !find_reference_state(env->cur_state, info->ref_obj_id)) { 4955 verbose(env, "invalid bpf_context access off=%d. Reference may already be released\n", 4956 off); 4957 return -EACCES; 4958 } 4959 } else { 4960 env->insn_aux_data[insn_idx].ctx_field_size = info->ctx_field_size; 4961 } 4962 /* remember the offset of last byte accessed in ctx */ 4963 if (env->prog->aux->max_ctx_offset < off + size) 4964 env->prog->aux->max_ctx_offset = off + size; 4965 return 0; 4966 } 4967 4968 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 4969 return -EACCES; 4970 } 4971 4972 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 4973 int off, int access_size, enum bpf_access_type t, 4974 struct bpf_insn_access_aux *info) 4975 { 4976 /* 4977 * Program types that don't rewrite ctx accesses can safely 4978 * dereference ctx pointers with fixed offsets. 4979 */ 4980 bool var_off_ok = is_var_ctx_off_allowed(env->prog); 4981 bool fixed_off_ok = !env->ops->convert_ctx_access; 4982 struct bpf_reg_state *regs = cur_regs(env); 4983 struct bpf_reg_state *reg = regs + regno; 4984 int err; 4985 4986 if (var_off_ok) 4987 err = check_mem_region_access(env, regno, off, access_size, U16_MAX, false); 4988 else 4989 err = __check_ptr_off_reg(env, reg, regno, fixed_off_ok); 4990 if (err) 4991 return err; 4992 off += reg->umax_value; 4993 4994 err = __check_ctx_access(env, insn_idx, off, access_size, t, info); 4995 if (err) 4996 verbose_linfo(env, insn_idx, "; "); 4997 return err; 4998 } 4999 5000 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5001 int size) 5002 { 5003 if (size < 0 || off < 0 || 5004 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5005 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5006 off, size); 5007 return -EACCES; 5008 } 5009 return 0; 5010 } 5011 5012 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5013 u32 regno, int off, int size, 5014 enum bpf_access_type t) 5015 { 5016 struct bpf_reg_state *reg = reg_state(env, regno); 5017 struct bpf_insn_access_aux info = {}; 5018 bool valid; 5019 5020 if (reg->smin_value < 0) { 5021 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5022 regno); 5023 return -EACCES; 5024 } 5025 5026 switch (reg->type) { 5027 case PTR_TO_SOCK_COMMON: 5028 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5029 break; 5030 case PTR_TO_SOCKET: 5031 valid = bpf_sock_is_valid_access(off, size, t, &info); 5032 break; 5033 case PTR_TO_TCP_SOCK: 5034 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5035 break; 5036 case PTR_TO_XDP_SOCK: 5037 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5038 break; 5039 default: 5040 valid = false; 5041 } 5042 5043 5044 if (valid) { 5045 env->insn_aux_data[insn_idx].ctx_field_size = 5046 info.ctx_field_size; 5047 return 0; 5048 } 5049 5050 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5051 regno, reg_type_str(env, reg->type), off, size); 5052 5053 return -EACCES; 5054 } 5055 5056 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5057 { 5058 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5059 } 5060 5061 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5062 { 5063 const struct bpf_reg_state *reg = reg_state(env, regno); 5064 5065 return reg->type == PTR_TO_CTX; 5066 } 5067 5068 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5069 { 5070 const struct bpf_reg_state *reg = reg_state(env, regno); 5071 5072 return type_is_sk_pointer(reg->type); 5073 } 5074 5075 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5076 { 5077 const struct bpf_reg_state *reg = reg_state(env, regno); 5078 5079 return type_is_pkt_pointer(reg->type); 5080 } 5081 5082 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5083 { 5084 const struct bpf_reg_state *reg = reg_state(env, regno); 5085 5086 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5087 return reg->type == PTR_TO_FLOW_KEYS; 5088 } 5089 5090 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 5091 { 5092 const struct bpf_reg_state *reg = reg_state(env, regno); 5093 5094 return reg->type == PTR_TO_ARENA; 5095 } 5096 5097 /* Return false if @regno contains a pointer whose type isn't supported for 5098 * atomic instruction @insn. 5099 */ 5100 static bool atomic_ptr_type_ok(struct bpf_verifier_env *env, int regno, 5101 struct bpf_insn *insn) 5102 { 5103 if (is_ctx_reg(env, regno)) 5104 return false; 5105 if (is_pkt_reg(env, regno)) 5106 return false; 5107 if (is_flow_key_reg(env, regno)) 5108 return false; 5109 if (is_sk_reg(env, regno)) 5110 return false; 5111 if (is_arena_reg(env, regno)) 5112 return bpf_jit_supports_insn(insn, true); 5113 5114 return true; 5115 } 5116 5117 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5118 #ifdef CONFIG_NET 5119 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5120 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5121 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5122 #endif 5123 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5124 }; 5125 5126 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5127 { 5128 /* A referenced register is always trusted. */ 5129 if (reg->ref_obj_id) 5130 return true; 5131 5132 /* Types listed in the reg2btf_ids are always trusted */ 5133 if (reg2btf_ids[base_type(reg->type)] && 5134 !bpf_type_has_unsafe_modifiers(reg->type)) 5135 return true; 5136 5137 /* If a register is not referenced, it is trusted if it has the 5138 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5139 * other type modifiers may be safe, but we elect to take an opt-in 5140 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5141 * not. 5142 * 5143 * Eventually, we should make PTR_TRUSTED the single source of truth 5144 * for whether a register is trusted. 5145 */ 5146 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5147 !bpf_type_has_unsafe_modifiers(reg->type); 5148 } 5149 5150 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5151 { 5152 return reg->type & MEM_RCU; 5153 } 5154 5155 static void clear_trusted_flags(enum bpf_type_flag *flag) 5156 { 5157 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5158 } 5159 5160 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5161 const struct bpf_reg_state *reg, 5162 int off, int size, bool strict) 5163 { 5164 struct tnum reg_off; 5165 int ip_align; 5166 5167 /* Byte size accesses are always allowed. */ 5168 if (!strict || size == 1) 5169 return 0; 5170 5171 /* For platforms that do not have a Kconfig enabling 5172 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5173 * NET_IP_ALIGN is universally set to '2'. And on platforms 5174 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5175 * to this code only in strict mode where we want to emulate 5176 * the NET_IP_ALIGN==2 checking. Therefore use an 5177 * unconditional IP align value of '2'. 5178 */ 5179 ip_align = 2; 5180 5181 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + off)); 5182 if (!tnum_is_aligned(reg_off, size)) { 5183 char tn_buf[48]; 5184 5185 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5186 verbose(env, 5187 "misaligned packet access off %d+%s+%d size %d\n", 5188 ip_align, tn_buf, off, size); 5189 return -EACCES; 5190 } 5191 5192 return 0; 5193 } 5194 5195 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5196 const struct bpf_reg_state *reg, 5197 const char *pointer_desc, 5198 int off, int size, bool strict) 5199 { 5200 struct tnum reg_off; 5201 5202 /* Byte size accesses are always allowed. */ 5203 if (!strict || size == 1) 5204 return 0; 5205 5206 reg_off = tnum_add(reg->var_off, tnum_const(off)); 5207 if (!tnum_is_aligned(reg_off, size)) { 5208 char tn_buf[48]; 5209 5210 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5211 verbose(env, "misaligned %saccess off %s+%d size %d\n", 5212 pointer_desc, tn_buf, off, size); 5213 return -EACCES; 5214 } 5215 5216 return 0; 5217 } 5218 5219 static int check_ptr_alignment(struct bpf_verifier_env *env, 5220 const struct bpf_reg_state *reg, int off, 5221 int size, bool strict_alignment_once) 5222 { 5223 bool strict = env->strict_alignment || strict_alignment_once; 5224 const char *pointer_desc = ""; 5225 5226 switch (reg->type) { 5227 case PTR_TO_PACKET: 5228 case PTR_TO_PACKET_META: 5229 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5230 * right in front, treat it the very same way. 5231 */ 5232 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5233 case PTR_TO_FLOW_KEYS: 5234 pointer_desc = "flow keys "; 5235 break; 5236 case PTR_TO_MAP_KEY: 5237 pointer_desc = "key "; 5238 break; 5239 case PTR_TO_MAP_VALUE: 5240 pointer_desc = "value "; 5241 if (reg->map_ptr->map_type == BPF_MAP_TYPE_INSN_ARRAY) 5242 strict = true; 5243 break; 5244 case PTR_TO_CTX: 5245 pointer_desc = "context "; 5246 break; 5247 case PTR_TO_STACK: 5248 pointer_desc = "stack "; 5249 /* The stack spill tracking logic in check_stack_write_fixed_off() 5250 * and check_stack_read_fixed_off() relies on stack accesses being 5251 * aligned. 5252 */ 5253 strict = true; 5254 break; 5255 case PTR_TO_SOCKET: 5256 pointer_desc = "sock "; 5257 break; 5258 case PTR_TO_SOCK_COMMON: 5259 pointer_desc = "sock_common "; 5260 break; 5261 case PTR_TO_TCP_SOCK: 5262 pointer_desc = "tcp_sock "; 5263 break; 5264 case PTR_TO_XDP_SOCK: 5265 pointer_desc = "xdp_sock "; 5266 break; 5267 case PTR_TO_ARENA: 5268 return 0; 5269 default: 5270 break; 5271 } 5272 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5273 strict); 5274 } 5275 5276 static enum priv_stack_mode bpf_enable_priv_stack(struct bpf_prog *prog) 5277 { 5278 if (!bpf_jit_supports_private_stack()) 5279 return NO_PRIV_STACK; 5280 5281 /* bpf_prog_check_recur() checks all prog types that use bpf trampoline 5282 * while kprobe/tp/perf_event/raw_tp don't use trampoline hence checked 5283 * explicitly. 5284 */ 5285 switch (prog->type) { 5286 case BPF_PROG_TYPE_KPROBE: 5287 case BPF_PROG_TYPE_TRACEPOINT: 5288 case BPF_PROG_TYPE_PERF_EVENT: 5289 case BPF_PROG_TYPE_RAW_TRACEPOINT: 5290 return PRIV_STACK_ADAPTIVE; 5291 case BPF_PROG_TYPE_TRACING: 5292 case BPF_PROG_TYPE_LSM: 5293 case BPF_PROG_TYPE_STRUCT_OPS: 5294 if (prog->aux->priv_stack_requested || bpf_prog_check_recur(prog)) 5295 return PRIV_STACK_ADAPTIVE; 5296 fallthrough; 5297 default: 5298 break; 5299 } 5300 5301 return NO_PRIV_STACK; 5302 } 5303 5304 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5305 { 5306 if (env->prog->jit_requested) 5307 return round_up(stack_depth, 16); 5308 5309 /* round up to 32-bytes, since this is granularity 5310 * of interpreter stack size 5311 */ 5312 return round_up(max_t(u32, stack_depth, 1), 32); 5313 } 5314 5315 /* temporary state used for call frame depth calculation */ 5316 struct bpf_subprog_call_depth_info { 5317 int ret_insn; /* caller instruction where we return to. */ 5318 int caller; /* caller subprogram idx */ 5319 int frame; /* # of consecutive static call stack frames on top of stack */ 5320 }; 5321 5322 /* starting from main bpf function walk all instructions of the function 5323 * and recursively walk all callees that given function can call. 5324 * Ignore jump and exit insns. 5325 */ 5326 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx, 5327 struct bpf_subprog_call_depth_info *dinfo, 5328 bool priv_stack_supported) 5329 { 5330 struct bpf_subprog_info *subprog = env->subprog_info; 5331 struct bpf_insn *insn = env->prog->insnsi; 5332 int depth = 0, frame = 0, i, subprog_end, subprog_depth; 5333 bool tail_call_reachable = false; 5334 int total; 5335 int tmp; 5336 5337 /* no caller idx */ 5338 dinfo[idx].caller = -1; 5339 5340 i = subprog[idx].start; 5341 if (!priv_stack_supported) 5342 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5343 process_func: 5344 /* protect against potential stack overflow that might happen when 5345 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5346 * depth for such case down to 256 so that the worst case scenario 5347 * would result in 8k stack size (32 which is tailcall limit * 256 = 5348 * 8k). 5349 * 5350 * To get the idea what might happen, see an example: 5351 * func1 -> sub rsp, 128 5352 * subfunc1 -> sub rsp, 256 5353 * tailcall1 -> add rsp, 256 5354 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5355 * subfunc2 -> sub rsp, 64 5356 * subfunc22 -> sub rsp, 128 5357 * tailcall2 -> add rsp, 128 5358 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5359 * 5360 * tailcall will unwind the current stack frame but it will not get rid 5361 * of caller's stack as shown on the example above. 5362 */ 5363 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5364 verbose(env, 5365 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5366 depth); 5367 return -EACCES; 5368 } 5369 5370 subprog_depth = round_up_stack_depth(env, subprog[idx].stack_depth); 5371 if (priv_stack_supported) { 5372 /* Request private stack support only if the subprog stack 5373 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to 5374 * avoid jit penalty if the stack usage is small. 5375 */ 5376 if (subprog[idx].priv_stack_mode == PRIV_STACK_UNKNOWN && 5377 subprog_depth >= BPF_PRIV_STACK_MIN_SIZE) 5378 subprog[idx].priv_stack_mode = PRIV_STACK_ADAPTIVE; 5379 } 5380 5381 if (subprog[idx].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5382 if (subprog_depth > MAX_BPF_STACK) { 5383 verbose(env, "stack size of subprog %d is %d. Too large\n", 5384 idx, subprog_depth); 5385 return -EACCES; 5386 } 5387 } else { 5388 depth += subprog_depth; 5389 if (depth > MAX_BPF_STACK) { 5390 total = 0; 5391 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) 5392 total++; 5393 5394 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5395 total, depth); 5396 return -EACCES; 5397 } 5398 } 5399 continue_func: 5400 subprog_end = subprog[idx + 1].start; 5401 for (; i < subprog_end; i++) { 5402 int next_insn, sidx; 5403 5404 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5405 bool err = false; 5406 5407 if (!bpf_is_throw_kfunc(insn + i)) 5408 continue; 5409 for (tmp = idx; tmp >= 0 && !err; tmp = dinfo[tmp].caller) { 5410 if (subprog[tmp].is_cb) { 5411 err = true; 5412 break; 5413 } 5414 } 5415 if (!err) 5416 continue; 5417 verbose(env, 5418 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5419 i, idx); 5420 return -EINVAL; 5421 } 5422 5423 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5424 continue; 5425 /* remember insn and function to return to */ 5426 5427 /* find the callee */ 5428 next_insn = i + insn[i].imm + 1; 5429 sidx = bpf_find_subprog(env, next_insn); 5430 if (verifier_bug_if(sidx < 0, env, "callee not found at insn %d", next_insn)) 5431 return -EFAULT; 5432 if (subprog[sidx].is_async_cb) { 5433 if (subprog[sidx].has_tail_call) { 5434 verifier_bug(env, "subprog has tail_call and async cb"); 5435 return -EFAULT; 5436 } 5437 /* async callbacks don't increase bpf prog stack size unless called directly */ 5438 if (!bpf_pseudo_call(insn + i)) 5439 continue; 5440 if (subprog[sidx].is_exception_cb) { 5441 verbose(env, "insn %d cannot call exception cb directly", i); 5442 return -EINVAL; 5443 } 5444 } 5445 5446 /* store caller info for after we return from callee */ 5447 dinfo[idx].frame = frame; 5448 dinfo[idx].ret_insn = i + 1; 5449 5450 /* push caller idx into callee's dinfo */ 5451 dinfo[sidx].caller = idx; 5452 5453 i = next_insn; 5454 5455 idx = sidx; 5456 if (!priv_stack_supported) 5457 subprog[idx].priv_stack_mode = NO_PRIV_STACK; 5458 5459 if (subprog[idx].has_tail_call) 5460 tail_call_reachable = true; 5461 5462 frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1; 5463 if (frame >= MAX_CALL_FRAMES) { 5464 verbose(env, "the call stack of %d frames is too deep !\n", 5465 frame); 5466 return -E2BIG; 5467 } 5468 goto process_func; 5469 } 5470 /* if tail call got detected across bpf2bpf calls then mark each of the 5471 * currently present subprog frames as tail call reachable subprogs; 5472 * this info will be utilized by JIT so that we will be preserving the 5473 * tail call counter throughout bpf2bpf calls combined with tailcalls 5474 */ 5475 if (tail_call_reachable) 5476 for (tmp = idx; tmp >= 0; tmp = dinfo[tmp].caller) { 5477 if (subprog[tmp].is_exception_cb) { 5478 verbose(env, "cannot tail call within exception cb\n"); 5479 return -EINVAL; 5480 } 5481 subprog[tmp].tail_call_reachable = true; 5482 } 5483 if (subprog[0].tail_call_reachable) 5484 env->prog->aux->tail_call_reachable = true; 5485 5486 /* end of for() loop means the last insn of the 'subprog' 5487 * was reached. Doesn't matter whether it was JA or EXIT 5488 */ 5489 if (frame == 0 && dinfo[idx].caller < 0) 5490 return 0; 5491 if (subprog[idx].priv_stack_mode != PRIV_STACK_ADAPTIVE) 5492 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 5493 5494 /* pop caller idx from callee */ 5495 idx = dinfo[idx].caller; 5496 5497 /* retrieve caller state from its frame */ 5498 frame = dinfo[idx].frame; 5499 i = dinfo[idx].ret_insn; 5500 5501 goto continue_func; 5502 } 5503 5504 static int check_max_stack_depth(struct bpf_verifier_env *env) 5505 { 5506 enum priv_stack_mode priv_stack_mode = PRIV_STACK_UNKNOWN; 5507 struct bpf_subprog_call_depth_info *dinfo; 5508 struct bpf_subprog_info *si = env->subprog_info; 5509 bool priv_stack_supported; 5510 int ret; 5511 5512 dinfo = kvcalloc(env->subprog_cnt, sizeof(*dinfo), GFP_KERNEL_ACCOUNT); 5513 if (!dinfo) 5514 return -ENOMEM; 5515 5516 for (int i = 0; i < env->subprog_cnt; i++) { 5517 if (si[i].has_tail_call) { 5518 priv_stack_mode = NO_PRIV_STACK; 5519 break; 5520 } 5521 } 5522 5523 if (priv_stack_mode == PRIV_STACK_UNKNOWN) 5524 priv_stack_mode = bpf_enable_priv_stack(env->prog); 5525 5526 /* All async_cb subprogs use normal kernel stack. If a particular 5527 * subprog appears in both main prog and async_cb subtree, that 5528 * subprog will use normal kernel stack to avoid potential nesting. 5529 * The reverse subprog traversal ensures when main prog subtree is 5530 * checked, the subprogs appearing in async_cb subtrees are already 5531 * marked as using normal kernel stack, so stack size checking can 5532 * be done properly. 5533 */ 5534 for (int i = env->subprog_cnt - 1; i >= 0; i--) { 5535 if (!i || si[i].is_async_cb) { 5536 priv_stack_supported = !i && priv_stack_mode == PRIV_STACK_ADAPTIVE; 5537 ret = check_max_stack_depth_subprog(env, i, dinfo, 5538 priv_stack_supported); 5539 if (ret < 0) { 5540 kvfree(dinfo); 5541 return ret; 5542 } 5543 } 5544 } 5545 5546 for (int i = 0; i < env->subprog_cnt; i++) { 5547 if (si[i].priv_stack_mode == PRIV_STACK_ADAPTIVE) { 5548 env->prog->aux->jits_use_priv_stack = true; 5549 break; 5550 } 5551 } 5552 5553 kvfree(dinfo); 5554 5555 return 0; 5556 } 5557 5558 static int __check_buffer_access(struct bpf_verifier_env *env, 5559 const char *buf_info, 5560 const struct bpf_reg_state *reg, 5561 int regno, int off, int size) 5562 { 5563 if (off < 0) { 5564 verbose(env, 5565 "R%d invalid %s buffer access: off=%d, size=%d\n", 5566 regno, buf_info, off, size); 5567 return -EACCES; 5568 } 5569 if (!tnum_is_const(reg->var_off)) { 5570 char tn_buf[48]; 5571 5572 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5573 verbose(env, 5574 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5575 regno, off, tn_buf); 5576 return -EACCES; 5577 } 5578 5579 return 0; 5580 } 5581 5582 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5583 const struct bpf_reg_state *reg, 5584 int regno, int off, int size) 5585 { 5586 int err; 5587 5588 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5589 if (err) 5590 return err; 5591 5592 env->prog->aux->max_tp_access = max(reg->var_off.value + off + size, 5593 env->prog->aux->max_tp_access); 5594 5595 return 0; 5596 } 5597 5598 static int check_buffer_access(struct bpf_verifier_env *env, 5599 const struct bpf_reg_state *reg, 5600 int regno, int off, int size, 5601 bool zero_size_allowed, 5602 u32 *max_access) 5603 { 5604 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5605 int err; 5606 5607 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 5608 if (err) 5609 return err; 5610 5611 *max_access = max(reg->var_off.value + off + size, *max_access); 5612 5613 return 0; 5614 } 5615 5616 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5617 static void zext_32_to_64(struct bpf_reg_state *reg) 5618 { 5619 reg->var_off = tnum_subreg(reg->var_off); 5620 __reg_assign_32_into_64(reg); 5621 } 5622 5623 /* truncate register to smaller size (in bytes) 5624 * must be called with size < BPF_REG_SIZE 5625 */ 5626 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5627 { 5628 u64 mask; 5629 5630 /* clear high bits in bit representation */ 5631 reg->var_off = tnum_cast(reg->var_off, size); 5632 5633 /* fix arithmetic bounds */ 5634 mask = ((u64)1 << (size * 8)) - 1; 5635 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 5636 reg->umin_value &= mask; 5637 reg->umax_value &= mask; 5638 } else { 5639 reg->umin_value = 0; 5640 reg->umax_value = mask; 5641 } 5642 reg->smin_value = reg->umin_value; 5643 reg->smax_value = reg->umax_value; 5644 5645 /* If size is smaller than 32bit register the 32bit register 5646 * values are also truncated so we push 64-bit bounds into 5647 * 32-bit bounds. Above were truncated < 32-bits already. 5648 */ 5649 if (size < 4) 5650 __mark_reg32_unbounded(reg); 5651 5652 reg_bounds_sync(reg); 5653 } 5654 5655 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 5656 { 5657 if (size == 1) { 5658 reg->smin_value = reg->s32_min_value = S8_MIN; 5659 reg->smax_value = reg->s32_max_value = S8_MAX; 5660 } else if (size == 2) { 5661 reg->smin_value = reg->s32_min_value = S16_MIN; 5662 reg->smax_value = reg->s32_max_value = S16_MAX; 5663 } else { 5664 /* size == 4 */ 5665 reg->smin_value = reg->s32_min_value = S32_MIN; 5666 reg->smax_value = reg->s32_max_value = S32_MAX; 5667 } 5668 reg->umin_value = reg->u32_min_value = 0; 5669 reg->umax_value = U64_MAX; 5670 reg->u32_max_value = U32_MAX; 5671 reg->var_off = tnum_unknown; 5672 } 5673 5674 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 5675 { 5676 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 5677 u64 top_smax_value, top_smin_value; 5678 u64 num_bits = size * 8; 5679 5680 if (tnum_is_const(reg->var_off)) { 5681 u64_cval = reg->var_off.value; 5682 if (size == 1) 5683 reg->var_off = tnum_const((s8)u64_cval); 5684 else if (size == 2) 5685 reg->var_off = tnum_const((s16)u64_cval); 5686 else 5687 /* size == 4 */ 5688 reg->var_off = tnum_const((s32)u64_cval); 5689 5690 u64_cval = reg->var_off.value; 5691 reg->smax_value = reg->smin_value = u64_cval; 5692 reg->umax_value = reg->umin_value = u64_cval; 5693 reg->s32_max_value = reg->s32_min_value = u64_cval; 5694 reg->u32_max_value = reg->u32_min_value = u64_cval; 5695 return; 5696 } 5697 5698 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 5699 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 5700 5701 if (top_smax_value != top_smin_value) 5702 goto out; 5703 5704 /* find the s64_min and s64_min after sign extension */ 5705 if (size == 1) { 5706 init_s64_max = (s8)reg->smax_value; 5707 init_s64_min = (s8)reg->smin_value; 5708 } else if (size == 2) { 5709 init_s64_max = (s16)reg->smax_value; 5710 init_s64_min = (s16)reg->smin_value; 5711 } else { 5712 init_s64_max = (s32)reg->smax_value; 5713 init_s64_min = (s32)reg->smin_value; 5714 } 5715 5716 s64_max = max(init_s64_max, init_s64_min); 5717 s64_min = min(init_s64_max, init_s64_min); 5718 5719 /* both of s64_max/s64_min positive or negative */ 5720 if ((s64_max >= 0) == (s64_min >= 0)) { 5721 reg->s32_min_value = reg->smin_value = s64_min; 5722 reg->s32_max_value = reg->smax_value = s64_max; 5723 reg->u32_min_value = reg->umin_value = s64_min; 5724 reg->u32_max_value = reg->umax_value = s64_max; 5725 reg->var_off = tnum_range(s64_min, s64_max); 5726 return; 5727 } 5728 5729 out: 5730 set_sext64_default_val(reg, size); 5731 } 5732 5733 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 5734 { 5735 if (size == 1) { 5736 reg->s32_min_value = S8_MIN; 5737 reg->s32_max_value = S8_MAX; 5738 } else { 5739 /* size == 2 */ 5740 reg->s32_min_value = S16_MIN; 5741 reg->s32_max_value = S16_MAX; 5742 } 5743 reg->u32_min_value = 0; 5744 reg->u32_max_value = U32_MAX; 5745 reg->var_off = tnum_subreg(tnum_unknown); 5746 } 5747 5748 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 5749 { 5750 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 5751 u32 top_smax_value, top_smin_value; 5752 u32 num_bits = size * 8; 5753 5754 if (tnum_is_const(reg->var_off)) { 5755 u32_val = reg->var_off.value; 5756 if (size == 1) 5757 reg->var_off = tnum_const((s8)u32_val); 5758 else 5759 reg->var_off = tnum_const((s16)u32_val); 5760 5761 u32_val = reg->var_off.value; 5762 reg->s32_min_value = reg->s32_max_value = u32_val; 5763 reg->u32_min_value = reg->u32_max_value = u32_val; 5764 return; 5765 } 5766 5767 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 5768 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 5769 5770 if (top_smax_value != top_smin_value) 5771 goto out; 5772 5773 /* find the s32_min and s32_min after sign extension */ 5774 if (size == 1) { 5775 init_s32_max = (s8)reg->s32_max_value; 5776 init_s32_min = (s8)reg->s32_min_value; 5777 } else { 5778 /* size == 2 */ 5779 init_s32_max = (s16)reg->s32_max_value; 5780 init_s32_min = (s16)reg->s32_min_value; 5781 } 5782 s32_max = max(init_s32_max, init_s32_min); 5783 s32_min = min(init_s32_max, init_s32_min); 5784 5785 if ((s32_min >= 0) == (s32_max >= 0)) { 5786 reg->s32_min_value = s32_min; 5787 reg->s32_max_value = s32_max; 5788 reg->u32_min_value = (u32)s32_min; 5789 reg->u32_max_value = (u32)s32_max; 5790 reg->var_off = tnum_subreg(tnum_range(s32_min, s32_max)); 5791 return; 5792 } 5793 5794 out: 5795 set_sext32_default_val(reg, size); 5796 } 5797 5798 bool bpf_map_is_rdonly(const struct bpf_map *map) 5799 { 5800 /* A map is considered read-only if the following condition are true: 5801 * 5802 * 1) BPF program side cannot change any of the map content. The 5803 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 5804 * and was set at map creation time. 5805 * 2) The map value(s) have been initialized from user space by a 5806 * loader and then "frozen", such that no new map update/delete 5807 * operations from syscall side are possible for the rest of 5808 * the map's lifetime from that point onwards. 5809 * 3) Any parallel/pending map update/delete operations from syscall 5810 * side have been completed. Only after that point, it's safe to 5811 * assume that map value(s) are immutable. 5812 */ 5813 return (map->map_flags & BPF_F_RDONLY_PROG) && 5814 READ_ONCE(map->frozen) && 5815 !bpf_map_write_active(map); 5816 } 5817 5818 int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 5819 bool is_ldsx) 5820 { 5821 void *ptr; 5822 u64 addr; 5823 int err; 5824 5825 err = map->ops->map_direct_value_addr(map, &addr, off); 5826 if (err) 5827 return err; 5828 ptr = (void *)(long)addr + off; 5829 5830 switch (size) { 5831 case sizeof(u8): 5832 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 5833 break; 5834 case sizeof(u16): 5835 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 5836 break; 5837 case sizeof(u32): 5838 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 5839 break; 5840 case sizeof(u64): 5841 *val = *(u64 *)ptr; 5842 break; 5843 default: 5844 return -EINVAL; 5845 } 5846 return 0; 5847 } 5848 5849 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 5850 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 5851 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 5852 #define BTF_TYPE_SAFE_TRUSTED_OR_NULL(__type) __PASTE(__type, __safe_trusted_or_null) 5853 5854 /* 5855 * Allow list few fields as RCU trusted or full trusted. 5856 * This logic doesn't allow mix tagging and will be removed once GCC supports 5857 * btf_type_tag. 5858 */ 5859 5860 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 5861 BTF_TYPE_SAFE_RCU(struct task_struct) { 5862 const cpumask_t *cpus_ptr; 5863 struct css_set __rcu *cgroups; 5864 struct task_struct __rcu *real_parent; 5865 struct task_struct *group_leader; 5866 }; 5867 5868 BTF_TYPE_SAFE_RCU(struct cgroup) { 5869 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 5870 struct kernfs_node *kn; 5871 }; 5872 5873 BTF_TYPE_SAFE_RCU(struct css_set) { 5874 struct cgroup *dfl_cgrp; 5875 }; 5876 5877 BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state) { 5878 struct cgroup *cgroup; 5879 }; 5880 5881 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 5882 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 5883 struct file __rcu *exe_file; 5884 #ifdef CONFIG_MEMCG 5885 struct task_struct __rcu *owner; 5886 #endif 5887 }; 5888 5889 /* skb->sk, req->sk are not RCU protected, but we mark them as such 5890 * because bpf prog accessible sockets are SOCK_RCU_FREE. 5891 */ 5892 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 5893 struct sock *sk; 5894 }; 5895 5896 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 5897 struct sock *sk; 5898 }; 5899 5900 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 5901 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 5902 struct seq_file *seq; 5903 }; 5904 5905 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 5906 struct bpf_iter_meta *meta; 5907 struct task_struct *task; 5908 }; 5909 5910 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 5911 struct file *file; 5912 }; 5913 5914 BTF_TYPE_SAFE_TRUSTED(struct file) { 5915 struct inode *f_inode; 5916 }; 5917 5918 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry) { 5919 struct inode *d_inode; 5920 }; 5921 5922 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) { 5923 struct sock *sk; 5924 }; 5925 5926 BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) { 5927 struct mm_struct *vm_mm; 5928 struct file *vm_file; 5929 }; 5930 5931 static bool type_is_rcu(struct bpf_verifier_env *env, 5932 struct bpf_reg_state *reg, 5933 const char *field_name, u32 btf_id) 5934 { 5935 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 5936 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 5937 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 5938 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup_subsys_state)); 5939 5940 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 5941 } 5942 5943 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 5944 struct bpf_reg_state *reg, 5945 const char *field_name, u32 btf_id) 5946 { 5947 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 5948 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 5949 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 5950 5951 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 5952 } 5953 5954 static bool type_is_trusted(struct bpf_verifier_env *env, 5955 struct bpf_reg_state *reg, 5956 const char *field_name, u32 btf_id) 5957 { 5958 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 5959 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 5960 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 5961 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 5962 5963 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 5964 } 5965 5966 static bool type_is_trusted_or_null(struct bpf_verifier_env *env, 5967 struct bpf_reg_state *reg, 5968 const char *field_name, u32 btf_id) 5969 { 5970 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket)); 5971 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry)); 5972 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct)); 5973 5974 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, 5975 "__safe_trusted_or_null"); 5976 } 5977 5978 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 5979 struct bpf_reg_state *regs, 5980 int regno, int off, int size, 5981 enum bpf_access_type atype, 5982 int value_regno) 5983 { 5984 struct bpf_reg_state *reg = regs + regno; 5985 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 5986 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 5987 const char *field_name = NULL; 5988 enum bpf_type_flag flag = 0; 5989 u32 btf_id = 0; 5990 int ret; 5991 5992 if (!env->allow_ptr_leaks) { 5993 verbose(env, 5994 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5995 tname); 5996 return -EPERM; 5997 } 5998 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 5999 verbose(env, 6000 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6001 tname); 6002 return -EINVAL; 6003 } 6004 6005 if (!tnum_is_const(reg->var_off)) { 6006 char tn_buf[48]; 6007 6008 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6009 verbose(env, 6010 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6011 regno, tname, off, tn_buf); 6012 return -EACCES; 6013 } 6014 6015 off += reg->var_off.value; 6016 6017 if (off < 0) { 6018 verbose(env, 6019 "R%d is ptr_%s invalid negative access: off=%d\n", 6020 regno, tname, off); 6021 return -EACCES; 6022 } 6023 6024 if (reg->type & MEM_USER) { 6025 verbose(env, 6026 "R%d is ptr_%s access user memory: off=%d\n", 6027 regno, tname, off); 6028 return -EACCES; 6029 } 6030 6031 if (reg->type & MEM_PERCPU) { 6032 verbose(env, 6033 "R%d is ptr_%s access percpu memory: off=%d\n", 6034 regno, tname, off); 6035 return -EACCES; 6036 } 6037 6038 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6039 if (!btf_is_kernel(reg->btf)) { 6040 verifier_bug(env, "reg->btf must be kernel btf"); 6041 return -EFAULT; 6042 } 6043 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6044 } else { 6045 /* Writes are permitted with default btf_struct_access for 6046 * program allocated objects (which always have ref_obj_id > 0), 6047 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6048 */ 6049 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6050 verbose(env, "only read is supported\n"); 6051 return -EACCES; 6052 } 6053 6054 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6055 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6056 verifier_bug(env, "ref_obj_id for allocated object must be non-zero"); 6057 return -EFAULT; 6058 } 6059 6060 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6061 } 6062 6063 if (ret < 0) 6064 return ret; 6065 6066 if (ret != PTR_TO_BTF_ID) { 6067 /* just mark; */ 6068 6069 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6070 /* If this is an untrusted pointer, all pointers formed by walking it 6071 * also inherit the untrusted flag. 6072 */ 6073 flag = PTR_UNTRUSTED; 6074 6075 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6076 /* By default any pointer obtained from walking a trusted pointer is no 6077 * longer trusted, unless the field being accessed has explicitly been 6078 * marked as inheriting its parent's state of trust (either full or RCU). 6079 * For example: 6080 * 'cgroups' pointer is untrusted if task->cgroups dereference 6081 * happened in a sleepable program outside of bpf_rcu_read_lock() 6082 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6083 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6084 * 6085 * A regular RCU-protected pointer with __rcu tag can also be deemed 6086 * trusted if we are in an RCU CS. Such pointer can be NULL. 6087 */ 6088 if (type_is_trusted(env, reg, field_name, btf_id)) { 6089 flag |= PTR_TRUSTED; 6090 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) { 6091 flag |= PTR_TRUSTED | PTR_MAYBE_NULL; 6092 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6093 if (type_is_rcu(env, reg, field_name, btf_id)) { 6094 /* ignore __rcu tag and mark it MEM_RCU */ 6095 flag |= MEM_RCU; 6096 } else if (flag & MEM_RCU || 6097 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6098 /* __rcu tagged pointers can be NULL */ 6099 flag |= MEM_RCU | PTR_MAYBE_NULL; 6100 6101 /* We always trust them */ 6102 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6103 flag & PTR_UNTRUSTED) 6104 flag &= ~PTR_UNTRUSTED; 6105 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6106 /* keep as-is */ 6107 } else { 6108 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6109 clear_trusted_flags(&flag); 6110 } 6111 } else { 6112 /* 6113 * If not in RCU CS or MEM_RCU pointer can be NULL then 6114 * aggressively mark as untrusted otherwise such 6115 * pointers will be plain PTR_TO_BTF_ID without flags 6116 * and will be allowed to be passed into helpers for 6117 * compat reasons. 6118 */ 6119 flag = PTR_UNTRUSTED; 6120 } 6121 } else { 6122 /* Old compat. Deprecated */ 6123 clear_trusted_flags(&flag); 6124 } 6125 6126 if (atype == BPF_READ && value_regno >= 0) { 6127 ret = mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6128 if (ret < 0) 6129 return ret; 6130 } 6131 6132 return 0; 6133 } 6134 6135 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6136 struct bpf_reg_state *regs, 6137 int regno, int off, int size, 6138 enum bpf_access_type atype, 6139 int value_regno) 6140 { 6141 struct bpf_reg_state *reg = regs + regno; 6142 struct bpf_map *map = reg->map_ptr; 6143 struct bpf_reg_state map_reg; 6144 enum bpf_type_flag flag = 0; 6145 const struct btf_type *t; 6146 const char *tname; 6147 u32 btf_id; 6148 int ret; 6149 6150 if (!btf_vmlinux) { 6151 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6152 return -ENOTSUPP; 6153 } 6154 6155 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6156 verbose(env, "map_ptr access not supported for map type %d\n", 6157 map->map_type); 6158 return -ENOTSUPP; 6159 } 6160 6161 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6162 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6163 6164 if (!env->allow_ptr_leaks) { 6165 verbose(env, 6166 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6167 tname); 6168 return -EPERM; 6169 } 6170 6171 if (off < 0) { 6172 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6173 regno, tname, off); 6174 return -EACCES; 6175 } 6176 6177 if (atype != BPF_READ) { 6178 verbose(env, "only read from %s is supported\n", tname); 6179 return -EACCES; 6180 } 6181 6182 /* Simulate access to a PTR_TO_BTF_ID */ 6183 memset(&map_reg, 0, sizeof(map_reg)); 6184 ret = mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, 6185 btf_vmlinux, *map->ops->map_btf_id, 0); 6186 if (ret < 0) 6187 return ret; 6188 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6189 if (ret < 0) 6190 return ret; 6191 6192 if (value_regno >= 0) { 6193 ret = mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6194 if (ret < 0) 6195 return ret; 6196 } 6197 6198 return 0; 6199 } 6200 6201 /* Check that the stack access at the given offset is within bounds. The 6202 * maximum valid offset is -1. 6203 * 6204 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6205 * -state->allocated_stack for reads. 6206 */ 6207 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6208 s64 off, 6209 struct bpf_func_state *state, 6210 enum bpf_access_type t) 6211 { 6212 int min_valid_off; 6213 6214 if (t == BPF_WRITE || env->allow_uninit_stack) 6215 min_valid_off = -MAX_BPF_STACK; 6216 else 6217 min_valid_off = -state->allocated_stack; 6218 6219 if (off < min_valid_off || off > -1) 6220 return -EACCES; 6221 return 0; 6222 } 6223 6224 /* Check that the stack access at 'regno + off' falls within the maximum stack 6225 * bounds. 6226 * 6227 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6228 */ 6229 static int check_stack_access_within_bounds( 6230 struct bpf_verifier_env *env, 6231 int regno, int off, int access_size, 6232 enum bpf_access_type type) 6233 { 6234 struct bpf_reg_state *reg = reg_state(env, regno); 6235 struct bpf_func_state *state = bpf_func(env, reg); 6236 s64 min_off, max_off; 6237 int err; 6238 char *err_extra; 6239 6240 if (type == BPF_READ) 6241 err_extra = " read from"; 6242 else 6243 err_extra = " write to"; 6244 6245 if (tnum_is_const(reg->var_off)) { 6246 min_off = (s64)reg->var_off.value + off; 6247 max_off = min_off + access_size; 6248 } else { 6249 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6250 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6251 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6252 err_extra, regno); 6253 return -EACCES; 6254 } 6255 min_off = reg->smin_value + off; 6256 max_off = reg->smax_value + off + access_size; 6257 } 6258 6259 err = check_stack_slot_within_bounds(env, min_off, state, type); 6260 if (!err && max_off > 0) 6261 err = -EINVAL; /* out of stack access into non-negative offsets */ 6262 if (!err && access_size < 0) 6263 /* access_size should not be negative (or overflow an int); others checks 6264 * along the way should have prevented such an access. 6265 */ 6266 err = -EFAULT; /* invalid negative access size; integer overflow? */ 6267 6268 if (err) { 6269 if (tnum_is_const(reg->var_off)) { 6270 verbose(env, "invalid%s stack R%d off=%lld size=%d\n", 6271 err_extra, regno, min_off, access_size); 6272 } else { 6273 char tn_buf[48]; 6274 6275 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6276 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6277 err_extra, regno, tn_buf, off, access_size); 6278 } 6279 return err; 6280 } 6281 6282 /* Note that there is no stack access with offset zero, so the needed stack 6283 * size is -min_off, not -min_off+1. 6284 */ 6285 return grow_stack_state(env, state, -min_off /* size */); 6286 } 6287 6288 static bool get_func_retval_range(struct bpf_prog *prog, 6289 struct bpf_retval_range *range) 6290 { 6291 if (prog->type == BPF_PROG_TYPE_LSM && 6292 prog->expected_attach_type == BPF_LSM_MAC && 6293 !bpf_lsm_get_retval_range(prog, range)) { 6294 return true; 6295 } 6296 return false; 6297 } 6298 6299 static void add_scalar_to_reg(struct bpf_reg_state *dst_reg, s64 val) 6300 { 6301 struct bpf_reg_state fake_reg; 6302 6303 if (!val) 6304 return; 6305 6306 fake_reg.type = SCALAR_VALUE; 6307 __mark_reg_known(&fake_reg, val); 6308 6309 scalar32_min_max_add(dst_reg, &fake_reg); 6310 scalar_min_max_add(dst_reg, &fake_reg); 6311 dst_reg->var_off = tnum_add(dst_reg->var_off, fake_reg.var_off); 6312 6313 reg_bounds_sync(dst_reg); 6314 } 6315 6316 /* check whether memory at (regno + off) is accessible for t = (read | write) 6317 * if t==write, value_regno is a register which value is stored into memory 6318 * if t==read, value_regno is a register which will receive the value from memory 6319 * if t==write && value_regno==-1, some unknown value is stored into memory 6320 * if t==read && value_regno==-1, don't care what we read from memory 6321 */ 6322 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6323 int off, int bpf_size, enum bpf_access_type t, 6324 int value_regno, bool strict_alignment_once, bool is_ldsx) 6325 { 6326 struct bpf_reg_state *regs = cur_regs(env); 6327 struct bpf_reg_state *reg = regs + regno; 6328 int size, err = 0; 6329 6330 size = bpf_size_to_bytes(bpf_size); 6331 if (size < 0) 6332 return size; 6333 6334 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6335 if (err) 6336 return err; 6337 6338 if (reg->type == PTR_TO_MAP_KEY) { 6339 if (t == BPF_WRITE) { 6340 verbose(env, "write to change key R%d not allowed\n", regno); 6341 return -EACCES; 6342 } 6343 6344 err = check_mem_region_access(env, regno, off, size, 6345 reg->map_ptr->key_size, false); 6346 if (err) 6347 return err; 6348 if (value_regno >= 0) 6349 mark_reg_unknown(env, regs, value_regno); 6350 } else if (reg->type == PTR_TO_MAP_VALUE) { 6351 struct btf_field *kptr_field = NULL; 6352 6353 if (t == BPF_WRITE && value_regno >= 0 && 6354 is_pointer_value(env, value_regno)) { 6355 verbose(env, "R%d leaks addr into map\n", value_regno); 6356 return -EACCES; 6357 } 6358 err = check_map_access_type(env, regno, off, size, t); 6359 if (err) 6360 return err; 6361 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6362 if (err) 6363 return err; 6364 if (tnum_is_const(reg->var_off)) 6365 kptr_field = btf_record_find(reg->map_ptr->record, 6366 off + reg->var_off.value, BPF_KPTR | BPF_UPTR); 6367 if (kptr_field) { 6368 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6369 } else if (t == BPF_READ && value_regno >= 0) { 6370 struct bpf_map *map = reg->map_ptr; 6371 6372 /* 6373 * If map is read-only, track its contents as scalars, 6374 * unless it is an insn array (see the special case below) 6375 */ 6376 if (tnum_is_const(reg->var_off) && 6377 bpf_map_is_rdonly(map) && 6378 map->ops->map_direct_value_addr && 6379 map->map_type != BPF_MAP_TYPE_INSN_ARRAY) { 6380 int map_off = off + reg->var_off.value; 6381 u64 val = 0; 6382 6383 err = bpf_map_direct_read(map, map_off, size, 6384 &val, is_ldsx); 6385 if (err) 6386 return err; 6387 6388 regs[value_regno].type = SCALAR_VALUE; 6389 __mark_reg_known(®s[value_regno], val); 6390 } else if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 6391 if (bpf_size != BPF_DW) { 6392 verbose(env, "Invalid read of %d bytes from insn_array\n", 6393 size); 6394 return -EACCES; 6395 } 6396 copy_register_state(®s[value_regno], reg); 6397 add_scalar_to_reg(®s[value_regno], off); 6398 regs[value_regno].type = PTR_TO_INSN; 6399 } else { 6400 mark_reg_unknown(env, regs, value_regno); 6401 } 6402 } 6403 } else if (base_type(reg->type) == PTR_TO_MEM) { 6404 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6405 bool rdonly_untrusted = rdonly_mem && (reg->type & PTR_UNTRUSTED); 6406 6407 if (type_may_be_null(reg->type)) { 6408 verbose(env, "R%d invalid mem access '%s'\n", regno, 6409 reg_type_str(env, reg->type)); 6410 return -EACCES; 6411 } 6412 6413 if (t == BPF_WRITE && rdonly_mem) { 6414 verbose(env, "R%d cannot write into %s\n", 6415 regno, reg_type_str(env, reg->type)); 6416 return -EACCES; 6417 } 6418 6419 if (t == BPF_WRITE && value_regno >= 0 && 6420 is_pointer_value(env, value_regno)) { 6421 verbose(env, "R%d leaks addr into mem\n", value_regno); 6422 return -EACCES; 6423 } 6424 6425 /* 6426 * Accesses to untrusted PTR_TO_MEM are done through probe 6427 * instructions, hence no need to check bounds in that case. 6428 */ 6429 if (!rdonly_untrusted) 6430 err = check_mem_region_access(env, regno, off, size, 6431 reg->mem_size, false); 6432 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6433 mark_reg_unknown(env, regs, value_regno); 6434 } else if (reg->type == PTR_TO_CTX) { 6435 struct bpf_insn_access_aux info = { 6436 .reg_type = SCALAR_VALUE, 6437 .is_ldsx = is_ldsx, 6438 .log = &env->log, 6439 }; 6440 struct bpf_retval_range range; 6441 6442 if (t == BPF_WRITE && value_regno >= 0 && 6443 is_pointer_value(env, value_regno)) { 6444 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6445 return -EACCES; 6446 } 6447 6448 err = check_ctx_access(env, insn_idx, regno, off, size, t, &info); 6449 if (!err && t == BPF_READ && value_regno >= 0) { 6450 /* ctx access returns either a scalar, or a 6451 * PTR_TO_PACKET[_META,_END]. In the latter 6452 * case, we know the offset is zero. 6453 */ 6454 if (info.reg_type == SCALAR_VALUE) { 6455 if (info.is_retval && get_func_retval_range(env->prog, &range)) { 6456 err = __mark_reg_s32_range(env, regs, value_regno, 6457 range.minval, range.maxval); 6458 if (err) 6459 return err; 6460 } else { 6461 mark_reg_unknown(env, regs, value_regno); 6462 } 6463 } else { 6464 mark_reg_known_zero(env, regs, 6465 value_regno); 6466 if (type_may_be_null(info.reg_type)) 6467 regs[value_regno].id = ++env->id_gen; 6468 /* A load of ctx field could have different 6469 * actual load size with the one encoded in the 6470 * insn. When the dst is PTR, it is for sure not 6471 * a sub-register. 6472 */ 6473 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6474 if (base_type(info.reg_type) == PTR_TO_BTF_ID) { 6475 regs[value_regno].btf = info.btf; 6476 regs[value_regno].btf_id = info.btf_id; 6477 regs[value_regno].ref_obj_id = info.ref_obj_id; 6478 } 6479 } 6480 regs[value_regno].type = info.reg_type; 6481 } 6482 6483 } else if (reg->type == PTR_TO_STACK) { 6484 /* Basic bounds checks. */ 6485 err = check_stack_access_within_bounds(env, regno, off, size, t); 6486 if (err) 6487 return err; 6488 6489 if (t == BPF_READ) 6490 err = check_stack_read(env, regno, off, size, 6491 value_regno); 6492 else 6493 err = check_stack_write(env, regno, off, size, 6494 value_regno, insn_idx); 6495 } else if (reg_is_pkt_pointer(reg)) { 6496 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6497 verbose(env, "cannot write into packet\n"); 6498 return -EACCES; 6499 } 6500 if (t == BPF_WRITE && value_regno >= 0 && 6501 is_pointer_value(env, value_regno)) { 6502 verbose(env, "R%d leaks addr into packet\n", 6503 value_regno); 6504 return -EACCES; 6505 } 6506 err = check_packet_access(env, regno, off, size, false); 6507 if (!err && t == BPF_READ && value_regno >= 0) 6508 mark_reg_unknown(env, regs, value_regno); 6509 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6510 if (t == BPF_WRITE && value_regno >= 0 && 6511 is_pointer_value(env, value_regno)) { 6512 verbose(env, "R%d leaks addr into flow keys\n", 6513 value_regno); 6514 return -EACCES; 6515 } 6516 6517 err = check_flow_keys_access(env, off, size); 6518 if (!err && t == BPF_READ && value_regno >= 0) 6519 mark_reg_unknown(env, regs, value_regno); 6520 } else if (type_is_sk_pointer(reg->type)) { 6521 if (t == BPF_WRITE) { 6522 verbose(env, "R%d cannot write into %s\n", 6523 regno, reg_type_str(env, reg->type)); 6524 return -EACCES; 6525 } 6526 err = check_sock_access(env, insn_idx, regno, off, size, t); 6527 if (!err && value_regno >= 0) 6528 mark_reg_unknown(env, regs, value_regno); 6529 } else if (reg->type == PTR_TO_TP_BUFFER) { 6530 err = check_tp_buffer_access(env, reg, regno, off, size); 6531 if (!err && t == BPF_READ && value_regno >= 0) 6532 mark_reg_unknown(env, regs, value_regno); 6533 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6534 !type_may_be_null(reg->type)) { 6535 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6536 value_regno); 6537 } else if (reg->type == CONST_PTR_TO_MAP) { 6538 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6539 value_regno); 6540 } else if (base_type(reg->type) == PTR_TO_BUF && 6541 !type_may_be_null(reg->type)) { 6542 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6543 u32 *max_access; 6544 6545 if (rdonly_mem) { 6546 if (t == BPF_WRITE) { 6547 verbose(env, "R%d cannot write into %s\n", 6548 regno, reg_type_str(env, reg->type)); 6549 return -EACCES; 6550 } 6551 max_access = &env->prog->aux->max_rdonly_access; 6552 } else { 6553 max_access = &env->prog->aux->max_rdwr_access; 6554 } 6555 6556 err = check_buffer_access(env, reg, regno, off, size, false, 6557 max_access); 6558 6559 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6560 mark_reg_unknown(env, regs, value_regno); 6561 } else if (reg->type == PTR_TO_ARENA) { 6562 if (t == BPF_READ && value_regno >= 0) 6563 mark_reg_unknown(env, regs, value_regno); 6564 } else { 6565 verbose(env, "R%d invalid mem access '%s'\n", regno, 6566 reg_type_str(env, reg->type)); 6567 return -EACCES; 6568 } 6569 6570 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6571 regs[value_regno].type == SCALAR_VALUE) { 6572 if (!is_ldsx) 6573 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6574 coerce_reg_to_size(®s[value_regno], size); 6575 else 6576 coerce_reg_to_size_sx(®s[value_regno], size); 6577 } 6578 return err; 6579 } 6580 6581 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 6582 bool allow_trust_mismatch); 6583 6584 static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn, 6585 bool strict_alignment_once, bool is_ldsx, 6586 bool allow_trust_mismatch, const char *ctx) 6587 { 6588 struct bpf_reg_state *regs = cur_regs(env); 6589 enum bpf_reg_type src_reg_type; 6590 int err; 6591 6592 /* check src operand */ 6593 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6594 if (err) 6595 return err; 6596 6597 /* check dst operand */ 6598 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6599 if (err) 6600 return err; 6601 6602 src_reg_type = regs[insn->src_reg].type; 6603 6604 /* Check if (src_reg + off) is readable. The state of dst_reg will be 6605 * updated by this call. 6606 */ 6607 err = check_mem_access(env, env->insn_idx, insn->src_reg, insn->off, 6608 BPF_SIZE(insn->code), BPF_READ, insn->dst_reg, 6609 strict_alignment_once, is_ldsx); 6610 err = err ?: save_aux_ptr_type(env, src_reg_type, 6611 allow_trust_mismatch); 6612 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], ctx); 6613 6614 return err; 6615 } 6616 6617 static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn, 6618 bool strict_alignment_once) 6619 { 6620 struct bpf_reg_state *regs = cur_regs(env); 6621 enum bpf_reg_type dst_reg_type; 6622 int err; 6623 6624 /* check src1 operand */ 6625 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6626 if (err) 6627 return err; 6628 6629 /* check src2 operand */ 6630 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6631 if (err) 6632 return err; 6633 6634 dst_reg_type = regs[insn->dst_reg].type; 6635 6636 /* Check if (dst_reg + off) is writeable. */ 6637 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 6638 BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg, 6639 strict_alignment_once, false); 6640 err = err ?: save_aux_ptr_type(env, dst_reg_type, false); 6641 6642 return err; 6643 } 6644 6645 static int check_atomic_rmw(struct bpf_verifier_env *env, 6646 struct bpf_insn *insn) 6647 { 6648 int load_reg; 6649 int err; 6650 6651 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6652 verbose(env, "invalid atomic operand size\n"); 6653 return -EINVAL; 6654 } 6655 6656 /* check src1 operand */ 6657 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6658 if (err) 6659 return err; 6660 6661 /* check src2 operand */ 6662 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6663 if (err) 6664 return err; 6665 6666 if (insn->imm == BPF_CMPXCHG) { 6667 /* Check comparison of R0 with memory location */ 6668 const u32 aux_reg = BPF_REG_0; 6669 6670 err = check_reg_arg(env, aux_reg, SRC_OP); 6671 if (err) 6672 return err; 6673 6674 if (is_pointer_value(env, aux_reg)) { 6675 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6676 return -EACCES; 6677 } 6678 } 6679 6680 if (is_pointer_value(env, insn->src_reg)) { 6681 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6682 return -EACCES; 6683 } 6684 6685 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6686 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6687 insn->dst_reg, 6688 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6689 return -EACCES; 6690 } 6691 6692 if (insn->imm & BPF_FETCH) { 6693 if (insn->imm == BPF_CMPXCHG) 6694 load_reg = BPF_REG_0; 6695 else 6696 load_reg = insn->src_reg; 6697 6698 /* check and record load of old value */ 6699 err = check_reg_arg(env, load_reg, DST_OP); 6700 if (err) 6701 return err; 6702 } else { 6703 /* This instruction accesses a memory location but doesn't 6704 * actually load it into a register. 6705 */ 6706 load_reg = -1; 6707 } 6708 6709 /* Check whether we can read the memory, with second call for fetch 6710 * case to simulate the register fill. 6711 */ 6712 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 6713 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 6714 if (!err && load_reg >= 0) 6715 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 6716 insn->off, BPF_SIZE(insn->code), 6717 BPF_READ, load_reg, true, false); 6718 if (err) 6719 return err; 6720 6721 if (is_arena_reg(env, insn->dst_reg)) { 6722 err = save_aux_ptr_type(env, PTR_TO_ARENA, false); 6723 if (err) 6724 return err; 6725 } 6726 /* Check whether we can write into the same memory. */ 6727 err = check_mem_access(env, env->insn_idx, insn->dst_reg, insn->off, 6728 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 6729 if (err) 6730 return err; 6731 return 0; 6732 } 6733 6734 static int check_atomic_load(struct bpf_verifier_env *env, 6735 struct bpf_insn *insn) 6736 { 6737 int err; 6738 6739 err = check_load_mem(env, insn, true, false, false, "atomic_load"); 6740 if (err) 6741 return err; 6742 6743 if (!atomic_ptr_type_ok(env, insn->src_reg, insn)) { 6744 verbose(env, "BPF_ATOMIC loads from R%d %s is not allowed\n", 6745 insn->src_reg, 6746 reg_type_str(env, reg_state(env, insn->src_reg)->type)); 6747 return -EACCES; 6748 } 6749 6750 return 0; 6751 } 6752 6753 static int check_atomic_store(struct bpf_verifier_env *env, 6754 struct bpf_insn *insn) 6755 { 6756 int err; 6757 6758 err = check_store_reg(env, insn, true); 6759 if (err) 6760 return err; 6761 6762 if (!atomic_ptr_type_ok(env, insn->dst_reg, insn)) { 6763 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6764 insn->dst_reg, 6765 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6766 return -EACCES; 6767 } 6768 6769 return 0; 6770 } 6771 6772 static int check_atomic(struct bpf_verifier_env *env, struct bpf_insn *insn) 6773 { 6774 switch (insn->imm) { 6775 case BPF_ADD: 6776 case BPF_ADD | BPF_FETCH: 6777 case BPF_AND: 6778 case BPF_AND | BPF_FETCH: 6779 case BPF_OR: 6780 case BPF_OR | BPF_FETCH: 6781 case BPF_XOR: 6782 case BPF_XOR | BPF_FETCH: 6783 case BPF_XCHG: 6784 case BPF_CMPXCHG: 6785 return check_atomic_rmw(env, insn); 6786 case BPF_LOAD_ACQ: 6787 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6788 verbose(env, 6789 "64-bit load-acquires are only supported on 64-bit arches\n"); 6790 return -EOPNOTSUPP; 6791 } 6792 return check_atomic_load(env, insn); 6793 case BPF_STORE_REL: 6794 if (BPF_SIZE(insn->code) == BPF_DW && BITS_PER_LONG != 64) { 6795 verbose(env, 6796 "64-bit store-releases are only supported on 64-bit arches\n"); 6797 return -EOPNOTSUPP; 6798 } 6799 return check_atomic_store(env, insn); 6800 default: 6801 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", 6802 insn->imm); 6803 return -EINVAL; 6804 } 6805 } 6806 6807 /* When register 'regno' is used to read the stack (either directly or through 6808 * a helper function) make sure that it's within stack boundary and, depending 6809 * on the access type and privileges, that all elements of the stack are 6810 * initialized. 6811 * 6812 * All registers that have been spilled on the stack in the slots within the 6813 * read offsets are marked as read. 6814 */ 6815 static int check_stack_range_initialized( 6816 struct bpf_verifier_env *env, int regno, int off, 6817 int access_size, bool zero_size_allowed, 6818 enum bpf_access_type type, struct bpf_call_arg_meta *meta) 6819 { 6820 struct bpf_reg_state *reg = reg_state(env, regno); 6821 struct bpf_func_state *state = bpf_func(env, reg); 6822 int err, min_off, max_off, i, j, slot, spi; 6823 /* Some accesses can write anything into the stack, others are 6824 * read-only. 6825 */ 6826 bool clobber = type == BPF_WRITE; 6827 /* 6828 * Negative access_size signals global subprog/kfunc arg check where 6829 * STACK_POISON slots are acceptable. static stack liveness 6830 * might have determined that subprog doesn't read them, 6831 * but BTF based global subprog validation isn't accurate enough. 6832 */ 6833 bool allow_poison = access_size < 0 || clobber; 6834 6835 access_size = abs(access_size); 6836 6837 if (access_size == 0 && !zero_size_allowed) { 6838 verbose(env, "invalid zero-sized read\n"); 6839 return -EACCES; 6840 } 6841 6842 err = check_stack_access_within_bounds(env, regno, off, access_size, type); 6843 if (err) 6844 return err; 6845 6846 6847 if (tnum_is_const(reg->var_off)) { 6848 min_off = max_off = reg->var_off.value + off; 6849 } else { 6850 /* Variable offset is prohibited for unprivileged mode for 6851 * simplicity since it requires corresponding support in 6852 * Spectre masking for stack ALU. 6853 * See also retrieve_ptr_limit(). 6854 */ 6855 if (!env->bypass_spec_v1) { 6856 char tn_buf[48]; 6857 6858 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6859 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 6860 regno, tn_buf); 6861 return -EACCES; 6862 } 6863 /* Only initialized buffer on stack is allowed to be accessed 6864 * with variable offset. With uninitialized buffer it's hard to 6865 * guarantee that whole memory is marked as initialized on 6866 * helper return since specific bounds are unknown what may 6867 * cause uninitialized stack leaking. 6868 */ 6869 if (meta && meta->raw_mode) 6870 meta = NULL; 6871 6872 min_off = reg->smin_value + off; 6873 max_off = reg->smax_value + off; 6874 } 6875 6876 if (meta && meta->raw_mode) { 6877 /* Ensure we won't be overwriting dynptrs when simulating byte 6878 * by byte access in check_helper_call using meta.access_size. 6879 * This would be a problem if we have a helper in the future 6880 * which takes: 6881 * 6882 * helper(uninit_mem, len, dynptr) 6883 * 6884 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 6885 * may end up writing to dynptr itself when touching memory from 6886 * arg 1. This can be relaxed on a case by case basis for known 6887 * safe cases, but reject due to the possibilitiy of aliasing by 6888 * default. 6889 */ 6890 for (i = min_off; i < max_off + access_size; i++) { 6891 int stack_off = -i - 1; 6892 6893 spi = bpf_get_spi(i); 6894 /* raw_mode may write past allocated_stack */ 6895 if (state->allocated_stack <= stack_off) 6896 continue; 6897 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 6898 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 6899 return -EACCES; 6900 } 6901 } 6902 meta->access_size = access_size; 6903 meta->regno = regno; 6904 return 0; 6905 } 6906 6907 for (i = min_off; i < max_off + access_size; i++) { 6908 u8 *stype; 6909 6910 slot = -i - 1; 6911 spi = slot / BPF_REG_SIZE; 6912 if (state->allocated_stack <= slot) { 6913 verbose(env, "allocated_stack too small\n"); 6914 return -EFAULT; 6915 } 6916 6917 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 6918 if (*stype == STACK_MISC) 6919 goto mark; 6920 if ((*stype == STACK_ZERO) || 6921 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 6922 if (clobber) { 6923 /* helper can write anything into the stack */ 6924 *stype = STACK_MISC; 6925 } 6926 goto mark; 6927 } 6928 6929 if (bpf_is_spilled_reg(&state->stack[spi]) && 6930 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 6931 env->allow_ptr_leaks)) { 6932 if (clobber) { 6933 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 6934 for (j = 0; j < BPF_REG_SIZE; j++) 6935 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 6936 } 6937 goto mark; 6938 } 6939 6940 if (*stype == STACK_POISON) { 6941 if (allow_poison) 6942 goto mark; 6943 verbose(env, "reading from stack R%d off %d+%d size %d, slot poisoned by dead code elimination\n", 6944 regno, min_off, i - min_off, access_size); 6945 } else if (tnum_is_const(reg->var_off)) { 6946 verbose(env, "invalid read from stack R%d off %d+%d size %d\n", 6947 regno, min_off, i - min_off, access_size); 6948 } else { 6949 char tn_buf[48]; 6950 6951 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6952 verbose(env, "invalid read from stack R%d var_off %s+%d size %d\n", 6953 regno, tn_buf, i - min_off, access_size); 6954 } 6955 return -EACCES; 6956 mark: 6957 ; 6958 } 6959 return 0; 6960 } 6961 6962 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 6963 int access_size, enum bpf_access_type access_type, 6964 bool zero_size_allowed, 6965 struct bpf_call_arg_meta *meta) 6966 { 6967 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6968 u32 *max_access; 6969 6970 switch (base_type(reg->type)) { 6971 case PTR_TO_PACKET: 6972 case PTR_TO_PACKET_META: 6973 return check_packet_access(env, regno, 0, access_size, 6974 zero_size_allowed); 6975 case PTR_TO_MAP_KEY: 6976 if (access_type == BPF_WRITE) { 6977 verbose(env, "R%d cannot write into %s\n", regno, 6978 reg_type_str(env, reg->type)); 6979 return -EACCES; 6980 } 6981 return check_mem_region_access(env, regno, 0, access_size, 6982 reg->map_ptr->key_size, false); 6983 case PTR_TO_MAP_VALUE: 6984 if (check_map_access_type(env, regno, 0, access_size, access_type)) 6985 return -EACCES; 6986 return check_map_access(env, regno, 0, access_size, 6987 zero_size_allowed, ACCESS_HELPER); 6988 case PTR_TO_MEM: 6989 if (type_is_rdonly_mem(reg->type)) { 6990 if (access_type == BPF_WRITE) { 6991 verbose(env, "R%d cannot write into %s\n", regno, 6992 reg_type_str(env, reg->type)); 6993 return -EACCES; 6994 } 6995 } 6996 return check_mem_region_access(env, regno, 0, 6997 access_size, reg->mem_size, 6998 zero_size_allowed); 6999 case PTR_TO_BUF: 7000 if (type_is_rdonly_mem(reg->type)) { 7001 if (access_type == BPF_WRITE) { 7002 verbose(env, "R%d cannot write into %s\n", regno, 7003 reg_type_str(env, reg->type)); 7004 return -EACCES; 7005 } 7006 7007 max_access = &env->prog->aux->max_rdonly_access; 7008 } else { 7009 max_access = &env->prog->aux->max_rdwr_access; 7010 } 7011 return check_buffer_access(env, reg, regno, 0, 7012 access_size, zero_size_allowed, 7013 max_access); 7014 case PTR_TO_STACK: 7015 return check_stack_range_initialized( 7016 env, 7017 regno, 0, access_size, 7018 zero_size_allowed, access_type, meta); 7019 case PTR_TO_BTF_ID: 7020 return check_ptr_to_btf_access(env, regs, regno, 0, 7021 access_size, BPF_READ, -1); 7022 case PTR_TO_CTX: 7023 /* Only permit reading or writing syscall context using helper calls. */ 7024 if (is_var_ctx_off_allowed(env->prog)) { 7025 int err = check_mem_region_access(env, regno, 0, access_size, U16_MAX, 7026 zero_size_allowed); 7027 if (err) 7028 return err; 7029 if (env->prog->aux->max_ctx_offset < reg->umax_value + access_size) 7030 env->prog->aux->max_ctx_offset = reg->umax_value + access_size; 7031 return 0; 7032 } 7033 fallthrough; 7034 default: /* scalar_value or invalid ptr */ 7035 /* Allow zero-byte read from NULL, regardless of pointer type */ 7036 if (zero_size_allowed && access_size == 0 && 7037 bpf_register_is_null(reg)) 7038 return 0; 7039 7040 verbose(env, "R%d type=%s ", regno, 7041 reg_type_str(env, reg->type)); 7042 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7043 return -EACCES; 7044 } 7045 } 7046 7047 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7048 * size. 7049 * 7050 * @regno is the register containing the access size. regno-1 is the register 7051 * containing the pointer. 7052 */ 7053 static int check_mem_size_reg(struct bpf_verifier_env *env, 7054 struct bpf_reg_state *reg, u32 regno, 7055 enum bpf_access_type access_type, 7056 bool zero_size_allowed, 7057 struct bpf_call_arg_meta *meta) 7058 { 7059 int err; 7060 7061 /* This is used to refine r0 return value bounds for helpers 7062 * that enforce this value as an upper bound on return values. 7063 * See do_refine_retval_range() for helpers that can refine 7064 * the return value. C type of helper is u32 so we pull register 7065 * bound from umax_value however, if negative verifier errors 7066 * out. Only upper bounds can be learned because retval is an 7067 * int type and negative retvals are allowed. 7068 */ 7069 meta->msize_max_value = reg->umax_value; 7070 7071 /* The register is SCALAR_VALUE; the access check happens using 7072 * its boundaries. For unprivileged variable accesses, disable 7073 * raw mode so that the program is required to initialize all 7074 * the memory that the helper could just partially fill up. 7075 */ 7076 if (!tnum_is_const(reg->var_off)) 7077 meta = NULL; 7078 7079 if (reg->smin_value < 0) { 7080 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7081 regno); 7082 return -EACCES; 7083 } 7084 7085 if (reg->umin_value == 0 && !zero_size_allowed) { 7086 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7087 regno, reg->umin_value, reg->umax_value); 7088 return -EACCES; 7089 } 7090 7091 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7092 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7093 regno); 7094 return -EACCES; 7095 } 7096 err = check_helper_mem_access(env, regno - 1, reg->umax_value, 7097 access_type, zero_size_allowed, meta); 7098 if (!err) 7099 err = mark_chain_precision(env, regno); 7100 return err; 7101 } 7102 7103 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7104 u32 regno, u32 mem_size) 7105 { 7106 bool may_be_null = type_may_be_null(reg->type); 7107 struct bpf_reg_state saved_reg; 7108 int err; 7109 7110 if (bpf_register_is_null(reg)) 7111 return 0; 7112 7113 /* Assuming that the register contains a value check if the memory 7114 * access is safe. Temporarily save and restore the register's state as 7115 * the conversion shouldn't be visible to a caller. 7116 */ 7117 if (may_be_null) { 7118 saved_reg = *reg; 7119 mark_ptr_not_null_reg(reg); 7120 } 7121 7122 int size = base_type(reg->type) == PTR_TO_STACK ? -(int)mem_size : mem_size; 7123 7124 err = check_helper_mem_access(env, regno, size, BPF_READ, true, NULL); 7125 err = err ?: check_helper_mem_access(env, regno, size, BPF_WRITE, true, NULL); 7126 7127 if (may_be_null) 7128 *reg = saved_reg; 7129 7130 return err; 7131 } 7132 7133 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7134 u32 regno) 7135 { 7136 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7137 bool may_be_null = type_may_be_null(mem_reg->type); 7138 struct bpf_reg_state saved_reg; 7139 struct bpf_call_arg_meta meta; 7140 int err; 7141 7142 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7143 7144 memset(&meta, 0, sizeof(meta)); 7145 7146 if (may_be_null) { 7147 saved_reg = *mem_reg; 7148 mark_ptr_not_null_reg(mem_reg); 7149 } 7150 7151 err = check_mem_size_reg(env, reg, regno, BPF_READ, true, &meta); 7152 err = err ?: check_mem_size_reg(env, reg, regno, BPF_WRITE, true, &meta); 7153 7154 if (may_be_null) 7155 *mem_reg = saved_reg; 7156 7157 return err; 7158 } 7159 7160 enum { 7161 PROCESS_SPIN_LOCK = (1 << 0), 7162 PROCESS_RES_LOCK = (1 << 1), 7163 PROCESS_LOCK_IRQ = (1 << 2), 7164 }; 7165 7166 /* Implementation details: 7167 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7168 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7169 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7170 * Two separate bpf_obj_new will also have different reg->id. 7171 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7172 * clears reg->id after value_or_null->value transition, since the verifier only 7173 * cares about the range of access to valid map value pointer and doesn't care 7174 * about actual address of the map element. 7175 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7176 * reg->id > 0 after value_or_null->value transition. By doing so 7177 * two bpf_map_lookups will be considered two different pointers that 7178 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7179 * returned from bpf_obj_new. 7180 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7181 * dead-locks. 7182 * Since only one bpf_spin_lock is allowed the checks are simpler than 7183 * reg_is_refcounted() logic. The verifier needs to remember only 7184 * one spin_lock instead of array of acquired_refs. 7185 * env->cur_state->active_locks remembers which map value element or allocated 7186 * object got locked and clears it after bpf_spin_unlock. 7187 */ 7188 static int process_spin_lock(struct bpf_verifier_env *env, int regno, int flags) 7189 { 7190 bool is_lock = flags & PROCESS_SPIN_LOCK, is_res_lock = flags & PROCESS_RES_LOCK; 7191 const char *lock_str = is_res_lock ? "bpf_res_spin" : "bpf_spin"; 7192 struct bpf_reg_state *reg = reg_state(env, regno); 7193 struct bpf_verifier_state *cur = env->cur_state; 7194 bool is_const = tnum_is_const(reg->var_off); 7195 bool is_irq = flags & PROCESS_LOCK_IRQ; 7196 u64 val = reg->var_off.value; 7197 struct bpf_map *map = NULL; 7198 struct btf *btf = NULL; 7199 struct btf_record *rec; 7200 u32 spin_lock_off; 7201 int err; 7202 7203 if (!is_const) { 7204 verbose(env, 7205 "R%d doesn't have constant offset. %s_lock has to be at the constant offset\n", 7206 regno, lock_str); 7207 return -EINVAL; 7208 } 7209 if (reg->type == PTR_TO_MAP_VALUE) { 7210 map = reg->map_ptr; 7211 if (!map->btf) { 7212 verbose(env, 7213 "map '%s' has to have BTF in order to use %s_lock\n", 7214 map->name, lock_str); 7215 return -EINVAL; 7216 } 7217 } else { 7218 btf = reg->btf; 7219 } 7220 7221 rec = reg_btf_record(reg); 7222 if (!btf_record_has_field(rec, is_res_lock ? BPF_RES_SPIN_LOCK : BPF_SPIN_LOCK)) { 7223 verbose(env, "%s '%s' has no valid %s_lock\n", map ? "map" : "local", 7224 map ? map->name : "kptr", lock_str); 7225 return -EINVAL; 7226 } 7227 spin_lock_off = is_res_lock ? rec->res_spin_lock_off : rec->spin_lock_off; 7228 if (spin_lock_off != val) { 7229 verbose(env, "off %lld doesn't point to 'struct %s_lock' that is at %d\n", 7230 val, lock_str, spin_lock_off); 7231 return -EINVAL; 7232 } 7233 if (is_lock) { 7234 void *ptr; 7235 int type; 7236 7237 if (map) 7238 ptr = map; 7239 else 7240 ptr = btf; 7241 7242 if (!is_res_lock && cur->active_locks) { 7243 if (find_lock_state(env->cur_state, REF_TYPE_LOCK, 0, NULL)) { 7244 verbose(env, 7245 "Locking two bpf_spin_locks are not allowed\n"); 7246 return -EINVAL; 7247 } 7248 } else if (is_res_lock && cur->active_locks) { 7249 if (find_lock_state(env->cur_state, REF_TYPE_RES_LOCK | REF_TYPE_RES_LOCK_IRQ, reg->id, ptr)) { 7250 verbose(env, "Acquiring the same lock again, AA deadlock detected\n"); 7251 return -EINVAL; 7252 } 7253 } 7254 7255 if (is_res_lock && is_irq) 7256 type = REF_TYPE_RES_LOCK_IRQ; 7257 else if (is_res_lock) 7258 type = REF_TYPE_RES_LOCK; 7259 else 7260 type = REF_TYPE_LOCK; 7261 err = acquire_lock_state(env, env->insn_idx, type, reg->id, ptr); 7262 if (err < 0) { 7263 verbose(env, "Failed to acquire lock state\n"); 7264 return err; 7265 } 7266 } else { 7267 void *ptr; 7268 int type; 7269 7270 if (map) 7271 ptr = map; 7272 else 7273 ptr = btf; 7274 7275 if (!cur->active_locks) { 7276 verbose(env, "%s_unlock without taking a lock\n", lock_str); 7277 return -EINVAL; 7278 } 7279 7280 if (is_res_lock && is_irq) 7281 type = REF_TYPE_RES_LOCK_IRQ; 7282 else if (is_res_lock) 7283 type = REF_TYPE_RES_LOCK; 7284 else 7285 type = REF_TYPE_LOCK; 7286 if (!find_lock_state(cur, type, reg->id, ptr)) { 7287 verbose(env, "%s_unlock of different lock\n", lock_str); 7288 return -EINVAL; 7289 } 7290 if (reg->id != cur->active_lock_id || ptr != cur->active_lock_ptr) { 7291 verbose(env, "%s_unlock cannot be out of order\n", lock_str); 7292 return -EINVAL; 7293 } 7294 if (release_lock_state(cur, type, reg->id, ptr)) { 7295 verbose(env, "%s_unlock of different lock\n", lock_str); 7296 return -EINVAL; 7297 } 7298 7299 invalidate_non_owning_refs(env); 7300 } 7301 return 0; 7302 } 7303 7304 /* Check if @regno is a pointer to a specific field in a map value */ 7305 static int check_map_field_pointer(struct bpf_verifier_env *env, u32 regno, 7306 enum btf_field_type field_type, 7307 struct bpf_map_desc *map_desc) 7308 { 7309 struct bpf_reg_state *reg = reg_state(env, regno); 7310 bool is_const = tnum_is_const(reg->var_off); 7311 struct bpf_map *map = reg->map_ptr; 7312 u64 val = reg->var_off.value; 7313 const char *struct_name = btf_field_type_name(field_type); 7314 int field_off = -1; 7315 7316 if (!is_const) { 7317 verbose(env, 7318 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 7319 regno, struct_name); 7320 return -EINVAL; 7321 } 7322 if (!map->btf) { 7323 verbose(env, "map '%s' has to have BTF in order to use %s\n", map->name, 7324 struct_name); 7325 return -EINVAL; 7326 } 7327 if (!btf_record_has_field(map->record, field_type)) { 7328 verbose(env, "map '%s' has no valid %s\n", map->name, struct_name); 7329 return -EINVAL; 7330 } 7331 switch (field_type) { 7332 case BPF_TIMER: 7333 field_off = map->record->timer_off; 7334 break; 7335 case BPF_TASK_WORK: 7336 field_off = map->record->task_work_off; 7337 break; 7338 case BPF_WORKQUEUE: 7339 field_off = map->record->wq_off; 7340 break; 7341 default: 7342 verifier_bug(env, "unsupported BTF field type: %s\n", struct_name); 7343 return -EINVAL; 7344 } 7345 if (field_off != val) { 7346 verbose(env, "off %lld doesn't point to 'struct %s' that is at %d\n", 7347 val, struct_name, field_off); 7348 return -EINVAL; 7349 } 7350 if (map_desc->ptr) { 7351 verifier_bug(env, "Two map pointers in a %s helper", struct_name); 7352 return -EFAULT; 7353 } 7354 map_desc->uid = reg->map_uid; 7355 map_desc->ptr = map; 7356 return 0; 7357 } 7358 7359 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7360 struct bpf_map_desc *map) 7361 { 7362 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 7363 verbose(env, "bpf_timer cannot be used for PREEMPT_RT.\n"); 7364 return -EOPNOTSUPP; 7365 } 7366 return check_map_field_pointer(env, regno, BPF_TIMER, map); 7367 } 7368 7369 static int process_timer_helper(struct bpf_verifier_env *env, int regno, 7370 struct bpf_call_arg_meta *meta) 7371 { 7372 return process_timer_func(env, regno, &meta->map); 7373 } 7374 7375 static int process_timer_kfunc(struct bpf_verifier_env *env, int regno, 7376 struct bpf_kfunc_call_arg_meta *meta) 7377 { 7378 return process_timer_func(env, regno, &meta->map); 7379 } 7380 7381 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7382 struct bpf_call_arg_meta *meta) 7383 { 7384 struct bpf_reg_state *reg = reg_state(env, regno); 7385 struct btf_field *kptr_field; 7386 struct bpf_map *map_ptr; 7387 struct btf_record *rec; 7388 u32 kptr_off; 7389 7390 if (type_is_ptr_alloc_obj(reg->type)) { 7391 rec = reg_btf_record(reg); 7392 } else { /* PTR_TO_MAP_VALUE */ 7393 map_ptr = reg->map_ptr; 7394 if (!map_ptr->btf) { 7395 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7396 map_ptr->name); 7397 return -EINVAL; 7398 } 7399 rec = map_ptr->record; 7400 meta->map.ptr = map_ptr; 7401 } 7402 7403 if (!tnum_is_const(reg->var_off)) { 7404 verbose(env, 7405 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7406 regno); 7407 return -EINVAL; 7408 } 7409 7410 if (!btf_record_has_field(rec, BPF_KPTR)) { 7411 verbose(env, "R%d has no valid kptr\n", regno); 7412 return -EINVAL; 7413 } 7414 7415 kptr_off = reg->var_off.value; 7416 kptr_field = btf_record_find(rec, kptr_off, BPF_KPTR); 7417 if (!kptr_field) { 7418 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7419 return -EACCES; 7420 } 7421 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7422 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7423 return -EACCES; 7424 } 7425 meta->kptr_field = kptr_field; 7426 return 0; 7427 } 7428 7429 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7430 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7431 * 7432 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7433 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7434 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7435 * 7436 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7437 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7438 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7439 * mutate the view of the dynptr and also possibly destroy it. In the latter 7440 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7441 * memory that dynptr points to. 7442 * 7443 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7444 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7445 * readonly dynptr view yet, hence only the first case is tracked and checked. 7446 * 7447 * This is consistent with how C applies the const modifier to a struct object, 7448 * where the pointer itself inside bpf_dynptr becomes const but not what it 7449 * points to. 7450 * 7451 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7452 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7453 */ 7454 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7455 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7456 { 7457 struct bpf_reg_state *reg = reg_state(env, regno); 7458 int err; 7459 7460 if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) { 7461 verbose(env, 7462 "arg#%d expected pointer to stack or const struct bpf_dynptr\n", 7463 regno - 1); 7464 return -EINVAL; 7465 } 7466 7467 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7468 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7469 */ 7470 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7471 verifier_bug(env, "misconfigured dynptr helper type flags"); 7472 return -EFAULT; 7473 } 7474 7475 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7476 * constructing a mutable bpf_dynptr object. 7477 * 7478 * Currently, this is only possible with PTR_TO_STACK 7479 * pointing to a region of at least 16 bytes which doesn't 7480 * contain an existing bpf_dynptr. 7481 * 7482 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7483 * mutated or destroyed. However, the memory it points to 7484 * may be mutated. 7485 * 7486 * None - Points to a initialized dynptr that can be mutated and 7487 * destroyed, including mutation of the memory it points 7488 * to. 7489 */ 7490 if (arg_type & MEM_UNINIT) { 7491 int i; 7492 7493 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7494 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7495 return -EINVAL; 7496 } 7497 7498 /* we write BPF_DW bits (8 bytes) at a time */ 7499 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7500 err = check_mem_access(env, insn_idx, regno, 7501 i, BPF_DW, BPF_WRITE, -1, false, false); 7502 if (err) 7503 return err; 7504 } 7505 7506 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7507 } else /* MEM_RDONLY and None case from above */ { 7508 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7509 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7510 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7511 return -EINVAL; 7512 } 7513 7514 if (!is_dynptr_reg_valid_init(env, reg)) { 7515 verbose(env, 7516 "Expected an initialized dynptr as arg #%d\n", 7517 regno - 1); 7518 return -EINVAL; 7519 } 7520 7521 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7522 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7523 verbose(env, 7524 "Expected a dynptr of type %s as arg #%d\n", 7525 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno - 1); 7526 return -EINVAL; 7527 } 7528 7529 err = mark_dynptr_read(env, reg); 7530 } 7531 return err; 7532 } 7533 7534 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7535 { 7536 struct bpf_func_state *state = bpf_func(env, reg); 7537 7538 return state->stack[spi].spilled_ptr.ref_obj_id; 7539 } 7540 7541 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7542 { 7543 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7544 } 7545 7546 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7547 { 7548 return meta->kfunc_flags & KF_ITER_NEW; 7549 } 7550 7551 7552 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7553 { 7554 return meta->kfunc_flags & KF_ITER_DESTROY; 7555 } 7556 7557 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg_idx, 7558 const struct btf_param *arg) 7559 { 7560 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7561 * kfunc is iter state pointer 7562 */ 7563 if (is_iter_kfunc(meta)) 7564 return arg_idx == 0; 7565 7566 /* iter passed as an argument to a generic kfunc */ 7567 return btf_param_match_suffix(meta->btf, arg, "__iter"); 7568 } 7569 7570 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7571 struct bpf_kfunc_call_arg_meta *meta) 7572 { 7573 struct bpf_reg_state *reg = reg_state(env, regno); 7574 const struct btf_type *t; 7575 int spi, err, i, nr_slots, btf_id; 7576 7577 if (reg->type != PTR_TO_STACK) { 7578 verbose(env, "arg#%d expected pointer to an iterator on stack\n", regno - 1); 7579 return -EINVAL; 7580 } 7581 7582 /* For iter_{new,next,destroy} functions, btf_check_iter_kfuncs() 7583 * ensures struct convention, so we wouldn't need to do any BTF 7584 * validation here. But given iter state can be passed as a parameter 7585 * to any kfunc, if arg has "__iter" suffix, we need to be a bit more 7586 * conservative here. 7587 */ 7588 btf_id = btf_check_iter_arg(meta->btf, meta->func_proto, regno - 1); 7589 if (btf_id < 0) { 7590 verbose(env, "expected valid iter pointer as arg #%d\n", regno - 1); 7591 return -EINVAL; 7592 } 7593 t = btf_type_by_id(meta->btf, btf_id); 7594 nr_slots = t->size / BPF_REG_SIZE; 7595 7596 if (is_iter_new_kfunc(meta)) { 7597 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7598 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7599 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7600 iter_type_str(meta->btf, btf_id), regno - 1); 7601 return -EINVAL; 7602 } 7603 7604 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7605 err = check_mem_access(env, insn_idx, regno, 7606 i, BPF_DW, BPF_WRITE, -1, false, false); 7607 if (err) 7608 return err; 7609 } 7610 7611 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7612 if (err) 7613 return err; 7614 } else { 7615 /* iter_next() or iter_destroy(), as well as any kfunc 7616 * accepting iter argument, expect initialized iter state 7617 */ 7618 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7619 switch (err) { 7620 case 0: 7621 break; 7622 case -EINVAL: 7623 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7624 iter_type_str(meta->btf, btf_id), regno - 1); 7625 return err; 7626 case -EPROTO: 7627 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7628 return err; 7629 default: 7630 return err; 7631 } 7632 7633 spi = iter_get_spi(env, reg, nr_slots); 7634 if (spi < 0) 7635 return spi; 7636 7637 err = mark_iter_read(env, reg, spi, nr_slots); 7638 if (err) 7639 return err; 7640 7641 /* remember meta->iter info for process_iter_next_call() */ 7642 meta->iter.spi = spi; 7643 meta->iter.frameno = reg->frameno; 7644 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7645 7646 if (is_iter_destroy_kfunc(meta)) { 7647 err = unmark_stack_slots_iter(env, reg, nr_slots); 7648 if (err) 7649 return err; 7650 } 7651 } 7652 7653 return 0; 7654 } 7655 7656 /* Look for a previous loop entry at insn_idx: nearest parent state 7657 * stopped at insn_idx with callsites matching those in cur->frame. 7658 */ 7659 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7660 struct bpf_verifier_state *cur, 7661 int insn_idx) 7662 { 7663 struct bpf_verifier_state_list *sl; 7664 struct bpf_verifier_state *st; 7665 struct list_head *pos, *head; 7666 7667 /* Explored states are pushed in stack order, most recent states come first */ 7668 head = bpf_explored_state(env, insn_idx); 7669 list_for_each(pos, head) { 7670 sl = container_of(pos, struct bpf_verifier_state_list, node); 7671 /* If st->branches != 0 state is a part of current DFS verification path, 7672 * hence cur & st for a loop. 7673 */ 7674 st = &sl->state; 7675 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7676 st->dfs_depth < cur->dfs_depth) 7677 return st; 7678 } 7679 7680 return NULL; 7681 } 7682 7683 /* 7684 * Check if scalar registers are exact for the purpose of not widening. 7685 * More lenient than regs_exact() 7686 */ 7687 static bool scalars_exact_for_widen(const struct bpf_reg_state *rold, 7688 const struct bpf_reg_state *rcur) 7689 { 7690 return !memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)); 7691 } 7692 7693 static void maybe_widen_reg(struct bpf_verifier_env *env, 7694 struct bpf_reg_state *rold, struct bpf_reg_state *rcur) 7695 { 7696 if (rold->type != SCALAR_VALUE) 7697 return; 7698 if (rold->type != rcur->type) 7699 return; 7700 if (rold->precise || rcur->precise || scalars_exact_for_widen(rold, rcur)) 7701 return; 7702 __mark_reg_unknown(env, rcur); 7703 } 7704 7705 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7706 struct bpf_verifier_state *old, 7707 struct bpf_verifier_state *cur) 7708 { 7709 struct bpf_func_state *fold, *fcur; 7710 int i, fr, num_slots; 7711 7712 for (fr = old->curframe; fr >= 0; fr--) { 7713 fold = old->frame[fr]; 7714 fcur = cur->frame[fr]; 7715 7716 for (i = 0; i < MAX_BPF_REG; i++) 7717 maybe_widen_reg(env, 7718 &fold->regs[i], 7719 &fcur->regs[i]); 7720 7721 num_slots = min(fold->allocated_stack / BPF_REG_SIZE, 7722 fcur->allocated_stack / BPF_REG_SIZE); 7723 for (i = 0; i < num_slots; i++) { 7724 if (!bpf_is_spilled_reg(&fold->stack[i]) || 7725 !bpf_is_spilled_reg(&fcur->stack[i])) 7726 continue; 7727 7728 maybe_widen_reg(env, 7729 &fold->stack[i].spilled_ptr, 7730 &fcur->stack[i].spilled_ptr); 7731 } 7732 } 7733 return 0; 7734 } 7735 7736 static struct bpf_reg_state *get_iter_from_state(struct bpf_verifier_state *cur_st, 7737 struct bpf_kfunc_call_arg_meta *meta) 7738 { 7739 int iter_frameno = meta->iter.frameno; 7740 int iter_spi = meta->iter.spi; 7741 7742 return &cur_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7743 } 7744 7745 /* process_iter_next_call() is called when verifier gets to iterator's next 7746 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7747 * to it as just "iter_next()" in comments below. 7748 * 7749 * BPF verifier relies on a crucial contract for any iter_next() 7750 * implementation: it should *eventually* return NULL, and once that happens 7751 * it should keep returning NULL. That is, once iterator exhausts elements to 7752 * iterate, it should never reset or spuriously return new elements. 7753 * 7754 * With the assumption of such contract, process_iter_next_call() simulates 7755 * a fork in the verifier state to validate loop logic correctness and safety 7756 * without having to simulate infinite amount of iterations. 7757 * 7758 * In current state, we first assume that iter_next() returned NULL and 7759 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7760 * conditions we should not form an infinite loop and should eventually reach 7761 * exit. 7762 * 7763 * Besides that, we also fork current state and enqueue it for later 7764 * verification. In a forked state we keep iterator state as ACTIVE 7765 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7766 * also bump iteration depth to prevent erroneous infinite loop detection 7767 * later on (see iter_active_depths_differ() comment for details). In this 7768 * state we assume that we'll eventually loop back to another iter_next() 7769 * calls (it could be in exactly same location or in some other instruction, 7770 * it doesn't matter, we don't make any unnecessary assumptions about this, 7771 * everything revolves around iterator state in a stack slot, not which 7772 * instruction is calling iter_next()). When that happens, we either will come 7773 * to iter_next() with equivalent state and can conclude that next iteration 7774 * will proceed in exactly the same way as we just verified, so it's safe to 7775 * assume that loop converges. If not, we'll go on another iteration 7776 * simulation with a different input state, until all possible starting states 7777 * are validated or we reach maximum number of instructions limit. 7778 * 7779 * This way, we will either exhaustively discover all possible input states 7780 * that iterator loop can start with and eventually will converge, or we'll 7781 * effectively regress into bounded loop simulation logic and either reach 7782 * maximum number of instructions if loop is not provably convergent, or there 7783 * is some statically known limit on number of iterations (e.g., if there is 7784 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7785 * 7786 * Iteration convergence logic in is_state_visited() relies on exact 7787 * states comparison, which ignores read and precision marks. 7788 * This is necessary because read and precision marks are not finalized 7789 * while in the loop. Exact comparison might preclude convergence for 7790 * simple programs like below: 7791 * 7792 * i = 0; 7793 * while(iter_next(&it)) 7794 * i++; 7795 * 7796 * At each iteration step i++ would produce a new distinct state and 7797 * eventually instruction processing limit would be reached. 7798 * 7799 * To avoid such behavior speculatively forget (widen) range for 7800 * imprecise scalar registers, if those registers were not precise at the 7801 * end of the previous iteration and do not match exactly. 7802 * 7803 * This is a conservative heuristic that allows to verify wide range of programs, 7804 * however it precludes verification of programs that conjure an 7805 * imprecise value on the first loop iteration and use it as precise on a second. 7806 * For example, the following safe program would fail to verify: 7807 * 7808 * struct bpf_num_iter it; 7809 * int arr[10]; 7810 * int i = 0, a = 0; 7811 * bpf_iter_num_new(&it, 0, 10); 7812 * while (bpf_iter_num_next(&it)) { 7813 * if (a == 0) { 7814 * a = 1; 7815 * i = 7; // Because i changed verifier would forget 7816 * // it's range on second loop entry. 7817 * } else { 7818 * arr[i] = 42; // This would fail to verify. 7819 * } 7820 * } 7821 * bpf_iter_num_destroy(&it); 7822 */ 7823 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7824 struct bpf_kfunc_call_arg_meta *meta) 7825 { 7826 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7827 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7828 struct bpf_reg_state *cur_iter, *queued_iter; 7829 7830 BTF_TYPE_EMIT(struct bpf_iter); 7831 7832 cur_iter = get_iter_from_state(cur_st, meta); 7833 7834 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7835 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7836 verifier_bug(env, "unexpected iterator state %d (%s)", 7837 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7838 return -EFAULT; 7839 } 7840 7841 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7842 /* Because iter_next() call is a checkpoint is_state_visitied() 7843 * should guarantee parent state with same call sites and insn_idx. 7844 */ 7845 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 7846 !same_callsites(cur_st->parent, cur_st)) { 7847 verifier_bug(env, "bad parent state for iter next call"); 7848 return -EFAULT; 7849 } 7850 /* Note cur_st->parent in the call below, it is necessary to skip 7851 * checkpoint created for cur_st by is_state_visited() 7852 * right at this instruction. 7853 */ 7854 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 7855 /* branch out active iter state */ 7856 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7857 if (IS_ERR(queued_st)) 7858 return PTR_ERR(queued_st); 7859 7860 queued_iter = get_iter_from_state(queued_st, meta); 7861 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7862 queued_iter->iter.depth++; 7863 if (prev_st) 7864 widen_imprecise_scalars(env, prev_st, queued_st); 7865 7866 queued_fr = queued_st->frame[queued_st->curframe]; 7867 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7868 } 7869 7870 /* switch to DRAINED state, but keep the depth unchanged */ 7871 /* mark current iter state as drained and assume returned NULL */ 7872 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7873 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 7874 7875 return 0; 7876 } 7877 7878 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7879 { 7880 return type == ARG_CONST_SIZE || 7881 type == ARG_CONST_SIZE_OR_ZERO; 7882 } 7883 7884 static bool arg_type_is_raw_mem(enum bpf_arg_type type) 7885 { 7886 return base_type(type) == ARG_PTR_TO_MEM && 7887 type & MEM_UNINIT; 7888 } 7889 7890 static bool arg_type_is_release(enum bpf_arg_type type) 7891 { 7892 return type & OBJ_RELEASE; 7893 } 7894 7895 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7896 { 7897 return base_type(type) == ARG_PTR_TO_DYNPTR; 7898 } 7899 7900 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7901 const struct bpf_call_arg_meta *meta, 7902 enum bpf_arg_type *arg_type) 7903 { 7904 if (!meta->map.ptr) { 7905 /* kernel subsystem misconfigured verifier */ 7906 verifier_bug(env, "invalid map_ptr to access map->type"); 7907 return -EFAULT; 7908 } 7909 7910 switch (meta->map.ptr->map_type) { 7911 case BPF_MAP_TYPE_SOCKMAP: 7912 case BPF_MAP_TYPE_SOCKHASH: 7913 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7914 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7915 } else { 7916 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7917 return -EINVAL; 7918 } 7919 break; 7920 case BPF_MAP_TYPE_BLOOM_FILTER: 7921 if (meta->func_id == BPF_FUNC_map_peek_elem) 7922 *arg_type = ARG_PTR_TO_MAP_VALUE; 7923 break; 7924 default: 7925 break; 7926 } 7927 return 0; 7928 } 7929 7930 struct bpf_reg_types { 7931 const enum bpf_reg_type types[10]; 7932 u32 *btf_id; 7933 }; 7934 7935 static const struct bpf_reg_types sock_types = { 7936 .types = { 7937 PTR_TO_SOCK_COMMON, 7938 PTR_TO_SOCKET, 7939 PTR_TO_TCP_SOCK, 7940 PTR_TO_XDP_SOCK, 7941 }, 7942 }; 7943 7944 #ifdef CONFIG_NET 7945 static const struct bpf_reg_types btf_id_sock_common_types = { 7946 .types = { 7947 PTR_TO_SOCK_COMMON, 7948 PTR_TO_SOCKET, 7949 PTR_TO_TCP_SOCK, 7950 PTR_TO_XDP_SOCK, 7951 PTR_TO_BTF_ID, 7952 PTR_TO_BTF_ID | PTR_TRUSTED, 7953 }, 7954 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7955 }; 7956 #endif 7957 7958 static const struct bpf_reg_types mem_types = { 7959 .types = { 7960 PTR_TO_STACK, 7961 PTR_TO_PACKET, 7962 PTR_TO_PACKET_META, 7963 PTR_TO_MAP_KEY, 7964 PTR_TO_MAP_VALUE, 7965 PTR_TO_MEM, 7966 PTR_TO_MEM | MEM_RINGBUF, 7967 PTR_TO_BUF, 7968 PTR_TO_BTF_ID | PTR_TRUSTED, 7969 PTR_TO_CTX, 7970 }, 7971 }; 7972 7973 static const struct bpf_reg_types spin_lock_types = { 7974 .types = { 7975 PTR_TO_MAP_VALUE, 7976 PTR_TO_BTF_ID | MEM_ALLOC, 7977 } 7978 }; 7979 7980 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7981 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7982 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7983 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7984 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7985 static const struct bpf_reg_types btf_ptr_types = { 7986 .types = { 7987 PTR_TO_BTF_ID, 7988 PTR_TO_BTF_ID | PTR_TRUSTED, 7989 PTR_TO_BTF_ID | MEM_RCU, 7990 }, 7991 }; 7992 static const struct bpf_reg_types percpu_btf_ptr_types = { 7993 .types = { 7994 PTR_TO_BTF_ID | MEM_PERCPU, 7995 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 7996 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7997 } 7998 }; 7999 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8000 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8001 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8002 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8003 static const struct bpf_reg_types kptr_xchg_dest_types = { 8004 .types = { 8005 PTR_TO_MAP_VALUE, 8006 PTR_TO_BTF_ID | MEM_ALLOC, 8007 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF, 8008 PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU, 8009 } 8010 }; 8011 static const struct bpf_reg_types dynptr_types = { 8012 .types = { 8013 PTR_TO_STACK, 8014 CONST_PTR_TO_DYNPTR, 8015 } 8016 }; 8017 8018 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8019 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8020 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8021 [ARG_CONST_SIZE] = &scalar_types, 8022 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8023 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8024 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8025 [ARG_PTR_TO_CTX] = &context_types, 8026 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8027 #ifdef CONFIG_NET 8028 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8029 #endif 8030 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8031 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8032 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8033 [ARG_PTR_TO_MEM] = &mem_types, 8034 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8035 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8036 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8037 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8038 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8039 [ARG_PTR_TO_TIMER] = &timer_types, 8040 [ARG_KPTR_XCHG_DEST] = &kptr_xchg_dest_types, 8041 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8042 }; 8043 8044 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8045 enum bpf_arg_type arg_type, 8046 const u32 *arg_btf_id, 8047 struct bpf_call_arg_meta *meta) 8048 { 8049 struct bpf_reg_state *reg = reg_state(env, regno); 8050 enum bpf_reg_type expected, type = reg->type; 8051 const struct bpf_reg_types *compatible; 8052 int i, j, err; 8053 8054 compatible = compatible_reg_types[base_type(arg_type)]; 8055 if (!compatible) { 8056 verifier_bug(env, "unsupported arg type %d", arg_type); 8057 return -EFAULT; 8058 } 8059 8060 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8061 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8062 * 8063 * Same for MAYBE_NULL: 8064 * 8065 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8066 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8067 * 8068 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8069 * 8070 * Therefore we fold these flags depending on the arg_type before comparison. 8071 */ 8072 if (arg_type & MEM_RDONLY) 8073 type &= ~MEM_RDONLY; 8074 if (arg_type & PTR_MAYBE_NULL) 8075 type &= ~PTR_MAYBE_NULL; 8076 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8077 type &= ~DYNPTR_TYPE_FLAG_MASK; 8078 8079 /* Local kptr types are allowed as the source argument of bpf_kptr_xchg */ 8080 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type) && regno == BPF_REG_2) { 8081 type &= ~MEM_ALLOC; 8082 type &= ~MEM_PERCPU; 8083 } 8084 8085 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8086 expected = compatible->types[i]; 8087 if (expected == NOT_INIT) 8088 break; 8089 8090 if (type == expected) 8091 goto found; 8092 } 8093 8094 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8095 for (j = 0; j + 1 < i; j++) 8096 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8097 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8098 return -EACCES; 8099 8100 found: 8101 if (base_type(reg->type) != PTR_TO_BTF_ID) 8102 return 0; 8103 8104 if (compatible == &mem_types) { 8105 if (!(arg_type & MEM_RDONLY)) { 8106 verbose(env, 8107 "%s() may write into memory pointed by R%d type=%s\n", 8108 func_id_name(meta->func_id), 8109 regno, reg_type_str(env, reg->type)); 8110 return -EACCES; 8111 } 8112 return 0; 8113 } 8114 8115 switch ((int)reg->type) { 8116 case PTR_TO_BTF_ID: 8117 case PTR_TO_BTF_ID | PTR_TRUSTED: 8118 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 8119 case PTR_TO_BTF_ID | MEM_RCU: 8120 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8121 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8122 { 8123 /* For bpf_sk_release, it needs to match against first member 8124 * 'struct sock_common', hence make an exception for it. This 8125 * allows bpf_sk_release to work for multiple socket types. 8126 */ 8127 bool strict_type_match = arg_type_is_release(arg_type) && 8128 meta->func_id != BPF_FUNC_sk_release; 8129 8130 if (type_may_be_null(reg->type) && 8131 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8132 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8133 return -EACCES; 8134 } 8135 8136 if (!arg_btf_id) { 8137 if (!compatible->btf_id) { 8138 verifier_bug(env, "missing arg compatible BTF ID"); 8139 return -EFAULT; 8140 } 8141 arg_btf_id = compatible->btf_id; 8142 } 8143 8144 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8145 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8146 return -EACCES; 8147 } else { 8148 if (arg_btf_id == BPF_PTR_POISON) { 8149 verbose(env, "verifier internal error:"); 8150 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8151 regno); 8152 return -EACCES; 8153 } 8154 8155 err = __check_ptr_off_reg(env, reg, regno, true); 8156 if (err) 8157 return err; 8158 8159 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 8160 reg->var_off.value, btf_vmlinux, *arg_btf_id, 8161 strict_type_match)) { 8162 verbose(env, "R%d is of type %s but %s is expected\n", 8163 regno, btf_type_name(reg->btf, reg->btf_id), 8164 btf_type_name(btf_vmlinux, *arg_btf_id)); 8165 return -EACCES; 8166 } 8167 } 8168 break; 8169 } 8170 case PTR_TO_BTF_ID | MEM_ALLOC: 8171 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8172 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8173 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8174 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8175 meta->func_id != BPF_FUNC_kptr_xchg) { 8176 verifier_bug(env, "unimplemented handling of MEM_ALLOC"); 8177 return -EFAULT; 8178 } 8179 /* Check if local kptr in src arg matches kptr in dst arg */ 8180 if (meta->func_id == BPF_FUNC_kptr_xchg && regno == BPF_REG_2) { 8181 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8182 return -EACCES; 8183 } 8184 break; 8185 case PTR_TO_BTF_ID | MEM_PERCPU: 8186 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8187 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8188 /* Handled by helper specific checks */ 8189 break; 8190 default: 8191 verifier_bug(env, "invalid PTR_TO_BTF_ID register for type match"); 8192 return -EFAULT; 8193 } 8194 return 0; 8195 } 8196 8197 static struct btf_field * 8198 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8199 { 8200 struct btf_field *field; 8201 struct btf_record *rec; 8202 8203 rec = reg_btf_record(reg); 8204 if (!rec) 8205 return NULL; 8206 8207 field = btf_record_find(rec, off, fields); 8208 if (!field) 8209 return NULL; 8210 8211 return field; 8212 } 8213 8214 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8215 const struct bpf_reg_state *reg, int regno, 8216 enum bpf_arg_type arg_type) 8217 { 8218 u32 type = reg->type; 8219 8220 /* When referenced register is passed to release function, its fixed 8221 * offset must be 0. 8222 * 8223 * We will check arg_type_is_release reg has ref_obj_id when storing 8224 * meta->release_regno. 8225 */ 8226 if (arg_type_is_release(arg_type)) { 8227 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8228 * may not directly point to the object being released, but to 8229 * dynptr pointing to such object, which might be at some offset 8230 * on the stack. In that case, we simply to fallback to the 8231 * default handling. 8232 */ 8233 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8234 return 0; 8235 8236 /* Doing check_ptr_off_reg check for the offset will catch this 8237 * because fixed_off_ok is false, but checking here allows us 8238 * to give the user a better error message. 8239 */ 8240 if (!tnum_is_const(reg->var_off) || reg->var_off.value != 0) { 8241 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8242 regno); 8243 return -EINVAL; 8244 } 8245 } 8246 8247 switch (type) { 8248 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8249 case PTR_TO_STACK: 8250 case PTR_TO_PACKET: 8251 case PTR_TO_PACKET_META: 8252 case PTR_TO_MAP_KEY: 8253 case PTR_TO_MAP_VALUE: 8254 case PTR_TO_MEM: 8255 case PTR_TO_MEM | MEM_RDONLY: 8256 case PTR_TO_MEM | MEM_RINGBUF: 8257 case PTR_TO_BUF: 8258 case PTR_TO_BUF | MEM_RDONLY: 8259 case PTR_TO_ARENA: 8260 case SCALAR_VALUE: 8261 return 0; 8262 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8263 * fixed offset. 8264 */ 8265 case PTR_TO_BTF_ID: 8266 case PTR_TO_BTF_ID | MEM_ALLOC: 8267 case PTR_TO_BTF_ID | PTR_TRUSTED: 8268 case PTR_TO_BTF_ID | MEM_RCU: 8269 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8270 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8271 /* When referenced PTR_TO_BTF_ID is passed to release function, 8272 * its fixed offset must be 0. In the other cases, fixed offset 8273 * can be non-zero. This was already checked above. So pass 8274 * fixed_off_ok as true to allow fixed offset for all other 8275 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8276 * still need to do checks instead of returning. 8277 */ 8278 return __check_ptr_off_reg(env, reg, regno, true); 8279 case PTR_TO_CTX: 8280 /* 8281 * Allow fixed and variable offsets for syscall context, but 8282 * only when the argument is passed as memory, not ctx, 8283 * otherwise we may get modified ctx in tail called programs and 8284 * global subprogs (that may act as extension prog hooks). 8285 */ 8286 if (arg_type != ARG_PTR_TO_CTX && is_var_ctx_off_allowed(env->prog)) 8287 return 0; 8288 fallthrough; 8289 default: 8290 return __check_ptr_off_reg(env, reg, regno, false); 8291 } 8292 } 8293 8294 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8295 const struct bpf_func_proto *fn, 8296 struct bpf_reg_state *regs) 8297 { 8298 struct bpf_reg_state *state = NULL; 8299 int i; 8300 8301 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8302 if (arg_type_is_dynptr(fn->arg_type[i])) { 8303 if (state) { 8304 verbose(env, "verifier internal error: multiple dynptr args\n"); 8305 return NULL; 8306 } 8307 state = ®s[BPF_REG_1 + i]; 8308 } 8309 8310 if (!state) 8311 verbose(env, "verifier internal error: no dynptr arg found\n"); 8312 8313 return state; 8314 } 8315 8316 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8317 { 8318 struct bpf_func_state *state = bpf_func(env, reg); 8319 int spi; 8320 8321 if (reg->type == CONST_PTR_TO_DYNPTR) 8322 return reg->id; 8323 spi = dynptr_get_spi(env, reg); 8324 if (spi < 0) 8325 return spi; 8326 return state->stack[spi].spilled_ptr.id; 8327 } 8328 8329 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8330 { 8331 struct bpf_func_state *state = bpf_func(env, reg); 8332 int spi; 8333 8334 if (reg->type == CONST_PTR_TO_DYNPTR) 8335 return reg->ref_obj_id; 8336 spi = dynptr_get_spi(env, reg); 8337 if (spi < 0) 8338 return spi; 8339 return state->stack[spi].spilled_ptr.ref_obj_id; 8340 } 8341 8342 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8343 struct bpf_reg_state *reg) 8344 { 8345 struct bpf_func_state *state = bpf_func(env, reg); 8346 int spi; 8347 8348 if (reg->type == CONST_PTR_TO_DYNPTR) 8349 return reg->dynptr.type; 8350 8351 spi = bpf_get_spi(reg->var_off.value); 8352 if (spi < 0) { 8353 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8354 return BPF_DYNPTR_TYPE_INVALID; 8355 } 8356 8357 return state->stack[spi].spilled_ptr.dynptr.type; 8358 } 8359 8360 static int check_reg_const_str(struct bpf_verifier_env *env, 8361 struct bpf_reg_state *reg, u32 regno) 8362 { 8363 struct bpf_map *map = reg->map_ptr; 8364 int err; 8365 int map_off; 8366 u64 map_addr; 8367 char *str_ptr; 8368 8369 if (reg->type != PTR_TO_MAP_VALUE) 8370 return -EINVAL; 8371 8372 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 8373 verbose(env, "R%d points to insn_array map which cannot be used as const string\n", regno); 8374 return -EACCES; 8375 } 8376 8377 if (!bpf_map_is_rdonly(map)) { 8378 verbose(env, "R%d does not point to a readonly map'\n", regno); 8379 return -EACCES; 8380 } 8381 8382 if (!tnum_is_const(reg->var_off)) { 8383 verbose(env, "R%d is not a constant address'\n", regno); 8384 return -EACCES; 8385 } 8386 8387 if (!map->ops->map_direct_value_addr) { 8388 verbose(env, "no direct value access support for this map type\n"); 8389 return -EACCES; 8390 } 8391 8392 err = check_map_access(env, regno, 0, 8393 map->value_size - reg->var_off.value, false, 8394 ACCESS_HELPER); 8395 if (err) 8396 return err; 8397 8398 map_off = reg->var_off.value; 8399 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8400 if (err) { 8401 verbose(env, "direct value access on string failed\n"); 8402 return err; 8403 } 8404 8405 str_ptr = (char *)(long)(map_addr); 8406 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8407 verbose(env, "string is not zero-terminated\n"); 8408 return -EINVAL; 8409 } 8410 return 0; 8411 } 8412 8413 /* Returns constant key value in `value` if possible, else negative error */ 8414 static int get_constant_map_key(struct bpf_verifier_env *env, 8415 struct bpf_reg_state *key, 8416 u32 key_size, 8417 s64 *value) 8418 { 8419 struct bpf_func_state *state = bpf_func(env, key); 8420 struct bpf_reg_state *reg; 8421 int slot, spi, off; 8422 int spill_size = 0; 8423 int zero_size = 0; 8424 int stack_off; 8425 int i, err; 8426 u8 *stype; 8427 8428 if (!env->bpf_capable) 8429 return -EOPNOTSUPP; 8430 if (key->type != PTR_TO_STACK) 8431 return -EOPNOTSUPP; 8432 if (!tnum_is_const(key->var_off)) 8433 return -EOPNOTSUPP; 8434 8435 stack_off = key->var_off.value; 8436 slot = -stack_off - 1; 8437 spi = slot / BPF_REG_SIZE; 8438 off = slot % BPF_REG_SIZE; 8439 stype = state->stack[spi].slot_type; 8440 8441 /* First handle precisely tracked STACK_ZERO */ 8442 for (i = off; i >= 0 && stype[i] == STACK_ZERO; i--) 8443 zero_size++; 8444 if (zero_size >= key_size) { 8445 *value = 0; 8446 return 0; 8447 } 8448 8449 /* Check that stack contains a scalar spill of expected size */ 8450 if (!bpf_is_spilled_scalar_reg(&state->stack[spi])) 8451 return -EOPNOTSUPP; 8452 for (i = off; i >= 0 && stype[i] == STACK_SPILL; i--) 8453 spill_size++; 8454 if (spill_size != key_size) 8455 return -EOPNOTSUPP; 8456 8457 reg = &state->stack[spi].spilled_ptr; 8458 if (!tnum_is_const(reg->var_off)) 8459 /* Stack value not statically known */ 8460 return -EOPNOTSUPP; 8461 8462 /* We are relying on a constant value. So mark as precise 8463 * to prevent pruning on it. 8464 */ 8465 bpf_bt_set_frame_slot(&env->bt, key->frameno, spi); 8466 err = mark_chain_precision_batch(env, env->cur_state); 8467 if (err < 0) 8468 return err; 8469 8470 *value = reg->var_off.value; 8471 return 0; 8472 } 8473 8474 static bool can_elide_value_nullness(enum bpf_map_type type); 8475 8476 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8477 struct bpf_call_arg_meta *meta, 8478 const struct bpf_func_proto *fn, 8479 int insn_idx) 8480 { 8481 u32 regno = BPF_REG_1 + arg; 8482 struct bpf_reg_state *reg = reg_state(env, regno); 8483 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8484 enum bpf_reg_type type = reg->type; 8485 u32 *arg_btf_id = NULL; 8486 u32 key_size; 8487 int err = 0; 8488 8489 if (arg_type == ARG_DONTCARE) 8490 return 0; 8491 8492 err = check_reg_arg(env, regno, SRC_OP); 8493 if (err) 8494 return err; 8495 8496 if (arg_type == ARG_ANYTHING) { 8497 if (is_pointer_value(env, regno)) { 8498 verbose(env, "R%d leaks addr into helper function\n", 8499 regno); 8500 return -EACCES; 8501 } 8502 return 0; 8503 } 8504 8505 if (type_is_pkt_pointer(type) && 8506 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8507 verbose(env, "helper access to the packet is not allowed\n"); 8508 return -EACCES; 8509 } 8510 8511 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8512 err = resolve_map_arg_type(env, meta, &arg_type); 8513 if (err) 8514 return err; 8515 } 8516 8517 if (bpf_register_is_null(reg) && type_may_be_null(arg_type)) 8518 /* A NULL register has a SCALAR_VALUE type, so skip 8519 * type checking. 8520 */ 8521 goto skip_type_check; 8522 8523 /* arg_btf_id and arg_size are in a union. */ 8524 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8525 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8526 arg_btf_id = fn->arg_btf_id[arg]; 8527 8528 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8529 if (err) 8530 return err; 8531 8532 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8533 if (err) 8534 return err; 8535 8536 skip_type_check: 8537 if (arg_type_is_release(arg_type)) { 8538 if (arg_type_is_dynptr(arg_type)) { 8539 struct bpf_func_state *state = bpf_func(env, reg); 8540 int spi; 8541 8542 /* Only dynptr created on stack can be released, thus 8543 * the get_spi and stack state checks for spilled_ptr 8544 * should only be done before process_dynptr_func for 8545 * PTR_TO_STACK. 8546 */ 8547 if (reg->type == PTR_TO_STACK) { 8548 spi = dynptr_get_spi(env, reg); 8549 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8550 verbose(env, "arg %d is an unacquired reference\n", regno); 8551 return -EINVAL; 8552 } 8553 } else { 8554 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8555 return -EINVAL; 8556 } 8557 } else if (!reg->ref_obj_id && !bpf_register_is_null(reg)) { 8558 verbose(env, "R%d must be referenced when passed to release function\n", 8559 regno); 8560 return -EINVAL; 8561 } 8562 if (meta->release_regno) { 8563 verifier_bug(env, "more than one release argument"); 8564 return -EFAULT; 8565 } 8566 meta->release_regno = regno; 8567 } 8568 8569 if (reg->ref_obj_id && base_type(arg_type) != ARG_KPTR_XCHG_DEST) { 8570 if (meta->ref_obj_id) { 8571 verbose(env, "more than one arg with ref_obj_id R%d %u %u", 8572 regno, reg->ref_obj_id, 8573 meta->ref_obj_id); 8574 return -EACCES; 8575 } 8576 meta->ref_obj_id = reg->ref_obj_id; 8577 } 8578 8579 switch (base_type(arg_type)) { 8580 case ARG_CONST_MAP_PTR: 8581 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8582 if (meta->map.ptr) { 8583 /* Use map_uid (which is unique id of inner map) to reject: 8584 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8585 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8586 * if (inner_map1 && inner_map2) { 8587 * timer = bpf_map_lookup_elem(inner_map1); 8588 * if (timer) 8589 * // mismatch would have been allowed 8590 * bpf_timer_init(timer, inner_map2); 8591 * } 8592 * 8593 * Comparing map_ptr is enough to distinguish normal and outer maps. 8594 */ 8595 if (meta->map.ptr != reg->map_ptr || 8596 meta->map.uid != reg->map_uid) { 8597 verbose(env, 8598 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8599 meta->map.uid, reg->map_uid); 8600 return -EINVAL; 8601 } 8602 } 8603 meta->map.ptr = reg->map_ptr; 8604 meta->map.uid = reg->map_uid; 8605 break; 8606 case ARG_PTR_TO_MAP_KEY: 8607 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8608 * check that [key, key + map->key_size) are within 8609 * stack limits and initialized 8610 */ 8611 if (!meta->map.ptr) { 8612 /* in function declaration map_ptr must come before 8613 * map_key, so that it's verified and known before 8614 * we have to check map_key here. Otherwise it means 8615 * that kernel subsystem misconfigured verifier 8616 */ 8617 verifier_bug(env, "invalid map_ptr to access map->key"); 8618 return -EFAULT; 8619 } 8620 key_size = meta->map.ptr->key_size; 8621 err = check_helper_mem_access(env, regno, key_size, BPF_READ, false, NULL); 8622 if (err) 8623 return err; 8624 if (can_elide_value_nullness(meta->map.ptr->map_type)) { 8625 err = get_constant_map_key(env, reg, key_size, &meta->const_map_key); 8626 if (err < 0) { 8627 meta->const_map_key = -1; 8628 if (err == -EOPNOTSUPP) 8629 err = 0; 8630 else 8631 return err; 8632 } 8633 } 8634 break; 8635 case ARG_PTR_TO_MAP_VALUE: 8636 if (type_may_be_null(arg_type) && bpf_register_is_null(reg)) 8637 return 0; 8638 8639 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8640 * check [value, value + map->value_size) validity 8641 */ 8642 if (!meta->map.ptr) { 8643 /* kernel subsystem misconfigured verifier */ 8644 verifier_bug(env, "invalid map_ptr to access map->value"); 8645 return -EFAULT; 8646 } 8647 meta->raw_mode = arg_type & MEM_UNINIT; 8648 err = check_helper_mem_access(env, regno, meta->map.ptr->value_size, 8649 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8650 false, meta); 8651 break; 8652 case ARG_PTR_TO_PERCPU_BTF_ID: 8653 if (!reg->btf_id) { 8654 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8655 return -EACCES; 8656 } 8657 meta->ret_btf = reg->btf; 8658 meta->ret_btf_id = reg->btf_id; 8659 break; 8660 case ARG_PTR_TO_SPIN_LOCK: 8661 if (in_rbtree_lock_required_cb(env)) { 8662 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8663 return -EACCES; 8664 } 8665 if (meta->func_id == BPF_FUNC_spin_lock) { 8666 err = process_spin_lock(env, regno, PROCESS_SPIN_LOCK); 8667 if (err) 8668 return err; 8669 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8670 err = process_spin_lock(env, regno, 0); 8671 if (err) 8672 return err; 8673 } else { 8674 verifier_bug(env, "spin lock arg on unexpected helper"); 8675 return -EFAULT; 8676 } 8677 break; 8678 case ARG_PTR_TO_TIMER: 8679 err = process_timer_helper(env, regno, meta); 8680 if (err) 8681 return err; 8682 break; 8683 case ARG_PTR_TO_FUNC: 8684 meta->subprogno = reg->subprogno; 8685 break; 8686 case ARG_PTR_TO_MEM: 8687 /* The access to this pointer is only checked when we hit the 8688 * next is_mem_size argument below. 8689 */ 8690 meta->raw_mode = arg_type & MEM_UNINIT; 8691 if (arg_type & MEM_FIXED_SIZE) { 8692 err = check_helper_mem_access(env, regno, fn->arg_size[arg], 8693 arg_type & MEM_WRITE ? BPF_WRITE : BPF_READ, 8694 false, meta); 8695 if (err) 8696 return err; 8697 if (arg_type & MEM_ALIGNED) 8698 err = check_ptr_alignment(env, reg, 0, fn->arg_size[arg], true); 8699 } 8700 break; 8701 case ARG_CONST_SIZE: 8702 err = check_mem_size_reg(env, reg, regno, 8703 fn->arg_type[arg - 1] & MEM_WRITE ? 8704 BPF_WRITE : BPF_READ, 8705 false, meta); 8706 break; 8707 case ARG_CONST_SIZE_OR_ZERO: 8708 err = check_mem_size_reg(env, reg, regno, 8709 fn->arg_type[arg - 1] & MEM_WRITE ? 8710 BPF_WRITE : BPF_READ, 8711 true, meta); 8712 break; 8713 case ARG_PTR_TO_DYNPTR: 8714 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8715 if (err) 8716 return err; 8717 break; 8718 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8719 if (!tnum_is_const(reg->var_off)) { 8720 verbose(env, "R%d is not a known constant'\n", 8721 regno); 8722 return -EACCES; 8723 } 8724 meta->mem_size = reg->var_off.value; 8725 err = mark_chain_precision(env, regno); 8726 if (err) 8727 return err; 8728 break; 8729 case ARG_PTR_TO_CONST_STR: 8730 { 8731 err = check_reg_const_str(env, reg, regno); 8732 if (err) 8733 return err; 8734 break; 8735 } 8736 case ARG_KPTR_XCHG_DEST: 8737 err = process_kptr_func(env, regno, meta); 8738 if (err) 8739 return err; 8740 break; 8741 } 8742 8743 return err; 8744 } 8745 8746 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8747 { 8748 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8749 enum bpf_prog_type type = resolve_prog_type(env->prog); 8750 8751 if (func_id != BPF_FUNC_map_update_elem && 8752 func_id != BPF_FUNC_map_delete_elem) 8753 return false; 8754 8755 /* It's not possible to get access to a locked struct sock in these 8756 * contexts, so updating is safe. 8757 */ 8758 switch (type) { 8759 case BPF_PROG_TYPE_TRACING: 8760 if (eatype == BPF_TRACE_ITER) 8761 return true; 8762 break; 8763 case BPF_PROG_TYPE_SOCK_OPS: 8764 /* map_update allowed only via dedicated helpers with event type checks */ 8765 if (func_id == BPF_FUNC_map_delete_elem) 8766 return true; 8767 break; 8768 case BPF_PROG_TYPE_SOCKET_FILTER: 8769 case BPF_PROG_TYPE_SCHED_CLS: 8770 case BPF_PROG_TYPE_SCHED_ACT: 8771 case BPF_PROG_TYPE_XDP: 8772 case BPF_PROG_TYPE_SK_REUSEPORT: 8773 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8774 case BPF_PROG_TYPE_SK_LOOKUP: 8775 return true; 8776 default: 8777 break; 8778 } 8779 8780 verbose(env, "cannot update sockmap in this context\n"); 8781 return false; 8782 } 8783 8784 bool bpf_allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8785 { 8786 return env->prog->jit_requested && 8787 bpf_jit_supports_subprog_tailcalls(); 8788 } 8789 8790 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8791 struct bpf_map *map, int func_id) 8792 { 8793 if (!map) 8794 return 0; 8795 8796 /* We need a two way check, first is from map perspective ... */ 8797 switch (map->map_type) { 8798 case BPF_MAP_TYPE_PROG_ARRAY: 8799 if (func_id != BPF_FUNC_tail_call) 8800 goto error; 8801 break; 8802 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8803 if (func_id != BPF_FUNC_perf_event_read && 8804 func_id != BPF_FUNC_perf_event_output && 8805 func_id != BPF_FUNC_skb_output && 8806 func_id != BPF_FUNC_perf_event_read_value && 8807 func_id != BPF_FUNC_xdp_output) 8808 goto error; 8809 break; 8810 case BPF_MAP_TYPE_RINGBUF: 8811 if (func_id != BPF_FUNC_ringbuf_output && 8812 func_id != BPF_FUNC_ringbuf_reserve && 8813 func_id != BPF_FUNC_ringbuf_query && 8814 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8815 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8816 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8817 goto error; 8818 break; 8819 case BPF_MAP_TYPE_USER_RINGBUF: 8820 if (func_id != BPF_FUNC_user_ringbuf_drain) 8821 goto error; 8822 break; 8823 case BPF_MAP_TYPE_STACK_TRACE: 8824 if (func_id != BPF_FUNC_get_stackid) 8825 goto error; 8826 break; 8827 case BPF_MAP_TYPE_CGROUP_ARRAY: 8828 if (func_id != BPF_FUNC_skb_under_cgroup && 8829 func_id != BPF_FUNC_current_task_under_cgroup) 8830 goto error; 8831 break; 8832 case BPF_MAP_TYPE_CGROUP_STORAGE: 8833 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8834 if (func_id != BPF_FUNC_get_local_storage) 8835 goto error; 8836 break; 8837 case BPF_MAP_TYPE_DEVMAP: 8838 case BPF_MAP_TYPE_DEVMAP_HASH: 8839 if (func_id != BPF_FUNC_redirect_map && 8840 func_id != BPF_FUNC_map_lookup_elem) 8841 goto error; 8842 break; 8843 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8844 * appear. 8845 */ 8846 case BPF_MAP_TYPE_CPUMAP: 8847 if (func_id != BPF_FUNC_redirect_map) 8848 goto error; 8849 break; 8850 case BPF_MAP_TYPE_XSKMAP: 8851 if (func_id != BPF_FUNC_redirect_map && 8852 func_id != BPF_FUNC_map_lookup_elem) 8853 goto error; 8854 break; 8855 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8856 case BPF_MAP_TYPE_HASH_OF_MAPS: 8857 if (func_id != BPF_FUNC_map_lookup_elem) 8858 goto error; 8859 break; 8860 case BPF_MAP_TYPE_SOCKMAP: 8861 if (func_id != BPF_FUNC_sk_redirect_map && 8862 func_id != BPF_FUNC_sock_map_update && 8863 func_id != BPF_FUNC_msg_redirect_map && 8864 func_id != BPF_FUNC_sk_select_reuseport && 8865 func_id != BPF_FUNC_map_lookup_elem && 8866 !may_update_sockmap(env, func_id)) 8867 goto error; 8868 break; 8869 case BPF_MAP_TYPE_SOCKHASH: 8870 if (func_id != BPF_FUNC_sk_redirect_hash && 8871 func_id != BPF_FUNC_sock_hash_update && 8872 func_id != BPF_FUNC_msg_redirect_hash && 8873 func_id != BPF_FUNC_sk_select_reuseport && 8874 func_id != BPF_FUNC_map_lookup_elem && 8875 !may_update_sockmap(env, func_id)) 8876 goto error; 8877 break; 8878 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8879 if (func_id != BPF_FUNC_sk_select_reuseport) 8880 goto error; 8881 break; 8882 case BPF_MAP_TYPE_QUEUE: 8883 case BPF_MAP_TYPE_STACK: 8884 if (func_id != BPF_FUNC_map_peek_elem && 8885 func_id != BPF_FUNC_map_pop_elem && 8886 func_id != BPF_FUNC_map_push_elem) 8887 goto error; 8888 break; 8889 case BPF_MAP_TYPE_SK_STORAGE: 8890 if (func_id != BPF_FUNC_sk_storage_get && 8891 func_id != BPF_FUNC_sk_storage_delete && 8892 func_id != BPF_FUNC_kptr_xchg) 8893 goto error; 8894 break; 8895 case BPF_MAP_TYPE_INODE_STORAGE: 8896 if (func_id != BPF_FUNC_inode_storage_get && 8897 func_id != BPF_FUNC_inode_storage_delete && 8898 func_id != BPF_FUNC_kptr_xchg) 8899 goto error; 8900 break; 8901 case BPF_MAP_TYPE_TASK_STORAGE: 8902 if (func_id != BPF_FUNC_task_storage_get && 8903 func_id != BPF_FUNC_task_storage_delete && 8904 func_id != BPF_FUNC_kptr_xchg) 8905 goto error; 8906 break; 8907 case BPF_MAP_TYPE_CGRP_STORAGE: 8908 if (func_id != BPF_FUNC_cgrp_storage_get && 8909 func_id != BPF_FUNC_cgrp_storage_delete && 8910 func_id != BPF_FUNC_kptr_xchg) 8911 goto error; 8912 break; 8913 case BPF_MAP_TYPE_BLOOM_FILTER: 8914 if (func_id != BPF_FUNC_map_peek_elem && 8915 func_id != BPF_FUNC_map_push_elem) 8916 goto error; 8917 break; 8918 case BPF_MAP_TYPE_INSN_ARRAY: 8919 goto error; 8920 default: 8921 break; 8922 } 8923 8924 /* ... and second from the function itself. */ 8925 switch (func_id) { 8926 case BPF_FUNC_tail_call: 8927 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8928 goto error; 8929 if (env->subprog_cnt > 1 && !bpf_allow_tail_call_in_subprogs(env)) { 8930 verbose(env, "mixing of tail_calls and bpf-to-bpf calls is not supported\n"); 8931 return -EINVAL; 8932 } 8933 break; 8934 case BPF_FUNC_perf_event_read: 8935 case BPF_FUNC_perf_event_output: 8936 case BPF_FUNC_perf_event_read_value: 8937 case BPF_FUNC_skb_output: 8938 case BPF_FUNC_xdp_output: 8939 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8940 goto error; 8941 break; 8942 case BPF_FUNC_ringbuf_output: 8943 case BPF_FUNC_ringbuf_reserve: 8944 case BPF_FUNC_ringbuf_query: 8945 case BPF_FUNC_ringbuf_reserve_dynptr: 8946 case BPF_FUNC_ringbuf_submit_dynptr: 8947 case BPF_FUNC_ringbuf_discard_dynptr: 8948 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8949 goto error; 8950 break; 8951 case BPF_FUNC_user_ringbuf_drain: 8952 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8953 goto error; 8954 break; 8955 case BPF_FUNC_get_stackid: 8956 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8957 goto error; 8958 break; 8959 case BPF_FUNC_current_task_under_cgroup: 8960 case BPF_FUNC_skb_under_cgroup: 8961 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8962 goto error; 8963 break; 8964 case BPF_FUNC_redirect_map: 8965 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8966 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8967 map->map_type != BPF_MAP_TYPE_CPUMAP && 8968 map->map_type != BPF_MAP_TYPE_XSKMAP) 8969 goto error; 8970 break; 8971 case BPF_FUNC_sk_redirect_map: 8972 case BPF_FUNC_msg_redirect_map: 8973 case BPF_FUNC_sock_map_update: 8974 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8975 goto error; 8976 break; 8977 case BPF_FUNC_sk_redirect_hash: 8978 case BPF_FUNC_msg_redirect_hash: 8979 case BPF_FUNC_sock_hash_update: 8980 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8981 goto error; 8982 break; 8983 case BPF_FUNC_get_local_storage: 8984 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8985 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8986 goto error; 8987 break; 8988 case BPF_FUNC_sk_select_reuseport: 8989 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8990 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8991 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8992 goto error; 8993 break; 8994 case BPF_FUNC_map_pop_elem: 8995 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8996 map->map_type != BPF_MAP_TYPE_STACK) 8997 goto error; 8998 break; 8999 case BPF_FUNC_map_peek_elem: 9000 case BPF_FUNC_map_push_elem: 9001 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9002 map->map_type != BPF_MAP_TYPE_STACK && 9003 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9004 goto error; 9005 break; 9006 case BPF_FUNC_map_lookup_percpu_elem: 9007 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9008 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9009 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9010 goto error; 9011 break; 9012 case BPF_FUNC_sk_storage_get: 9013 case BPF_FUNC_sk_storage_delete: 9014 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9015 goto error; 9016 break; 9017 case BPF_FUNC_inode_storage_get: 9018 case BPF_FUNC_inode_storage_delete: 9019 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9020 goto error; 9021 break; 9022 case BPF_FUNC_task_storage_get: 9023 case BPF_FUNC_task_storage_delete: 9024 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9025 goto error; 9026 break; 9027 case BPF_FUNC_cgrp_storage_get: 9028 case BPF_FUNC_cgrp_storage_delete: 9029 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9030 goto error; 9031 break; 9032 default: 9033 break; 9034 } 9035 9036 return 0; 9037 error: 9038 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9039 map->map_type, func_id_name(func_id), func_id); 9040 return -EINVAL; 9041 } 9042 9043 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9044 { 9045 int count = 0; 9046 9047 if (arg_type_is_raw_mem(fn->arg1_type)) 9048 count++; 9049 if (arg_type_is_raw_mem(fn->arg2_type)) 9050 count++; 9051 if (arg_type_is_raw_mem(fn->arg3_type)) 9052 count++; 9053 if (arg_type_is_raw_mem(fn->arg4_type)) 9054 count++; 9055 if (arg_type_is_raw_mem(fn->arg5_type)) 9056 count++; 9057 9058 /* We only support one arg being in raw mode at the moment, 9059 * which is sufficient for the helper functions we have 9060 * right now. 9061 */ 9062 return count <= 1; 9063 } 9064 9065 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9066 { 9067 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9068 bool has_size = fn->arg_size[arg] != 0; 9069 bool is_next_size = false; 9070 9071 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9072 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9073 9074 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9075 return is_next_size; 9076 9077 return has_size == is_next_size || is_next_size == is_fixed; 9078 } 9079 9080 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9081 { 9082 /* bpf_xxx(..., buf, len) call will access 'len' 9083 * bytes from memory 'buf'. Both arg types need 9084 * to be paired, so make sure there's no buggy 9085 * helper function specification. 9086 */ 9087 if (arg_type_is_mem_size(fn->arg1_type) || 9088 check_args_pair_invalid(fn, 0) || 9089 check_args_pair_invalid(fn, 1) || 9090 check_args_pair_invalid(fn, 2) || 9091 check_args_pair_invalid(fn, 3) || 9092 check_args_pair_invalid(fn, 4)) 9093 return false; 9094 9095 return true; 9096 } 9097 9098 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9099 { 9100 int i; 9101 9102 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9103 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9104 return !!fn->arg_btf_id[i]; 9105 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9106 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9107 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9108 /* arg_btf_id and arg_size are in a union. */ 9109 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9110 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9111 return false; 9112 } 9113 9114 return true; 9115 } 9116 9117 static bool check_mem_arg_rw_flag_ok(const struct bpf_func_proto *fn) 9118 { 9119 int i; 9120 9121 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9122 enum bpf_arg_type arg_type = fn->arg_type[i]; 9123 9124 if (base_type(arg_type) != ARG_PTR_TO_MEM) 9125 continue; 9126 if (!(arg_type & (MEM_WRITE | MEM_RDONLY))) 9127 return false; 9128 } 9129 9130 return true; 9131 } 9132 9133 static int check_func_proto(const struct bpf_func_proto *fn) 9134 { 9135 return check_raw_mode_ok(fn) && 9136 check_arg_pair_ok(fn) && 9137 check_mem_arg_rw_flag_ok(fn) && 9138 check_btf_id_ok(fn) ? 0 : -EINVAL; 9139 } 9140 9141 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9142 * are now invalid, so turn them into unknown SCALAR_VALUE. 9143 * 9144 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9145 * since these slices point to packet data. 9146 */ 9147 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9148 { 9149 struct bpf_func_state *state; 9150 struct bpf_reg_state *reg; 9151 9152 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9153 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9154 mark_reg_invalid(env, reg); 9155 })); 9156 } 9157 9158 enum { 9159 AT_PKT_END = -1, 9160 BEYOND_PKT_END = -2, 9161 }; 9162 9163 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9164 { 9165 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9166 struct bpf_reg_state *reg = &state->regs[regn]; 9167 9168 if (reg->type != PTR_TO_PACKET) 9169 /* PTR_TO_PACKET_META is not supported yet */ 9170 return; 9171 9172 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9173 * How far beyond pkt_end it goes is unknown. 9174 * if (!range_open) it's the case of pkt >= pkt_end 9175 * if (range_open) it's the case of pkt > pkt_end 9176 * hence this pointer is at least 1 byte bigger than pkt_end 9177 */ 9178 if (range_open) 9179 reg->range = BEYOND_PKT_END; 9180 else 9181 reg->range = AT_PKT_END; 9182 } 9183 9184 static int release_reference_nomark(struct bpf_verifier_state *state, int ref_obj_id) 9185 { 9186 int i; 9187 9188 for (i = 0; i < state->acquired_refs; i++) { 9189 if (state->refs[i].type != REF_TYPE_PTR) 9190 continue; 9191 if (state->refs[i].id == ref_obj_id) { 9192 release_reference_state(state, i); 9193 return 0; 9194 } 9195 } 9196 return -EINVAL; 9197 } 9198 9199 /* The pointer with the specified id has released its reference to kernel 9200 * resources. Identify all copies of the same pointer and clear the reference. 9201 * 9202 * This is the release function corresponding to acquire_reference(). Idempotent. 9203 */ 9204 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id) 9205 { 9206 struct bpf_verifier_state *vstate = env->cur_state; 9207 struct bpf_func_state *state; 9208 struct bpf_reg_state *reg; 9209 int err; 9210 9211 err = release_reference_nomark(vstate, ref_obj_id); 9212 if (err) 9213 return err; 9214 9215 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 9216 if (reg->ref_obj_id == ref_obj_id) 9217 mark_reg_invalid(env, reg); 9218 })); 9219 9220 return 0; 9221 } 9222 9223 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9224 { 9225 struct bpf_func_state *unused; 9226 struct bpf_reg_state *reg; 9227 9228 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9229 if (type_is_non_owning_ref(reg->type)) 9230 mark_reg_invalid(env, reg); 9231 })); 9232 } 9233 9234 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9235 struct bpf_reg_state *regs) 9236 { 9237 int i; 9238 9239 /* after the call registers r0 - r5 were scratched */ 9240 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9241 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 9242 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9243 } 9244 } 9245 9246 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9247 struct bpf_func_state *caller, 9248 struct bpf_func_state *callee, 9249 int insn_idx); 9250 9251 static int set_callee_state(struct bpf_verifier_env *env, 9252 struct bpf_func_state *caller, 9253 struct bpf_func_state *callee, int insn_idx); 9254 9255 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9256 set_callee_state_fn set_callee_state_cb, 9257 struct bpf_verifier_state *state) 9258 { 9259 struct bpf_func_state *caller, *callee; 9260 int err; 9261 9262 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9263 verbose(env, "the call stack of %d frames is too deep\n", 9264 state->curframe + 2); 9265 return -E2BIG; 9266 } 9267 9268 if (state->frame[state->curframe + 1]) { 9269 verifier_bug(env, "Frame %d already allocated", state->curframe + 1); 9270 return -EFAULT; 9271 } 9272 9273 caller = state->frame[state->curframe]; 9274 callee = kzalloc_obj(*callee, GFP_KERNEL_ACCOUNT); 9275 if (!callee) 9276 return -ENOMEM; 9277 state->frame[state->curframe + 1] = callee; 9278 9279 /* callee cannot access r0, r6 - r9 for reading and has to write 9280 * into its own stack before reading from it. 9281 * callee can read/write into caller's stack 9282 */ 9283 init_func_state(env, callee, 9284 /* remember the callsite, it will be used by bpf_exit */ 9285 callsite, 9286 state->curframe + 1 /* frameno within this callchain */, 9287 subprog /* subprog number within this prog */); 9288 err = set_callee_state_cb(env, caller, callee, callsite); 9289 if (err) 9290 goto err_out; 9291 9292 /* only increment it after check_reg_arg() finished */ 9293 state->curframe++; 9294 9295 return 0; 9296 9297 err_out: 9298 free_func_state(callee); 9299 state->frame[state->curframe + 1] = NULL; 9300 return err; 9301 } 9302 9303 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9304 const struct btf *btf, 9305 struct bpf_reg_state *regs) 9306 { 9307 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9308 struct bpf_verifier_log *log = &env->log; 9309 u32 i; 9310 int ret; 9311 9312 ret = btf_prepare_func_args(env, subprog); 9313 if (ret) 9314 return ret; 9315 9316 /* check that BTF function arguments match actual types that the 9317 * verifier sees. 9318 */ 9319 for (i = 0; i < sub->arg_cnt; i++) { 9320 u32 regno = i + 1; 9321 struct bpf_reg_state *reg = ®s[regno]; 9322 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9323 9324 if (arg->arg_type == ARG_ANYTHING) { 9325 if (reg->type != SCALAR_VALUE) { 9326 bpf_log(log, "R%d is not a scalar\n", regno); 9327 return -EINVAL; 9328 } 9329 } else if (arg->arg_type & PTR_UNTRUSTED) { 9330 /* 9331 * Anything is allowed for untrusted arguments, as these are 9332 * read-only and probe read instructions would protect against 9333 * invalid memory access. 9334 */ 9335 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9336 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_CTX); 9337 if (ret < 0) 9338 return ret; 9339 /* If function expects ctx type in BTF check that caller 9340 * is passing PTR_TO_CTX. 9341 */ 9342 if (reg->type != PTR_TO_CTX) { 9343 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9344 return -EINVAL; 9345 } 9346 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9347 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9348 if (ret < 0) 9349 return ret; 9350 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9351 return -EINVAL; 9352 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9353 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9354 return -EINVAL; 9355 } 9356 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9357 /* 9358 * Can pass any value and the kernel won't crash, but 9359 * only PTR_TO_ARENA or SCALAR make sense. Everything 9360 * else is a bug in the bpf program. Point it out to 9361 * the user at the verification time instead of 9362 * run-time debug nightmare. 9363 */ 9364 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9365 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 9366 return -EINVAL; 9367 } 9368 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9369 ret = check_func_arg_reg_off(env, reg, regno, ARG_PTR_TO_DYNPTR); 9370 if (ret) 9371 return ret; 9372 9373 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9374 if (ret) 9375 return ret; 9376 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9377 struct bpf_call_arg_meta meta; 9378 int err; 9379 9380 if (bpf_register_is_null(reg) && type_may_be_null(arg->arg_type)) 9381 continue; 9382 9383 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9384 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 9385 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 9386 if (err) 9387 return err; 9388 } else { 9389 verifier_bug(env, "unrecognized arg#%d type %d", i, arg->arg_type); 9390 return -EFAULT; 9391 } 9392 } 9393 9394 return 0; 9395 } 9396 9397 /* Compare BTF of a function call with given bpf_reg_state. 9398 * Returns: 9399 * EFAULT - there is a verifier bug. Abort verification. 9400 * EINVAL - there is a type mismatch or BTF is not available. 9401 * 0 - BTF matches with what bpf_reg_state expects. 9402 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9403 */ 9404 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9405 struct bpf_reg_state *regs) 9406 { 9407 struct bpf_prog *prog = env->prog; 9408 struct btf *btf = prog->aux->btf; 9409 u32 btf_id; 9410 int err; 9411 9412 if (!prog->aux->func_info) 9413 return -EINVAL; 9414 9415 btf_id = prog->aux->func_info[subprog].type_id; 9416 if (!btf_id) 9417 return -EFAULT; 9418 9419 if (prog->aux->func_info_aux[subprog].unreliable) 9420 return -EINVAL; 9421 9422 err = btf_check_func_arg_match(env, subprog, btf, regs); 9423 /* Compiler optimizations can remove arguments from static functions 9424 * or mismatched type can be passed into a global function. 9425 * In such cases mark the function as unreliable from BTF point of view. 9426 */ 9427 if (err) 9428 prog->aux->func_info_aux[subprog].unreliable = true; 9429 return err; 9430 } 9431 9432 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9433 int insn_idx, int subprog, 9434 set_callee_state_fn set_callee_state_cb) 9435 { 9436 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9437 struct bpf_func_state *caller, *callee; 9438 int err; 9439 9440 caller = state->frame[state->curframe]; 9441 err = btf_check_subprog_call(env, subprog, caller->regs); 9442 if (err == -EFAULT) 9443 return err; 9444 9445 /* set_callee_state is used for direct subprog calls, but we are 9446 * interested in validating only BPF helpers that can call subprogs as 9447 * callbacks 9448 */ 9449 env->subprog_info[subprog].is_cb = true; 9450 if (bpf_pseudo_kfunc_call(insn) && 9451 !is_callback_calling_kfunc(insn->imm)) { 9452 verifier_bug(env, "kfunc %s#%d not marked as callback-calling", 9453 func_id_name(insn->imm), insn->imm); 9454 return -EFAULT; 9455 } else if (!bpf_pseudo_kfunc_call(insn) && 9456 !is_callback_calling_function(insn->imm)) { /* helper */ 9457 verifier_bug(env, "helper %s#%d not marked as callback-calling", 9458 func_id_name(insn->imm), insn->imm); 9459 return -EFAULT; 9460 } 9461 9462 if (bpf_is_async_callback_calling_insn(insn)) { 9463 struct bpf_verifier_state *async_cb; 9464 9465 /* there is no real recursion here. timer and workqueue callbacks are async */ 9466 env->subprog_info[subprog].is_async_cb = true; 9467 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9468 insn_idx, subprog, 9469 is_async_cb_sleepable(env, insn)); 9470 if (IS_ERR(async_cb)) 9471 return PTR_ERR(async_cb); 9472 callee = async_cb->frame[0]; 9473 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9474 9475 /* Convert bpf_timer_set_callback() args into timer callback args */ 9476 err = set_callee_state_cb(env, caller, callee, insn_idx); 9477 if (err) 9478 return err; 9479 9480 return 0; 9481 } 9482 9483 /* for callback functions enqueue entry to callback and 9484 * proceed with next instruction within current frame. 9485 */ 9486 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9487 if (IS_ERR(callback_state)) 9488 return PTR_ERR(callback_state); 9489 9490 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9491 callback_state); 9492 if (err) 9493 return err; 9494 9495 callback_state->callback_unroll_depth++; 9496 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9497 caller->callback_depth = 0; 9498 return 0; 9499 } 9500 9501 static int process_bpf_exit_full(struct bpf_verifier_env *env, 9502 bool *do_print_state, bool exception_exit); 9503 9504 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9505 int *insn_idx) 9506 { 9507 struct bpf_verifier_state *state = env->cur_state; 9508 struct bpf_func_state *caller; 9509 int err, subprog, target_insn; 9510 9511 target_insn = *insn_idx + insn->imm + 1; 9512 subprog = bpf_find_subprog(env, target_insn); 9513 if (verifier_bug_if(subprog < 0, env, "target of func call at insn %d is not a program", 9514 target_insn)) 9515 return -EFAULT; 9516 9517 caller = state->frame[state->curframe]; 9518 err = btf_check_subprog_call(env, subprog, caller->regs); 9519 if (err == -EFAULT) 9520 return err; 9521 if (bpf_subprog_is_global(env, subprog)) { 9522 const char *sub_name = subprog_name(env, subprog); 9523 9524 if (env->cur_state->active_locks) { 9525 verbose(env, "global function calls are not allowed while holding a lock,\n" 9526 "use static function instead\n"); 9527 return -EINVAL; 9528 } 9529 9530 if (env->subprog_info[subprog].might_sleep && !in_sleepable_context(env)) { 9531 verbose(env, "sleepable global function %s() called in %s\n", 9532 sub_name, non_sleepable_context_description(env)); 9533 return -EINVAL; 9534 } 9535 9536 if (err) { 9537 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9538 subprog, sub_name); 9539 return err; 9540 } 9541 9542 if (env->log.level & BPF_LOG_LEVEL) 9543 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9544 subprog, sub_name); 9545 if (env->subprog_info[subprog].changes_pkt_data) 9546 clear_all_pkt_pointers(env); 9547 /* mark global subprog for verifying after main prog */ 9548 subprog_aux(env, subprog)->called = true; 9549 clear_caller_saved_regs(env, caller->regs); 9550 9551 /* All non-void global functions return a 64-bit SCALAR_VALUE. */ 9552 if (!subprog_returns_void(env, subprog)) { 9553 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9554 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9555 } 9556 9557 if (env->subprog_info[subprog].might_throw) { 9558 struct bpf_verifier_state *branch; 9559 9560 branch = push_stack(env, *insn_idx + 1, *insn_idx, false); 9561 if (IS_ERR(branch)) { 9562 verbose(env, "failed to push state for global subprog exception path\n"); 9563 return PTR_ERR(branch); 9564 } 9565 return process_bpf_exit_full(env, NULL, true); 9566 } 9567 9568 /* continue with next insn after call */ 9569 return 0; 9570 } 9571 9572 /* for regular function entry setup new frame and continue 9573 * from that frame. 9574 */ 9575 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9576 if (err) 9577 return err; 9578 9579 clear_caller_saved_regs(env, caller->regs); 9580 9581 /* and go analyze first insn of the callee */ 9582 *insn_idx = env->subprog_info[subprog].start - 1; 9583 9584 if (env->log.level & BPF_LOG_LEVEL) { 9585 verbose(env, "caller:\n"); 9586 print_verifier_state(env, state, caller->frameno, true); 9587 verbose(env, "callee:\n"); 9588 print_verifier_state(env, state, state->curframe, true); 9589 } 9590 9591 return 0; 9592 } 9593 9594 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9595 struct bpf_func_state *caller, 9596 struct bpf_func_state *callee) 9597 { 9598 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9599 * void *callback_ctx, u64 flags); 9600 * callback_fn(struct bpf_map *map, void *key, void *value, 9601 * void *callback_ctx); 9602 */ 9603 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9604 9605 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9606 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9607 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9608 9609 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9610 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9611 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9612 9613 /* pointer to stack or null */ 9614 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9615 9616 /* unused */ 9617 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9618 return 0; 9619 } 9620 9621 static int set_callee_state(struct bpf_verifier_env *env, 9622 struct bpf_func_state *caller, 9623 struct bpf_func_state *callee, int insn_idx) 9624 { 9625 int i; 9626 9627 /* copy r1 - r5 args that callee can access. The copy includes parent 9628 * pointers, which connects us up to the liveness chain 9629 */ 9630 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9631 callee->regs[i] = caller->regs[i]; 9632 return 0; 9633 } 9634 9635 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9636 struct bpf_func_state *caller, 9637 struct bpf_func_state *callee, 9638 int insn_idx) 9639 { 9640 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9641 struct bpf_map *map; 9642 int err; 9643 9644 /* valid map_ptr and poison value does not matter */ 9645 map = insn_aux->map_ptr_state.map_ptr; 9646 if (!map->ops->map_set_for_each_callback_args || 9647 !map->ops->map_for_each_callback) { 9648 verbose(env, "callback function not allowed for map\n"); 9649 return -ENOTSUPP; 9650 } 9651 9652 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9653 if (err) 9654 return err; 9655 9656 callee->in_callback_fn = true; 9657 callee->callback_ret_range = retval_range(0, 1); 9658 return 0; 9659 } 9660 9661 static int set_loop_callback_state(struct bpf_verifier_env *env, 9662 struct bpf_func_state *caller, 9663 struct bpf_func_state *callee, 9664 int insn_idx) 9665 { 9666 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9667 * u64 flags); 9668 * callback_fn(u64 index, void *callback_ctx); 9669 */ 9670 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9671 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9672 9673 /* unused */ 9674 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9675 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9676 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9677 9678 callee->in_callback_fn = true; 9679 callee->callback_ret_range = retval_range(0, 1); 9680 return 0; 9681 } 9682 9683 static int set_timer_callback_state(struct bpf_verifier_env *env, 9684 struct bpf_func_state *caller, 9685 struct bpf_func_state *callee, 9686 int insn_idx) 9687 { 9688 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9689 9690 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9691 * callback_fn(struct bpf_map *map, void *key, void *value); 9692 */ 9693 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9694 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9695 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9696 9697 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9698 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9699 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9700 9701 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9702 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9703 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9704 9705 /* unused */ 9706 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9707 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9708 callee->in_async_callback_fn = true; 9709 callee->callback_ret_range = retval_range(0, 0); 9710 return 0; 9711 } 9712 9713 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9714 struct bpf_func_state *caller, 9715 struct bpf_func_state *callee, 9716 int insn_idx) 9717 { 9718 /* bpf_find_vma(struct task_struct *task, u64 addr, 9719 * void *callback_fn, void *callback_ctx, u64 flags) 9720 * (callback_fn)(struct task_struct *task, 9721 * struct vm_area_struct *vma, void *callback_ctx); 9722 */ 9723 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9724 9725 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9726 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9727 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9728 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9729 9730 /* pointer to stack or null */ 9731 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9732 9733 /* unused */ 9734 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9735 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9736 callee->in_callback_fn = true; 9737 callee->callback_ret_range = retval_range(0, 1); 9738 return 0; 9739 } 9740 9741 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9742 struct bpf_func_state *caller, 9743 struct bpf_func_state *callee, 9744 int insn_idx) 9745 { 9746 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9747 * callback_ctx, u64 flags); 9748 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9749 */ 9750 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9751 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9752 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9753 9754 /* unused */ 9755 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9756 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9757 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9758 9759 callee->in_callback_fn = true; 9760 callee->callback_ret_range = retval_range(0, 1); 9761 return 0; 9762 } 9763 9764 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9765 struct bpf_func_state *caller, 9766 struct bpf_func_state *callee, 9767 int insn_idx) 9768 { 9769 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9770 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9771 * 9772 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9773 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9774 * by this point, so look at 'root' 9775 */ 9776 struct btf_field *field; 9777 9778 field = reg_find_field_offset(&caller->regs[BPF_REG_1], 9779 caller->regs[BPF_REG_1].var_off.value, 9780 BPF_RB_ROOT); 9781 if (!field || !field->graph_root.value_btf_id) 9782 return -EFAULT; 9783 9784 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9785 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9786 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9787 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9788 9789 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9790 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9791 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9792 callee->in_callback_fn = true; 9793 callee->callback_ret_range = retval_range(0, 1); 9794 return 0; 9795 } 9796 9797 static int set_task_work_schedule_callback_state(struct bpf_verifier_env *env, 9798 struct bpf_func_state *caller, 9799 struct bpf_func_state *callee, 9800 int insn_idx) 9801 { 9802 struct bpf_map *map_ptr = caller->regs[BPF_REG_3].map_ptr; 9803 9804 /* 9805 * callback_fn(struct bpf_map *map, void *key, void *value); 9806 */ 9807 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9808 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9809 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9810 9811 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9812 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9813 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9814 9815 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9816 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9817 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9818 9819 /* unused */ 9820 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9821 bpf_mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9822 callee->in_async_callback_fn = true; 9823 callee->callback_ret_range = retval_range(S32_MIN, S32_MAX); 9824 return 0; 9825 } 9826 9827 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9828 9829 /* Are we currently verifying the callback for a rbtree helper that must 9830 * be called with lock held? If so, no need to complain about unreleased 9831 * lock 9832 */ 9833 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9834 { 9835 struct bpf_verifier_state *state = env->cur_state; 9836 struct bpf_insn *insn = env->prog->insnsi; 9837 struct bpf_func_state *callee; 9838 int kfunc_btf_id; 9839 9840 if (!state->curframe) 9841 return false; 9842 9843 callee = state->frame[state->curframe]; 9844 9845 if (!callee->in_callback_fn) 9846 return false; 9847 9848 kfunc_btf_id = insn[callee->callsite].imm; 9849 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9850 } 9851 9852 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9853 { 9854 if (range.return_32bit) 9855 return range.minval <= reg->s32_min_value && reg->s32_max_value <= range.maxval; 9856 else 9857 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 9858 } 9859 9860 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9861 { 9862 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9863 struct bpf_func_state *caller, *callee; 9864 struct bpf_reg_state *r0; 9865 bool in_callback_fn; 9866 int err; 9867 9868 callee = state->frame[state->curframe]; 9869 r0 = &callee->regs[BPF_REG_0]; 9870 if (r0->type == PTR_TO_STACK) { 9871 /* technically it's ok to return caller's stack pointer 9872 * (or caller's caller's pointer) back to the caller, 9873 * since these pointers are valid. Only current stack 9874 * pointer will be invalid as soon as function exits, 9875 * but let's be conservative 9876 */ 9877 verbose(env, "cannot return stack pointer to the caller\n"); 9878 return -EINVAL; 9879 } 9880 9881 caller = state->frame[state->curframe - 1]; 9882 if (callee->in_callback_fn) { 9883 if (r0->type != SCALAR_VALUE) { 9884 verbose(env, "R0 not a scalar value\n"); 9885 return -EACCES; 9886 } 9887 9888 /* we are going to rely on register's precise value */ 9889 err = mark_chain_precision(env, BPF_REG_0); 9890 if (err) 9891 return err; 9892 9893 /* enforce R0 return value range, and bpf_callback_t returns 64bit */ 9894 if (!retval_range_within(callee->callback_ret_range, r0)) { 9895 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9896 "At callback return", "R0"); 9897 return -EINVAL; 9898 } 9899 if (!bpf_calls_callback(env, callee->callsite)) { 9900 verifier_bug(env, "in callback at %d, callsite %d !calls_callback", 9901 *insn_idx, callee->callsite); 9902 return -EFAULT; 9903 } 9904 } else { 9905 /* return to the caller whatever r0 had in the callee */ 9906 caller->regs[BPF_REG_0] = *r0; 9907 } 9908 9909 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9910 * there function call logic would reschedule callback visit. If iteration 9911 * converges is_state_visited() would prune that visit eventually. 9912 */ 9913 in_callback_fn = callee->in_callback_fn; 9914 if (in_callback_fn) 9915 *insn_idx = callee->callsite; 9916 else 9917 *insn_idx = callee->callsite + 1; 9918 9919 if (env->log.level & BPF_LOG_LEVEL) { 9920 verbose(env, "returning from callee:\n"); 9921 print_verifier_state(env, state, callee->frameno, true); 9922 verbose(env, "to caller at %d:\n", *insn_idx); 9923 print_verifier_state(env, state, caller->frameno, true); 9924 } 9925 /* clear everything in the callee. In case of exceptional exits using 9926 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9927 free_func_state(callee); 9928 state->frame[state->curframe--] = NULL; 9929 9930 /* for callbacks widen imprecise scalars to make programs like below verify: 9931 * 9932 * struct ctx { int i; } 9933 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9934 * ... 9935 * struct ctx = { .i = 0; } 9936 * bpf_loop(100, cb, &ctx, 0); 9937 * 9938 * This is similar to what is done in process_iter_next_call() for open 9939 * coded iterators. 9940 */ 9941 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9942 if (prev_st) { 9943 err = widen_imprecise_scalars(env, prev_st, state); 9944 if (err) 9945 return err; 9946 } 9947 return 0; 9948 } 9949 9950 static int do_refine_retval_range(struct bpf_verifier_env *env, 9951 struct bpf_reg_state *regs, int ret_type, 9952 int func_id, 9953 struct bpf_call_arg_meta *meta) 9954 { 9955 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9956 9957 if (ret_type != RET_INTEGER) 9958 return 0; 9959 9960 switch (func_id) { 9961 case BPF_FUNC_get_stack: 9962 case BPF_FUNC_get_task_stack: 9963 case BPF_FUNC_probe_read_str: 9964 case BPF_FUNC_probe_read_kernel_str: 9965 case BPF_FUNC_probe_read_user_str: 9966 ret_reg->smax_value = meta->msize_max_value; 9967 ret_reg->s32_max_value = meta->msize_max_value; 9968 ret_reg->smin_value = -MAX_ERRNO; 9969 ret_reg->s32_min_value = -MAX_ERRNO; 9970 reg_bounds_sync(ret_reg); 9971 break; 9972 case BPF_FUNC_get_smp_processor_id: 9973 ret_reg->umax_value = nr_cpu_ids - 1; 9974 ret_reg->u32_max_value = nr_cpu_ids - 1; 9975 ret_reg->smax_value = nr_cpu_ids - 1; 9976 ret_reg->s32_max_value = nr_cpu_ids - 1; 9977 ret_reg->umin_value = 0; 9978 ret_reg->u32_min_value = 0; 9979 ret_reg->smin_value = 0; 9980 ret_reg->s32_min_value = 0; 9981 reg_bounds_sync(ret_reg); 9982 break; 9983 } 9984 9985 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9986 } 9987 9988 static int 9989 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9990 int func_id, int insn_idx) 9991 { 9992 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9993 struct bpf_map *map = meta->map.ptr; 9994 9995 if (func_id != BPF_FUNC_tail_call && 9996 func_id != BPF_FUNC_map_lookup_elem && 9997 func_id != BPF_FUNC_map_update_elem && 9998 func_id != BPF_FUNC_map_delete_elem && 9999 func_id != BPF_FUNC_map_push_elem && 10000 func_id != BPF_FUNC_map_pop_elem && 10001 func_id != BPF_FUNC_map_peek_elem && 10002 func_id != BPF_FUNC_for_each_map_elem && 10003 func_id != BPF_FUNC_redirect_map && 10004 func_id != BPF_FUNC_map_lookup_percpu_elem) 10005 return 0; 10006 10007 if (map == NULL) { 10008 verifier_bug(env, "expected map for helper call"); 10009 return -EFAULT; 10010 } 10011 10012 /* In case of read-only, some additional restrictions 10013 * need to be applied in order to prevent altering the 10014 * state of the map from program side. 10015 */ 10016 if ((map->map_flags & BPF_F_RDONLY_PROG) && 10017 (func_id == BPF_FUNC_map_delete_elem || 10018 func_id == BPF_FUNC_map_update_elem || 10019 func_id == BPF_FUNC_map_push_elem || 10020 func_id == BPF_FUNC_map_pop_elem)) { 10021 verbose(env, "write into map forbidden\n"); 10022 return -EACCES; 10023 } 10024 10025 if (!aux->map_ptr_state.map_ptr) 10026 bpf_map_ptr_store(aux, meta->map.ptr, 10027 !meta->map.ptr->bypass_spec_v1, false); 10028 else if (aux->map_ptr_state.map_ptr != meta->map.ptr) 10029 bpf_map_ptr_store(aux, meta->map.ptr, 10030 !meta->map.ptr->bypass_spec_v1, true); 10031 return 0; 10032 } 10033 10034 static int 10035 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10036 int func_id, int insn_idx) 10037 { 10038 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10039 struct bpf_reg_state *reg; 10040 struct bpf_map *map = meta->map.ptr; 10041 u64 val, max; 10042 int err; 10043 10044 if (func_id != BPF_FUNC_tail_call) 10045 return 0; 10046 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 10047 verbose(env, "expected prog array map for tail call"); 10048 return -EINVAL; 10049 } 10050 10051 reg = reg_state(env, BPF_REG_3); 10052 val = reg->var_off.value; 10053 max = map->max_entries; 10054 10055 if (!(is_reg_const(reg, false) && val < max)) { 10056 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10057 return 0; 10058 } 10059 10060 err = mark_chain_precision(env, BPF_REG_3); 10061 if (err) 10062 return err; 10063 if (bpf_map_key_unseen(aux)) 10064 bpf_map_key_store(aux, val); 10065 else if (!bpf_map_key_poisoned(aux) && 10066 bpf_map_key_immediate(aux) != val) 10067 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10068 return 0; 10069 } 10070 10071 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 10072 { 10073 struct bpf_verifier_state *state = env->cur_state; 10074 enum bpf_prog_type type = resolve_prog_type(env->prog); 10075 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 10076 bool refs_lingering = false; 10077 int i; 10078 10079 if (!exception_exit && cur_func(env)->frameno) 10080 return 0; 10081 10082 for (i = 0; i < state->acquired_refs; i++) { 10083 if (state->refs[i].type != REF_TYPE_PTR) 10084 continue; 10085 /* Allow struct_ops programs to return a referenced kptr back to 10086 * kernel. Type checks are performed later in check_return_code. 10087 */ 10088 if (type == BPF_PROG_TYPE_STRUCT_OPS && !exception_exit && 10089 reg->ref_obj_id == state->refs[i].id) 10090 continue; 10091 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 10092 state->refs[i].id, state->refs[i].insn_idx); 10093 refs_lingering = true; 10094 } 10095 return refs_lingering ? -EINVAL : 0; 10096 } 10097 10098 static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix) 10099 { 10100 int err; 10101 10102 if (check_lock && env->cur_state->active_locks) { 10103 verbose(env, "%s cannot be used inside bpf_spin_lock-ed region\n", prefix); 10104 return -EINVAL; 10105 } 10106 10107 err = check_reference_leak(env, exception_exit); 10108 if (err) { 10109 verbose(env, "%s would lead to reference leak\n", prefix); 10110 return err; 10111 } 10112 10113 if (check_lock && env->cur_state->active_irq_id) { 10114 verbose(env, "%s cannot be used inside bpf_local_irq_save-ed region\n", prefix); 10115 return -EINVAL; 10116 } 10117 10118 if (check_lock && env->cur_state->active_rcu_locks) { 10119 verbose(env, "%s cannot be used inside bpf_rcu_read_lock-ed region\n", prefix); 10120 return -EINVAL; 10121 } 10122 10123 if (check_lock && env->cur_state->active_preempt_locks) { 10124 verbose(env, "%s cannot be used inside bpf_preempt_disable-ed region\n", prefix); 10125 return -EINVAL; 10126 } 10127 10128 return 0; 10129 } 10130 10131 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10132 struct bpf_reg_state *regs) 10133 { 10134 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10135 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10136 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10137 struct bpf_bprintf_data data = {}; 10138 int err, fmt_map_off, num_args; 10139 u64 fmt_addr; 10140 char *fmt; 10141 10142 /* data must be an array of u64 */ 10143 if (data_len_reg->var_off.value % 8) 10144 return -EINVAL; 10145 num_args = data_len_reg->var_off.value / 8; 10146 10147 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10148 * and map_direct_value_addr is set. 10149 */ 10150 fmt_map_off = fmt_reg->var_off.value; 10151 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10152 fmt_map_off); 10153 if (err) { 10154 verbose(env, "failed to retrieve map value address\n"); 10155 return -EFAULT; 10156 } 10157 fmt = (char *)(long)fmt_addr + fmt_map_off; 10158 10159 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10160 * can focus on validating the format specifiers. 10161 */ 10162 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10163 if (err < 0) 10164 verbose(env, "Invalid format string\n"); 10165 10166 return err; 10167 } 10168 10169 static int check_get_func_ip(struct bpf_verifier_env *env) 10170 { 10171 enum bpf_prog_type type = resolve_prog_type(env->prog); 10172 int func_id = BPF_FUNC_get_func_ip; 10173 10174 if (type == BPF_PROG_TYPE_TRACING) { 10175 if (!bpf_prog_has_trampoline(env->prog)) { 10176 verbose(env, "func %s#%d supported only for fentry/fexit/fsession/fmod_ret programs\n", 10177 func_id_name(func_id), func_id); 10178 return -ENOTSUPP; 10179 } 10180 return 0; 10181 } else if (type == BPF_PROG_TYPE_KPROBE) { 10182 return 0; 10183 } 10184 10185 verbose(env, "func %s#%d not supported for program type %d\n", 10186 func_id_name(func_id), func_id, type); 10187 return -ENOTSUPP; 10188 } 10189 10190 static struct bpf_insn_aux_data *cur_aux(const struct bpf_verifier_env *env) 10191 { 10192 return &env->insn_aux_data[env->insn_idx]; 10193 } 10194 10195 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10196 { 10197 struct bpf_reg_state *reg = reg_state(env, BPF_REG_4); 10198 bool reg_is_null = bpf_register_is_null(reg); 10199 10200 if (reg_is_null) 10201 mark_chain_precision(env, BPF_REG_4); 10202 10203 return reg_is_null; 10204 } 10205 10206 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10207 { 10208 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10209 10210 if (!state->initialized) { 10211 state->initialized = 1; 10212 state->fit_for_inline = loop_flag_is_zero(env); 10213 state->callback_subprogno = subprogno; 10214 return; 10215 } 10216 10217 if (!state->fit_for_inline) 10218 return; 10219 10220 state->fit_for_inline = (loop_flag_is_zero(env) && 10221 state->callback_subprogno == subprogno); 10222 } 10223 10224 /* Returns whether or not the given map type can potentially elide 10225 * lookup return value nullness check. This is possible if the key 10226 * is statically known. 10227 */ 10228 static bool can_elide_value_nullness(enum bpf_map_type type) 10229 { 10230 switch (type) { 10231 case BPF_MAP_TYPE_ARRAY: 10232 case BPF_MAP_TYPE_PERCPU_ARRAY: 10233 return true; 10234 default: 10235 return false; 10236 } 10237 } 10238 10239 int bpf_get_helper_proto(struct bpf_verifier_env *env, int func_id, 10240 const struct bpf_func_proto **ptr) 10241 { 10242 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) 10243 return -ERANGE; 10244 10245 if (!env->ops->get_func_proto) 10246 return -EINVAL; 10247 10248 *ptr = env->ops->get_func_proto(func_id, env->prog); 10249 return *ptr && (*ptr)->func ? 0 : -EINVAL; 10250 } 10251 10252 /* Check if we're in a sleepable context. */ 10253 static inline bool in_sleepable_context(struct bpf_verifier_env *env) 10254 { 10255 return !env->cur_state->active_rcu_locks && 10256 !env->cur_state->active_preempt_locks && 10257 !env->cur_state->active_locks && 10258 !env->cur_state->active_irq_id && 10259 in_sleepable(env); 10260 } 10261 10262 static const char *non_sleepable_context_description(struct bpf_verifier_env *env) 10263 { 10264 if (env->cur_state->active_rcu_locks) 10265 return "rcu_read_lock region"; 10266 if (env->cur_state->active_preempt_locks) 10267 return "non-preemptible region"; 10268 if (env->cur_state->active_irq_id) 10269 return "IRQ-disabled region"; 10270 if (env->cur_state->active_locks) 10271 return "lock region"; 10272 return "non-sleepable prog"; 10273 } 10274 10275 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10276 int *insn_idx_p) 10277 { 10278 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10279 bool returns_cpu_specific_alloc_ptr = false; 10280 const struct bpf_func_proto *fn = NULL; 10281 enum bpf_return_type ret_type; 10282 enum bpf_type_flag ret_flag; 10283 struct bpf_reg_state *regs; 10284 struct bpf_call_arg_meta meta; 10285 int insn_idx = *insn_idx_p; 10286 bool changes_data; 10287 int i, err, func_id; 10288 10289 /* find function prototype */ 10290 func_id = insn->imm; 10291 err = bpf_get_helper_proto(env, insn->imm, &fn); 10292 if (err == -ERANGE) { 10293 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), func_id); 10294 return -EINVAL; 10295 } 10296 10297 if (err) { 10298 verbose(env, "program of this type cannot use helper %s#%d\n", 10299 func_id_name(func_id), func_id); 10300 return err; 10301 } 10302 10303 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10304 if (!env->prog->gpl_compatible && fn->gpl_only) { 10305 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10306 return -EINVAL; 10307 } 10308 10309 if (fn->allowed && !fn->allowed(env->prog)) { 10310 verbose(env, "helper call is not allowed in probe\n"); 10311 return -EINVAL; 10312 } 10313 10314 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10315 changes_data = bpf_helper_changes_pkt_data(func_id); 10316 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10317 verifier_bug(env, "func %s#%d: r1 != ctx", func_id_name(func_id), func_id); 10318 return -EFAULT; 10319 } 10320 10321 memset(&meta, 0, sizeof(meta)); 10322 meta.pkt_access = fn->pkt_access; 10323 10324 err = check_func_proto(fn); 10325 if (err) { 10326 verifier_bug(env, "incorrect func proto %s#%d", func_id_name(func_id), func_id); 10327 return err; 10328 } 10329 10330 if (fn->might_sleep && !in_sleepable_context(env)) { 10331 verbose(env, "sleepable helper %s#%d in %s\n", func_id_name(func_id), func_id, 10332 non_sleepable_context_description(env)); 10333 return -EINVAL; 10334 } 10335 10336 /* Track non-sleepable context for helpers. */ 10337 if (!in_sleepable_context(env)) 10338 env->insn_aux_data[insn_idx].non_sleepable = true; 10339 10340 meta.func_id = func_id; 10341 /* check args */ 10342 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10343 err = check_func_arg(env, i, &meta, fn, insn_idx); 10344 if (err) 10345 return err; 10346 } 10347 10348 err = record_func_map(env, &meta, func_id, insn_idx); 10349 if (err) 10350 return err; 10351 10352 err = record_func_key(env, &meta, func_id, insn_idx); 10353 if (err) 10354 return err; 10355 10356 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10357 * is inferred from register state. 10358 */ 10359 for (i = 0; i < meta.access_size; i++) { 10360 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10361 BPF_WRITE, -1, false, false); 10362 if (err) 10363 return err; 10364 } 10365 10366 regs = cur_regs(env); 10367 10368 if (meta.release_regno) { 10369 err = -EINVAL; 10370 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10371 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10372 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10373 u32 ref_obj_id = meta.ref_obj_id; 10374 bool in_rcu = in_rcu_cs(env); 10375 struct bpf_func_state *state; 10376 struct bpf_reg_state *reg; 10377 10378 err = release_reference_nomark(env->cur_state, ref_obj_id); 10379 if (!err) { 10380 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10381 if (reg->ref_obj_id == ref_obj_id) { 10382 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10383 reg->ref_obj_id = 0; 10384 reg->type &= ~MEM_ALLOC; 10385 reg->type |= MEM_RCU; 10386 } else { 10387 mark_reg_invalid(env, reg); 10388 } 10389 } 10390 })); 10391 } 10392 } else if (meta.ref_obj_id) { 10393 err = release_reference(env, meta.ref_obj_id); 10394 } else if (bpf_register_is_null(®s[meta.release_regno])) { 10395 /* meta.ref_obj_id can only be 0 if register that is meant to be 10396 * released is NULL, which must be > R0. 10397 */ 10398 err = 0; 10399 } 10400 if (err) { 10401 verbose(env, "func %s#%d reference has not been acquired before\n", 10402 func_id_name(func_id), func_id); 10403 return err; 10404 } 10405 } 10406 10407 switch (func_id) { 10408 case BPF_FUNC_tail_call: 10409 err = check_resource_leak(env, false, true, "tail_call"); 10410 if (err) 10411 return err; 10412 break; 10413 case BPF_FUNC_get_local_storage: 10414 /* check that flags argument in get_local_storage(map, flags) is 0, 10415 * this is required because get_local_storage() can't return an error. 10416 */ 10417 if (!bpf_register_is_null(®s[BPF_REG_2])) { 10418 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10419 return -EINVAL; 10420 } 10421 break; 10422 case BPF_FUNC_for_each_map_elem: 10423 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10424 set_map_elem_callback_state); 10425 break; 10426 case BPF_FUNC_timer_set_callback: 10427 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10428 set_timer_callback_state); 10429 break; 10430 case BPF_FUNC_find_vma: 10431 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10432 set_find_vma_callback_state); 10433 break; 10434 case BPF_FUNC_snprintf: 10435 err = check_bpf_snprintf_call(env, regs); 10436 break; 10437 case BPF_FUNC_loop: 10438 update_loop_inline_state(env, meta.subprogno); 10439 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10440 * is finished, thus mark it precise. 10441 */ 10442 err = mark_chain_precision(env, BPF_REG_1); 10443 if (err) 10444 return err; 10445 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10446 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10447 set_loop_callback_state); 10448 } else { 10449 cur_func(env)->callback_depth = 0; 10450 if (env->log.level & BPF_LOG_LEVEL2) 10451 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10452 env->cur_state->curframe); 10453 } 10454 break; 10455 case BPF_FUNC_dynptr_from_mem: 10456 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10457 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10458 reg_type_str(env, regs[BPF_REG_1].type)); 10459 return -EACCES; 10460 } 10461 break; 10462 case BPF_FUNC_set_retval: 10463 if (prog_type == BPF_PROG_TYPE_LSM && 10464 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10465 if (!env->prog->aux->attach_func_proto->type) { 10466 /* Make sure programs that attach to void 10467 * hooks don't try to modify return value. 10468 */ 10469 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10470 return -EINVAL; 10471 } 10472 } 10473 break; 10474 case BPF_FUNC_dynptr_data: 10475 { 10476 struct bpf_reg_state *reg; 10477 int id, ref_obj_id; 10478 10479 reg = get_dynptr_arg_reg(env, fn, regs); 10480 if (!reg) 10481 return -EFAULT; 10482 10483 10484 if (meta.dynptr_id) { 10485 verifier_bug(env, "meta.dynptr_id already set"); 10486 return -EFAULT; 10487 } 10488 if (meta.ref_obj_id) { 10489 verifier_bug(env, "meta.ref_obj_id already set"); 10490 return -EFAULT; 10491 } 10492 10493 id = dynptr_id(env, reg); 10494 if (id < 0) { 10495 verifier_bug(env, "failed to obtain dynptr id"); 10496 return id; 10497 } 10498 10499 ref_obj_id = dynptr_ref_obj_id(env, reg); 10500 if (ref_obj_id < 0) { 10501 verifier_bug(env, "failed to obtain dynptr ref_obj_id"); 10502 return ref_obj_id; 10503 } 10504 10505 meta.dynptr_id = id; 10506 meta.ref_obj_id = ref_obj_id; 10507 10508 break; 10509 } 10510 case BPF_FUNC_dynptr_write: 10511 { 10512 enum bpf_dynptr_type dynptr_type; 10513 struct bpf_reg_state *reg; 10514 10515 reg = get_dynptr_arg_reg(env, fn, regs); 10516 if (!reg) 10517 return -EFAULT; 10518 10519 dynptr_type = dynptr_get_type(env, reg); 10520 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10521 return -EFAULT; 10522 10523 if (dynptr_type == BPF_DYNPTR_TYPE_SKB || 10524 dynptr_type == BPF_DYNPTR_TYPE_SKB_META) 10525 /* this will trigger clear_all_pkt_pointers(), which will 10526 * invalidate all dynptr slices associated with the skb 10527 */ 10528 changes_data = true; 10529 10530 break; 10531 } 10532 case BPF_FUNC_per_cpu_ptr: 10533 case BPF_FUNC_this_cpu_ptr: 10534 { 10535 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10536 const struct btf_type *type; 10537 10538 if (reg->type & MEM_RCU) { 10539 type = btf_type_by_id(reg->btf, reg->btf_id); 10540 if (!type || !btf_type_is_struct(type)) { 10541 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10542 return -EFAULT; 10543 } 10544 returns_cpu_specific_alloc_ptr = true; 10545 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10546 } 10547 break; 10548 } 10549 case BPF_FUNC_user_ringbuf_drain: 10550 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10551 set_user_ringbuf_callback_state); 10552 break; 10553 } 10554 10555 if (err) 10556 return err; 10557 10558 /* reset caller saved regs */ 10559 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10560 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 10561 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10562 } 10563 10564 /* helper call returns 64-bit value. */ 10565 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10566 10567 /* update return register (already marked as written above) */ 10568 ret_type = fn->ret_type; 10569 ret_flag = type_flag(ret_type); 10570 10571 switch (base_type(ret_type)) { 10572 case RET_INTEGER: 10573 /* sets type to SCALAR_VALUE */ 10574 mark_reg_unknown(env, regs, BPF_REG_0); 10575 break; 10576 case RET_VOID: 10577 regs[BPF_REG_0].type = NOT_INIT; 10578 break; 10579 case RET_PTR_TO_MAP_VALUE: 10580 /* There is no offset yet applied, variable or fixed */ 10581 mark_reg_known_zero(env, regs, BPF_REG_0); 10582 /* remember map_ptr, so that check_map_access() 10583 * can check 'value_size' boundary of memory access 10584 * to map element returned from bpf_map_lookup_elem() 10585 */ 10586 if (meta.map.ptr == NULL) { 10587 verifier_bug(env, "unexpected null map_ptr"); 10588 return -EFAULT; 10589 } 10590 10591 if (func_id == BPF_FUNC_map_lookup_elem && 10592 can_elide_value_nullness(meta.map.ptr->map_type) && 10593 meta.const_map_key >= 0 && 10594 meta.const_map_key < meta.map.ptr->max_entries) 10595 ret_flag &= ~PTR_MAYBE_NULL; 10596 10597 regs[BPF_REG_0].map_ptr = meta.map.ptr; 10598 regs[BPF_REG_0].map_uid = meta.map.uid; 10599 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10600 if (!type_may_be_null(ret_flag) && 10601 btf_record_has_field(meta.map.ptr->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 10602 regs[BPF_REG_0].id = ++env->id_gen; 10603 } 10604 break; 10605 case RET_PTR_TO_SOCKET: 10606 mark_reg_known_zero(env, regs, BPF_REG_0); 10607 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10608 break; 10609 case RET_PTR_TO_SOCK_COMMON: 10610 mark_reg_known_zero(env, regs, BPF_REG_0); 10611 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10612 break; 10613 case RET_PTR_TO_TCP_SOCK: 10614 mark_reg_known_zero(env, regs, BPF_REG_0); 10615 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10616 break; 10617 case RET_PTR_TO_MEM: 10618 mark_reg_known_zero(env, regs, BPF_REG_0); 10619 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10620 regs[BPF_REG_0].mem_size = meta.mem_size; 10621 break; 10622 case RET_PTR_TO_MEM_OR_BTF_ID: 10623 { 10624 const struct btf_type *t; 10625 10626 mark_reg_known_zero(env, regs, BPF_REG_0); 10627 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10628 if (!btf_type_is_struct(t)) { 10629 u32 tsize; 10630 const struct btf_type *ret; 10631 const char *tname; 10632 10633 /* resolve the type size of ksym. */ 10634 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10635 if (IS_ERR(ret)) { 10636 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10637 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10638 tname, PTR_ERR(ret)); 10639 return -EINVAL; 10640 } 10641 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10642 regs[BPF_REG_0].mem_size = tsize; 10643 } else { 10644 if (returns_cpu_specific_alloc_ptr) { 10645 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10646 } else { 10647 /* MEM_RDONLY may be carried from ret_flag, but it 10648 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10649 * it will confuse the check of PTR_TO_BTF_ID in 10650 * check_mem_access(). 10651 */ 10652 ret_flag &= ~MEM_RDONLY; 10653 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10654 } 10655 10656 regs[BPF_REG_0].btf = meta.ret_btf; 10657 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10658 } 10659 break; 10660 } 10661 case RET_PTR_TO_BTF_ID: 10662 { 10663 struct btf *ret_btf; 10664 int ret_btf_id; 10665 10666 mark_reg_known_zero(env, regs, BPF_REG_0); 10667 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10668 if (func_id == BPF_FUNC_kptr_xchg) { 10669 ret_btf = meta.kptr_field->kptr.btf; 10670 ret_btf_id = meta.kptr_field->kptr.btf_id; 10671 if (!btf_is_kernel(ret_btf)) { 10672 regs[BPF_REG_0].type |= MEM_ALLOC; 10673 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10674 regs[BPF_REG_0].type |= MEM_PERCPU; 10675 } 10676 } else { 10677 if (fn->ret_btf_id == BPF_PTR_POISON) { 10678 verifier_bug(env, "func %s has non-overwritten BPF_PTR_POISON return type", 10679 func_id_name(func_id)); 10680 return -EFAULT; 10681 } 10682 ret_btf = btf_vmlinux; 10683 ret_btf_id = *fn->ret_btf_id; 10684 } 10685 if (ret_btf_id == 0) { 10686 verbose(env, "invalid return type %u of func %s#%d\n", 10687 base_type(ret_type), func_id_name(func_id), 10688 func_id); 10689 return -EINVAL; 10690 } 10691 regs[BPF_REG_0].btf = ret_btf; 10692 regs[BPF_REG_0].btf_id = ret_btf_id; 10693 break; 10694 } 10695 default: 10696 verbose(env, "unknown return type %u of func %s#%d\n", 10697 base_type(ret_type), func_id_name(func_id), func_id); 10698 return -EINVAL; 10699 } 10700 10701 if (type_may_be_null(regs[BPF_REG_0].type)) 10702 regs[BPF_REG_0].id = ++env->id_gen; 10703 10704 if (helper_multiple_ref_obj_use(func_id, meta.map.ptr)) { 10705 verifier_bug(env, "func %s#%d sets ref_obj_id more than once", 10706 func_id_name(func_id), func_id); 10707 return -EFAULT; 10708 } 10709 10710 if (is_dynptr_ref_function(func_id)) 10711 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10712 10713 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10714 /* For release_reference() */ 10715 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10716 } else if (is_acquire_function(func_id, meta.map.ptr)) { 10717 int id = acquire_reference(env, insn_idx); 10718 10719 if (id < 0) 10720 return id; 10721 /* For mark_ptr_or_null_reg() */ 10722 regs[BPF_REG_0].id = id; 10723 /* For release_reference() */ 10724 regs[BPF_REG_0].ref_obj_id = id; 10725 } 10726 10727 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10728 if (err) 10729 return err; 10730 10731 err = check_map_func_compatibility(env, meta.map.ptr, func_id); 10732 if (err) 10733 return err; 10734 10735 if ((func_id == BPF_FUNC_get_stack || 10736 func_id == BPF_FUNC_get_task_stack) && 10737 !env->prog->has_callchain_buf) { 10738 const char *err_str; 10739 10740 #ifdef CONFIG_PERF_EVENTS 10741 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10742 err_str = "cannot get callchain buffer for func %s#%d\n"; 10743 #else 10744 err = -ENOTSUPP; 10745 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10746 #endif 10747 if (err) { 10748 verbose(env, err_str, func_id_name(func_id), func_id); 10749 return err; 10750 } 10751 10752 env->prog->has_callchain_buf = true; 10753 } 10754 10755 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10756 env->prog->call_get_stack = true; 10757 10758 if (func_id == BPF_FUNC_get_func_ip) { 10759 if (check_get_func_ip(env)) 10760 return -ENOTSUPP; 10761 env->prog->call_get_func_ip = true; 10762 } 10763 10764 if (func_id == BPF_FUNC_tail_call) { 10765 if (env->cur_state->curframe) { 10766 struct bpf_verifier_state *branch; 10767 10768 mark_reg_scratched(env, BPF_REG_0); 10769 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 10770 if (IS_ERR(branch)) 10771 return PTR_ERR(branch); 10772 clear_all_pkt_pointers(env); 10773 mark_reg_unknown(env, regs, BPF_REG_0); 10774 err = prepare_func_exit(env, &env->insn_idx); 10775 if (err) 10776 return err; 10777 env->insn_idx--; 10778 } else { 10779 changes_data = false; 10780 } 10781 } 10782 10783 if (changes_data) 10784 clear_all_pkt_pointers(env); 10785 return 0; 10786 } 10787 10788 /* mark_btf_func_reg_size() is used when the reg size is determined by 10789 * the BTF func_proto's return value size and argument. 10790 */ 10791 static void __mark_btf_func_reg_size(struct bpf_verifier_env *env, struct bpf_reg_state *regs, 10792 u32 regno, size_t reg_size) 10793 { 10794 struct bpf_reg_state *reg = ®s[regno]; 10795 10796 if (regno == BPF_REG_0) { 10797 /* Function return value */ 10798 reg->subreg_def = reg_size == sizeof(u64) ? 10799 DEF_NOT_SUBREG : env->insn_idx + 1; 10800 } else if (reg_size == sizeof(u64)) { 10801 /* Function argument */ 10802 mark_insn_zext(env, reg); 10803 } 10804 } 10805 10806 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10807 size_t reg_size) 10808 { 10809 return __mark_btf_func_reg_size(env, cur_regs(env), regno, reg_size); 10810 } 10811 10812 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10813 { 10814 return meta->kfunc_flags & KF_ACQUIRE; 10815 } 10816 10817 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10818 { 10819 return meta->kfunc_flags & KF_RELEASE; 10820 } 10821 10822 10823 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10824 { 10825 return meta->kfunc_flags & KF_DESTRUCTIVE; 10826 } 10827 10828 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10829 { 10830 return meta->kfunc_flags & KF_RCU; 10831 } 10832 10833 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10834 { 10835 return meta->kfunc_flags & KF_RCU_PROTECTED; 10836 } 10837 10838 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10839 const struct btf_param *arg, 10840 const struct bpf_reg_state *reg) 10841 { 10842 const struct btf_type *t; 10843 10844 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10845 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10846 return false; 10847 10848 return btf_param_match_suffix(btf, arg, "__sz"); 10849 } 10850 10851 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10852 const struct btf_param *arg, 10853 const struct bpf_reg_state *reg) 10854 { 10855 const struct btf_type *t; 10856 10857 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10858 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10859 return false; 10860 10861 return btf_param_match_suffix(btf, arg, "__szk"); 10862 } 10863 10864 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10865 { 10866 return btf_param_match_suffix(btf, arg, "__k"); 10867 } 10868 10869 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10870 { 10871 return btf_param_match_suffix(btf, arg, "__ign"); 10872 } 10873 10874 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 10875 { 10876 return btf_param_match_suffix(btf, arg, "__map"); 10877 } 10878 10879 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10880 { 10881 return btf_param_match_suffix(btf, arg, "__alloc"); 10882 } 10883 10884 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10885 { 10886 return btf_param_match_suffix(btf, arg, "__uninit"); 10887 } 10888 10889 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10890 { 10891 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 10892 } 10893 10894 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10895 { 10896 return btf_param_match_suffix(btf, arg, "__nullable"); 10897 } 10898 10899 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10900 { 10901 return btf_param_match_suffix(btf, arg, "__str"); 10902 } 10903 10904 static bool is_kfunc_arg_irq_flag(const struct btf *btf, const struct btf_param *arg) 10905 { 10906 return btf_param_match_suffix(btf, arg, "__irq_flag"); 10907 } 10908 10909 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10910 const struct btf_param *arg, 10911 const char *name) 10912 { 10913 int len, target_len = strlen(name); 10914 const char *param_name; 10915 10916 param_name = btf_name_by_offset(btf, arg->name_off); 10917 if (str_is_empty(param_name)) 10918 return false; 10919 len = strlen(param_name); 10920 if (len != target_len) 10921 return false; 10922 if (strcmp(param_name, name)) 10923 return false; 10924 10925 return true; 10926 } 10927 10928 enum { 10929 KF_ARG_DYNPTR_ID, 10930 KF_ARG_LIST_HEAD_ID, 10931 KF_ARG_LIST_NODE_ID, 10932 KF_ARG_RB_ROOT_ID, 10933 KF_ARG_RB_NODE_ID, 10934 KF_ARG_WORKQUEUE_ID, 10935 KF_ARG_RES_SPIN_LOCK_ID, 10936 KF_ARG_TASK_WORK_ID, 10937 KF_ARG_PROG_AUX_ID, 10938 KF_ARG_TIMER_ID 10939 }; 10940 10941 BTF_ID_LIST(kf_arg_btf_ids) 10942 BTF_ID(struct, bpf_dynptr) 10943 BTF_ID(struct, bpf_list_head) 10944 BTF_ID(struct, bpf_list_node) 10945 BTF_ID(struct, bpf_rb_root) 10946 BTF_ID(struct, bpf_rb_node) 10947 BTF_ID(struct, bpf_wq) 10948 BTF_ID(struct, bpf_res_spin_lock) 10949 BTF_ID(struct, bpf_task_work) 10950 BTF_ID(struct, bpf_prog_aux) 10951 BTF_ID(struct, bpf_timer) 10952 10953 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10954 const struct btf_param *arg, int type) 10955 { 10956 const struct btf_type *t; 10957 u32 res_id; 10958 10959 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10960 if (!t) 10961 return false; 10962 if (!btf_type_is_ptr(t)) 10963 return false; 10964 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10965 if (!t) 10966 return false; 10967 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10968 } 10969 10970 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10971 { 10972 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10973 } 10974 10975 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10976 { 10977 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10978 } 10979 10980 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10981 { 10982 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10983 } 10984 10985 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10986 { 10987 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10988 } 10989 10990 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10991 { 10992 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10993 } 10994 10995 static bool is_kfunc_arg_timer(const struct btf *btf, const struct btf_param *arg) 10996 { 10997 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TIMER_ID); 10998 } 10999 11000 static bool is_kfunc_arg_wq(const struct btf *btf, const struct btf_param *arg) 11001 { 11002 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_WORKQUEUE_ID); 11003 } 11004 11005 static bool is_kfunc_arg_task_work(const struct btf *btf, const struct btf_param *arg) 11006 { 11007 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_TASK_WORK_ID); 11008 } 11009 11010 static bool is_kfunc_arg_res_spin_lock(const struct btf *btf, const struct btf_param *arg) 11011 { 11012 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RES_SPIN_LOCK_ID); 11013 } 11014 11015 static bool is_rbtree_node_type(const struct btf_type *t) 11016 { 11017 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_RB_NODE_ID]); 11018 } 11019 11020 static bool is_list_node_type(const struct btf_type *t) 11021 { 11022 return t == btf_type_by_id(btf_vmlinux, kf_arg_btf_ids[KF_ARG_LIST_NODE_ID]); 11023 } 11024 11025 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 11026 const struct btf_param *arg) 11027 { 11028 const struct btf_type *t; 11029 11030 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 11031 if (!t) 11032 return false; 11033 11034 return true; 11035 } 11036 11037 static bool is_kfunc_arg_prog_aux(const struct btf *btf, const struct btf_param *arg) 11038 { 11039 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_PROG_AUX_ID); 11040 } 11041 11042 /* 11043 * A kfunc with KF_IMPLICIT_ARGS has two prototypes in BTF: 11044 * - the _impl prototype with full arg list (meta->func_proto) 11045 * - the BPF API prototype w/o implicit args (func->type in BTF) 11046 * To determine whether an argument is implicit, we compare its position 11047 * against the number of arguments in the prototype w/o implicit args. 11048 */ 11049 static bool is_kfunc_arg_implicit(const struct bpf_kfunc_call_arg_meta *meta, u32 arg_idx) 11050 { 11051 const struct btf_type *func, *func_proto; 11052 u32 argn; 11053 11054 if (!(meta->kfunc_flags & KF_IMPLICIT_ARGS)) 11055 return false; 11056 11057 func = btf_type_by_id(meta->btf, meta->func_id); 11058 func_proto = btf_type_by_id(meta->btf, func->type); 11059 argn = btf_type_vlen(func_proto); 11060 11061 return argn <= arg_idx; 11062 } 11063 11064 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 11065 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 11066 const struct btf *btf, 11067 const struct btf_type *t, int rec) 11068 { 11069 const struct btf_type *member_type; 11070 const struct btf_member *member; 11071 u32 i; 11072 11073 if (!btf_type_is_struct(t)) 11074 return false; 11075 11076 for_each_member(i, t, member) { 11077 const struct btf_array *array; 11078 11079 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 11080 if (btf_type_is_struct(member_type)) { 11081 if (rec >= 3) { 11082 verbose(env, "max struct nesting depth exceeded\n"); 11083 return false; 11084 } 11085 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 11086 return false; 11087 continue; 11088 } 11089 if (btf_type_is_array(member_type)) { 11090 array = btf_array(member_type); 11091 if (!array->nelems) 11092 return false; 11093 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 11094 if (!btf_type_is_scalar(member_type)) 11095 return false; 11096 continue; 11097 } 11098 if (!btf_type_is_scalar(member_type)) 11099 return false; 11100 } 11101 return true; 11102 } 11103 11104 enum kfunc_ptr_arg_type { 11105 KF_ARG_PTR_TO_CTX, 11106 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 11107 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 11108 KF_ARG_PTR_TO_DYNPTR, 11109 KF_ARG_PTR_TO_ITER, 11110 KF_ARG_PTR_TO_LIST_HEAD, 11111 KF_ARG_PTR_TO_LIST_NODE, 11112 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 11113 KF_ARG_PTR_TO_MEM, 11114 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 11115 KF_ARG_PTR_TO_CALLBACK, 11116 KF_ARG_PTR_TO_RB_ROOT, 11117 KF_ARG_PTR_TO_RB_NODE, 11118 KF_ARG_PTR_TO_NULL, 11119 KF_ARG_PTR_TO_CONST_STR, 11120 KF_ARG_PTR_TO_MAP, 11121 KF_ARG_PTR_TO_TIMER, 11122 KF_ARG_PTR_TO_WORKQUEUE, 11123 KF_ARG_PTR_TO_IRQ_FLAG, 11124 KF_ARG_PTR_TO_RES_SPIN_LOCK, 11125 KF_ARG_PTR_TO_TASK_WORK, 11126 }; 11127 11128 enum special_kfunc_type { 11129 KF_bpf_obj_new_impl, 11130 KF_bpf_obj_new, 11131 KF_bpf_obj_drop_impl, 11132 KF_bpf_obj_drop, 11133 KF_bpf_refcount_acquire_impl, 11134 KF_bpf_refcount_acquire, 11135 KF_bpf_list_push_front_impl, 11136 KF_bpf_list_push_front, 11137 KF_bpf_list_push_back_impl, 11138 KF_bpf_list_push_back, 11139 KF_bpf_list_pop_front, 11140 KF_bpf_list_pop_back, 11141 KF_bpf_list_front, 11142 KF_bpf_list_back, 11143 KF_bpf_cast_to_kern_ctx, 11144 KF_bpf_rdonly_cast, 11145 KF_bpf_rcu_read_lock, 11146 KF_bpf_rcu_read_unlock, 11147 KF_bpf_rbtree_remove, 11148 KF_bpf_rbtree_add_impl, 11149 KF_bpf_rbtree_add, 11150 KF_bpf_rbtree_first, 11151 KF_bpf_rbtree_root, 11152 KF_bpf_rbtree_left, 11153 KF_bpf_rbtree_right, 11154 KF_bpf_dynptr_from_skb, 11155 KF_bpf_dynptr_from_xdp, 11156 KF_bpf_dynptr_from_skb_meta, 11157 KF_bpf_xdp_pull_data, 11158 KF_bpf_dynptr_slice, 11159 KF_bpf_dynptr_slice_rdwr, 11160 KF_bpf_dynptr_clone, 11161 KF_bpf_percpu_obj_new_impl, 11162 KF_bpf_percpu_obj_new, 11163 KF_bpf_percpu_obj_drop_impl, 11164 KF_bpf_percpu_obj_drop, 11165 KF_bpf_throw, 11166 KF_bpf_wq_set_callback, 11167 KF_bpf_preempt_disable, 11168 KF_bpf_preempt_enable, 11169 KF_bpf_iter_css_task_new, 11170 KF_bpf_session_cookie, 11171 KF_bpf_get_kmem_cache, 11172 KF_bpf_local_irq_save, 11173 KF_bpf_local_irq_restore, 11174 KF_bpf_iter_num_new, 11175 KF_bpf_iter_num_next, 11176 KF_bpf_iter_num_destroy, 11177 KF_bpf_set_dentry_xattr, 11178 KF_bpf_remove_dentry_xattr, 11179 KF_bpf_res_spin_lock, 11180 KF_bpf_res_spin_unlock, 11181 KF_bpf_res_spin_lock_irqsave, 11182 KF_bpf_res_spin_unlock_irqrestore, 11183 KF_bpf_dynptr_from_file, 11184 KF_bpf_dynptr_file_discard, 11185 KF___bpf_trap, 11186 KF_bpf_task_work_schedule_signal, 11187 KF_bpf_task_work_schedule_resume, 11188 KF_bpf_arena_alloc_pages, 11189 KF_bpf_arena_free_pages, 11190 KF_bpf_arena_reserve_pages, 11191 KF_bpf_session_is_return, 11192 KF_bpf_stream_vprintk, 11193 KF_bpf_stream_print_stack, 11194 }; 11195 11196 BTF_ID_LIST(special_kfunc_list) 11197 BTF_ID(func, bpf_obj_new_impl) 11198 BTF_ID(func, bpf_obj_new) 11199 BTF_ID(func, bpf_obj_drop_impl) 11200 BTF_ID(func, bpf_obj_drop) 11201 BTF_ID(func, bpf_refcount_acquire_impl) 11202 BTF_ID(func, bpf_refcount_acquire) 11203 BTF_ID(func, bpf_list_push_front_impl) 11204 BTF_ID(func, bpf_list_push_front) 11205 BTF_ID(func, bpf_list_push_back_impl) 11206 BTF_ID(func, bpf_list_push_back) 11207 BTF_ID(func, bpf_list_pop_front) 11208 BTF_ID(func, bpf_list_pop_back) 11209 BTF_ID(func, bpf_list_front) 11210 BTF_ID(func, bpf_list_back) 11211 BTF_ID(func, bpf_cast_to_kern_ctx) 11212 BTF_ID(func, bpf_rdonly_cast) 11213 BTF_ID(func, bpf_rcu_read_lock) 11214 BTF_ID(func, bpf_rcu_read_unlock) 11215 BTF_ID(func, bpf_rbtree_remove) 11216 BTF_ID(func, bpf_rbtree_add_impl) 11217 BTF_ID(func, bpf_rbtree_add) 11218 BTF_ID(func, bpf_rbtree_first) 11219 BTF_ID(func, bpf_rbtree_root) 11220 BTF_ID(func, bpf_rbtree_left) 11221 BTF_ID(func, bpf_rbtree_right) 11222 #ifdef CONFIG_NET 11223 BTF_ID(func, bpf_dynptr_from_skb) 11224 BTF_ID(func, bpf_dynptr_from_xdp) 11225 BTF_ID(func, bpf_dynptr_from_skb_meta) 11226 BTF_ID(func, bpf_xdp_pull_data) 11227 #else 11228 BTF_ID_UNUSED 11229 BTF_ID_UNUSED 11230 BTF_ID_UNUSED 11231 BTF_ID_UNUSED 11232 #endif 11233 BTF_ID(func, bpf_dynptr_slice) 11234 BTF_ID(func, bpf_dynptr_slice_rdwr) 11235 BTF_ID(func, bpf_dynptr_clone) 11236 BTF_ID(func, bpf_percpu_obj_new_impl) 11237 BTF_ID(func, bpf_percpu_obj_new) 11238 BTF_ID(func, bpf_percpu_obj_drop_impl) 11239 BTF_ID(func, bpf_percpu_obj_drop) 11240 BTF_ID(func, bpf_throw) 11241 BTF_ID(func, bpf_wq_set_callback) 11242 BTF_ID(func, bpf_preempt_disable) 11243 BTF_ID(func, bpf_preempt_enable) 11244 #ifdef CONFIG_CGROUPS 11245 BTF_ID(func, bpf_iter_css_task_new) 11246 #else 11247 BTF_ID_UNUSED 11248 #endif 11249 #ifdef CONFIG_BPF_EVENTS 11250 BTF_ID(func, bpf_session_cookie) 11251 #else 11252 BTF_ID_UNUSED 11253 #endif 11254 BTF_ID(func, bpf_get_kmem_cache) 11255 BTF_ID(func, bpf_local_irq_save) 11256 BTF_ID(func, bpf_local_irq_restore) 11257 BTF_ID(func, bpf_iter_num_new) 11258 BTF_ID(func, bpf_iter_num_next) 11259 BTF_ID(func, bpf_iter_num_destroy) 11260 #ifdef CONFIG_BPF_LSM 11261 BTF_ID(func, bpf_set_dentry_xattr) 11262 BTF_ID(func, bpf_remove_dentry_xattr) 11263 #else 11264 BTF_ID_UNUSED 11265 BTF_ID_UNUSED 11266 #endif 11267 BTF_ID(func, bpf_res_spin_lock) 11268 BTF_ID(func, bpf_res_spin_unlock) 11269 BTF_ID(func, bpf_res_spin_lock_irqsave) 11270 BTF_ID(func, bpf_res_spin_unlock_irqrestore) 11271 BTF_ID(func, bpf_dynptr_from_file) 11272 BTF_ID(func, bpf_dynptr_file_discard) 11273 BTF_ID(func, __bpf_trap) 11274 BTF_ID(func, bpf_task_work_schedule_signal) 11275 BTF_ID(func, bpf_task_work_schedule_resume) 11276 BTF_ID(func, bpf_arena_alloc_pages) 11277 BTF_ID(func, bpf_arena_free_pages) 11278 BTF_ID(func, bpf_arena_reserve_pages) 11279 #ifdef CONFIG_BPF_EVENTS 11280 BTF_ID(func, bpf_session_is_return) 11281 #else 11282 BTF_ID_UNUSED 11283 #endif 11284 BTF_ID(func, bpf_stream_vprintk) 11285 BTF_ID(func, bpf_stream_print_stack) 11286 11287 static bool is_bpf_obj_new_kfunc(u32 func_id) 11288 { 11289 return func_id == special_kfunc_list[KF_bpf_obj_new] || 11290 func_id == special_kfunc_list[KF_bpf_obj_new_impl]; 11291 } 11292 11293 static bool is_bpf_percpu_obj_new_kfunc(u32 func_id) 11294 { 11295 return func_id == special_kfunc_list[KF_bpf_percpu_obj_new] || 11296 func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]; 11297 } 11298 11299 static bool is_bpf_obj_drop_kfunc(u32 func_id) 11300 { 11301 return func_id == special_kfunc_list[KF_bpf_obj_drop] || 11302 func_id == special_kfunc_list[KF_bpf_obj_drop_impl]; 11303 } 11304 11305 static bool is_bpf_percpu_obj_drop_kfunc(u32 func_id) 11306 { 11307 return func_id == special_kfunc_list[KF_bpf_percpu_obj_drop] || 11308 func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]; 11309 } 11310 11311 static bool is_bpf_refcount_acquire_kfunc(u32 func_id) 11312 { 11313 return func_id == special_kfunc_list[KF_bpf_refcount_acquire] || 11314 func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11315 } 11316 11317 static bool is_bpf_list_push_kfunc(u32 func_id) 11318 { 11319 return func_id == special_kfunc_list[KF_bpf_list_push_front] || 11320 func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11321 func_id == special_kfunc_list[KF_bpf_list_push_back] || 11322 func_id == special_kfunc_list[KF_bpf_list_push_back_impl]; 11323 } 11324 11325 static bool is_bpf_rbtree_add_kfunc(u32 func_id) 11326 { 11327 return func_id == special_kfunc_list[KF_bpf_rbtree_add] || 11328 func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11329 } 11330 11331 static bool is_task_work_add_kfunc(u32 func_id) 11332 { 11333 return func_id == special_kfunc_list[KF_bpf_task_work_schedule_signal] || 11334 func_id == special_kfunc_list[KF_bpf_task_work_schedule_resume]; 11335 } 11336 11337 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11338 { 11339 if (is_bpf_refcount_acquire_kfunc(meta->func_id) && meta->arg_owning_ref) 11340 return false; 11341 11342 return meta->kfunc_flags & KF_RET_NULL; 11343 } 11344 11345 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11346 { 11347 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11348 } 11349 11350 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11351 { 11352 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11353 } 11354 11355 static bool is_kfunc_bpf_preempt_disable(struct bpf_kfunc_call_arg_meta *meta) 11356 { 11357 return meta->func_id == special_kfunc_list[KF_bpf_preempt_disable]; 11358 } 11359 11360 static bool is_kfunc_bpf_preempt_enable(struct bpf_kfunc_call_arg_meta *meta) 11361 { 11362 return meta->func_id == special_kfunc_list[KF_bpf_preempt_enable]; 11363 } 11364 11365 bool bpf_is_kfunc_pkt_changing(struct bpf_kfunc_call_arg_meta *meta) 11366 { 11367 return meta->func_id == special_kfunc_list[KF_bpf_xdp_pull_data]; 11368 } 11369 11370 static enum kfunc_ptr_arg_type 11371 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 11372 struct bpf_kfunc_call_arg_meta *meta, 11373 const struct btf_type *t, const struct btf_type *ref_t, 11374 const char *ref_tname, const struct btf_param *args, 11375 int argno, int nargs) 11376 { 11377 u32 regno = argno + 1; 11378 struct bpf_reg_state *regs = cur_regs(env); 11379 struct bpf_reg_state *reg = ®s[regno]; 11380 bool arg_mem_size = false; 11381 11382 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 11383 meta->func_id == special_kfunc_list[KF_bpf_session_is_return] || 11384 meta->func_id == special_kfunc_list[KF_bpf_session_cookie]) 11385 return KF_ARG_PTR_TO_CTX; 11386 11387 if (argno + 1 < nargs && 11388 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11389 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11390 arg_mem_size = true; 11391 11392 /* In this function, we verify the kfunc's BTF as per the argument type, 11393 * leaving the rest of the verification with respect to the register 11394 * type to our caller. When a set of conditions hold in the BTF type of 11395 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11396 */ 11397 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 11398 return KF_ARG_PTR_TO_CTX; 11399 11400 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && bpf_register_is_null(reg) && 11401 !arg_mem_size) 11402 return KF_ARG_PTR_TO_NULL; 11403 11404 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 11405 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11406 11407 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 11408 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11409 11410 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 11411 return KF_ARG_PTR_TO_DYNPTR; 11412 11413 if (is_kfunc_arg_iter(meta, argno, &args[argno])) 11414 return KF_ARG_PTR_TO_ITER; 11415 11416 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 11417 return KF_ARG_PTR_TO_LIST_HEAD; 11418 11419 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 11420 return KF_ARG_PTR_TO_LIST_NODE; 11421 11422 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 11423 return KF_ARG_PTR_TO_RB_ROOT; 11424 11425 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 11426 return KF_ARG_PTR_TO_RB_NODE; 11427 11428 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11429 return KF_ARG_PTR_TO_CONST_STR; 11430 11431 if (is_kfunc_arg_map(meta->btf, &args[argno])) 11432 return KF_ARG_PTR_TO_MAP; 11433 11434 if (is_kfunc_arg_wq(meta->btf, &args[argno])) 11435 return KF_ARG_PTR_TO_WORKQUEUE; 11436 11437 if (is_kfunc_arg_timer(meta->btf, &args[argno])) 11438 return KF_ARG_PTR_TO_TIMER; 11439 11440 if (is_kfunc_arg_task_work(meta->btf, &args[argno])) 11441 return KF_ARG_PTR_TO_TASK_WORK; 11442 11443 if (is_kfunc_arg_irq_flag(meta->btf, &args[argno])) 11444 return KF_ARG_PTR_TO_IRQ_FLAG; 11445 11446 if (is_kfunc_arg_res_spin_lock(meta->btf, &args[argno])) 11447 return KF_ARG_PTR_TO_RES_SPIN_LOCK; 11448 11449 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11450 if (!btf_type_is_struct(ref_t)) { 11451 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11452 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11453 return -EINVAL; 11454 } 11455 return KF_ARG_PTR_TO_BTF_ID; 11456 } 11457 11458 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11459 return KF_ARG_PTR_TO_CALLBACK; 11460 11461 /* This is the catch all argument type of register types supported by 11462 * check_helper_mem_access. However, we only allow when argument type is 11463 * pointer to scalar, or struct composed (recursively) of scalars. When 11464 * arg_mem_size is true, the pointer can be void *. 11465 */ 11466 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11467 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11468 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11469 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11470 return -EINVAL; 11471 } 11472 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11473 } 11474 11475 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11476 struct bpf_reg_state *reg, 11477 const struct btf_type *ref_t, 11478 const char *ref_tname, u32 ref_id, 11479 struct bpf_kfunc_call_arg_meta *meta, 11480 int argno) 11481 { 11482 const struct btf_type *reg_ref_t; 11483 bool strict_type_match = false; 11484 const struct btf *reg_btf; 11485 const char *reg_ref_tname; 11486 bool taking_projection; 11487 bool struct_same; 11488 u32 reg_ref_id; 11489 11490 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11491 reg_btf = reg->btf; 11492 reg_ref_id = reg->btf_id; 11493 } else { 11494 reg_btf = btf_vmlinux; 11495 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11496 } 11497 11498 /* Enforce strict type matching for calls to kfuncs that are acquiring 11499 * or releasing a reference, or are no-cast aliases. We do _not_ 11500 * enforce strict matching for kfuncs by default, 11501 * as we want to enable BPF programs to pass types that are bitwise 11502 * equivalent without forcing them to explicitly cast with something 11503 * like bpf_cast_to_kern_ctx(). 11504 * 11505 * For example, say we had a type like the following: 11506 * 11507 * struct bpf_cpumask { 11508 * cpumask_t cpumask; 11509 * refcount_t usage; 11510 * }; 11511 * 11512 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11513 * to a struct cpumask, so it would be safe to pass a struct 11514 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11515 * 11516 * The philosophy here is similar to how we allow scalars of different 11517 * types to be passed to kfuncs as long as the size is the same. The 11518 * only difference here is that we're simply allowing 11519 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11520 * resolve types. 11521 */ 11522 if ((is_kfunc_release(meta) && reg->ref_obj_id) || 11523 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11524 strict_type_match = true; 11525 11526 WARN_ON_ONCE(is_kfunc_release(meta) && !tnum_is_const(reg->var_off)); 11527 11528 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11529 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11530 struct_same = btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->var_off.value, 11531 meta->btf, ref_id, strict_type_match); 11532 /* If kfunc is accepting a projection type (ie. __sk_buff), it cannot 11533 * actually use it -- it must cast to the underlying type. So we allow 11534 * caller to pass in the underlying type. 11535 */ 11536 taking_projection = btf_is_projection_of(ref_tname, reg_ref_tname); 11537 if (!taking_projection && !struct_same) { 11538 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11539 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11540 btf_type_str(reg_ref_t), reg_ref_tname); 11541 return -EINVAL; 11542 } 11543 return 0; 11544 } 11545 11546 static int process_irq_flag(struct bpf_verifier_env *env, int regno, 11547 struct bpf_kfunc_call_arg_meta *meta) 11548 { 11549 struct bpf_reg_state *reg = reg_state(env, regno); 11550 int err, kfunc_class = IRQ_NATIVE_KFUNC; 11551 bool irq_save; 11552 11553 if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_save] || 11554 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) { 11555 irq_save = true; 11556 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 11557 kfunc_class = IRQ_LOCK_KFUNC; 11558 } else if (meta->func_id == special_kfunc_list[KF_bpf_local_irq_restore] || 11559 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) { 11560 irq_save = false; 11561 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 11562 kfunc_class = IRQ_LOCK_KFUNC; 11563 } else { 11564 verifier_bug(env, "unknown irq flags kfunc"); 11565 return -EFAULT; 11566 } 11567 11568 if (irq_save) { 11569 if (!is_irq_flag_reg_valid_uninit(env, reg)) { 11570 verbose(env, "expected uninitialized irq flag as arg#%d\n", regno - 1); 11571 return -EINVAL; 11572 } 11573 11574 err = check_mem_access(env, env->insn_idx, regno, 0, BPF_DW, BPF_WRITE, -1, false, false); 11575 if (err) 11576 return err; 11577 11578 err = mark_stack_slot_irq_flag(env, meta, reg, env->insn_idx, kfunc_class); 11579 if (err) 11580 return err; 11581 } else { 11582 err = is_irq_flag_reg_valid_init(env, reg); 11583 if (err) { 11584 verbose(env, "expected an initialized irq flag as arg#%d\n", regno - 1); 11585 return err; 11586 } 11587 11588 err = mark_irq_flag_read(env, reg); 11589 if (err) 11590 return err; 11591 11592 err = unmark_stack_slot_irq_flag(env, reg, kfunc_class); 11593 if (err) 11594 return err; 11595 } 11596 return 0; 11597 } 11598 11599 11600 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11601 { 11602 struct btf_record *rec = reg_btf_record(reg); 11603 11604 if (!env->cur_state->active_locks) { 11605 verifier_bug(env, "%s w/o active lock", __func__); 11606 return -EFAULT; 11607 } 11608 11609 if (type_flag(reg->type) & NON_OWN_REF) { 11610 verifier_bug(env, "NON_OWN_REF already set"); 11611 return -EFAULT; 11612 } 11613 11614 reg->type |= NON_OWN_REF; 11615 if (rec->refcount_off >= 0) 11616 reg->type |= MEM_RCU; 11617 11618 return 0; 11619 } 11620 11621 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11622 { 11623 struct bpf_verifier_state *state = env->cur_state; 11624 struct bpf_func_state *unused; 11625 struct bpf_reg_state *reg; 11626 int i; 11627 11628 if (!ref_obj_id) { 11629 verifier_bug(env, "ref_obj_id is zero for owning -> non-owning conversion"); 11630 return -EFAULT; 11631 } 11632 11633 for (i = 0; i < state->acquired_refs; i++) { 11634 if (state->refs[i].id != ref_obj_id) 11635 continue; 11636 11637 /* Clear ref_obj_id here so release_reference doesn't clobber 11638 * the whole reg 11639 */ 11640 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11641 if (reg->ref_obj_id == ref_obj_id) { 11642 reg->ref_obj_id = 0; 11643 ref_set_non_owning(env, reg); 11644 } 11645 })); 11646 return 0; 11647 } 11648 11649 verifier_bug(env, "ref state missing for ref_obj_id"); 11650 return -EFAULT; 11651 } 11652 11653 /* Implementation details: 11654 * 11655 * Each register points to some region of memory, which we define as an 11656 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11657 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11658 * allocation. The lock and the data it protects are colocated in the same 11659 * memory region. 11660 * 11661 * Hence, everytime a register holds a pointer value pointing to such 11662 * allocation, the verifier preserves a unique reg->id for it. 11663 * 11664 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11665 * bpf_spin_lock is called. 11666 * 11667 * To enable this, lock state in the verifier captures two values: 11668 * active_lock.ptr = Register's type specific pointer 11669 * active_lock.id = A unique ID for each register pointer value 11670 * 11671 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11672 * supported register types. 11673 * 11674 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11675 * allocated objects is the reg->btf pointer. 11676 * 11677 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11678 * can establish the provenance of the map value statically for each distinct 11679 * lookup into such maps. They always contain a single map value hence unique 11680 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11681 * 11682 * So, in case of global variables, they use array maps with max_entries = 1, 11683 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11684 * into the same map value as max_entries is 1, as described above). 11685 * 11686 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11687 * outer map pointer (in verifier context), but each lookup into an inner map 11688 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11689 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11690 * will get different reg->id assigned to each lookup, hence different 11691 * active_lock.id. 11692 * 11693 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11694 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11695 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11696 */ 11697 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11698 { 11699 struct bpf_reference_state *s; 11700 void *ptr; 11701 u32 id; 11702 11703 switch ((int)reg->type) { 11704 case PTR_TO_MAP_VALUE: 11705 ptr = reg->map_ptr; 11706 break; 11707 case PTR_TO_BTF_ID | MEM_ALLOC: 11708 ptr = reg->btf; 11709 break; 11710 default: 11711 verifier_bug(env, "unknown reg type for lock check"); 11712 return -EFAULT; 11713 } 11714 id = reg->id; 11715 11716 if (!env->cur_state->active_locks) 11717 return -EINVAL; 11718 s = find_lock_state(env->cur_state, REF_TYPE_LOCK_MASK, id, ptr); 11719 if (!s) { 11720 verbose(env, "held lock and object are not in the same allocation\n"); 11721 return -EINVAL; 11722 } 11723 return 0; 11724 } 11725 11726 static bool is_bpf_list_api_kfunc(u32 btf_id) 11727 { 11728 return is_bpf_list_push_kfunc(btf_id) || 11729 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11730 btf_id == special_kfunc_list[KF_bpf_list_pop_back] || 11731 btf_id == special_kfunc_list[KF_bpf_list_front] || 11732 btf_id == special_kfunc_list[KF_bpf_list_back]; 11733 } 11734 11735 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11736 { 11737 return is_bpf_rbtree_add_kfunc(btf_id) || 11738 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11739 btf_id == special_kfunc_list[KF_bpf_rbtree_first] || 11740 btf_id == special_kfunc_list[KF_bpf_rbtree_root] || 11741 btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11742 btf_id == special_kfunc_list[KF_bpf_rbtree_right]; 11743 } 11744 11745 static bool is_bpf_iter_num_api_kfunc(u32 btf_id) 11746 { 11747 return btf_id == special_kfunc_list[KF_bpf_iter_num_new] || 11748 btf_id == special_kfunc_list[KF_bpf_iter_num_next] || 11749 btf_id == special_kfunc_list[KF_bpf_iter_num_destroy]; 11750 } 11751 11752 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11753 { 11754 return is_bpf_list_api_kfunc(btf_id) || 11755 is_bpf_rbtree_api_kfunc(btf_id) || 11756 is_bpf_refcount_acquire_kfunc(btf_id); 11757 } 11758 11759 static bool is_bpf_res_spin_lock_kfunc(u32 btf_id) 11760 { 11761 return btf_id == special_kfunc_list[KF_bpf_res_spin_lock] || 11762 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock] || 11763 btf_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 11764 btf_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]; 11765 } 11766 11767 static bool is_bpf_arena_kfunc(u32 btf_id) 11768 { 11769 return btf_id == special_kfunc_list[KF_bpf_arena_alloc_pages] || 11770 btf_id == special_kfunc_list[KF_bpf_arena_free_pages] || 11771 btf_id == special_kfunc_list[KF_bpf_arena_reserve_pages]; 11772 } 11773 11774 static bool is_bpf_stream_kfunc(u32 btf_id) 11775 { 11776 return btf_id == special_kfunc_list[KF_bpf_stream_vprintk] || 11777 btf_id == special_kfunc_list[KF_bpf_stream_print_stack]; 11778 } 11779 11780 static bool kfunc_spin_allowed(u32 btf_id) 11781 { 11782 return is_bpf_graph_api_kfunc(btf_id) || is_bpf_iter_num_api_kfunc(btf_id) || 11783 is_bpf_res_spin_lock_kfunc(btf_id) || is_bpf_arena_kfunc(btf_id) || 11784 is_bpf_stream_kfunc(btf_id); 11785 } 11786 11787 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11788 { 11789 return is_bpf_rbtree_add_kfunc(btf_id); 11790 } 11791 11792 static bool is_async_callback_calling_kfunc(u32 btf_id) 11793 { 11794 return is_bpf_wq_set_callback_kfunc(btf_id) || 11795 is_task_work_add_kfunc(btf_id); 11796 } 11797 11798 bool bpf_is_throw_kfunc(struct bpf_insn *insn) 11799 { 11800 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11801 insn->imm == special_kfunc_list[KF_bpf_throw]; 11802 } 11803 11804 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id) 11805 { 11806 return btf_id == special_kfunc_list[KF_bpf_wq_set_callback]; 11807 } 11808 11809 static bool is_callback_calling_kfunc(u32 btf_id) 11810 { 11811 return is_sync_callback_calling_kfunc(btf_id) || 11812 is_async_callback_calling_kfunc(btf_id); 11813 } 11814 11815 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11816 { 11817 return is_bpf_rbtree_api_kfunc(btf_id); 11818 } 11819 11820 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11821 enum btf_field_type head_field_type, 11822 u32 kfunc_btf_id) 11823 { 11824 bool ret; 11825 11826 switch (head_field_type) { 11827 case BPF_LIST_HEAD: 11828 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11829 break; 11830 case BPF_RB_ROOT: 11831 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11832 break; 11833 default: 11834 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11835 btf_field_type_name(head_field_type)); 11836 return false; 11837 } 11838 11839 if (!ret) 11840 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11841 btf_field_type_name(head_field_type)); 11842 return ret; 11843 } 11844 11845 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11846 enum btf_field_type node_field_type, 11847 u32 kfunc_btf_id) 11848 { 11849 bool ret; 11850 11851 switch (node_field_type) { 11852 case BPF_LIST_NODE: 11853 ret = is_bpf_list_push_kfunc(kfunc_btf_id); 11854 break; 11855 case BPF_RB_NODE: 11856 ret = (is_bpf_rbtree_add_kfunc(kfunc_btf_id) || 11857 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11858 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_left] || 11859 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]); 11860 break; 11861 default: 11862 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11863 btf_field_type_name(node_field_type)); 11864 return false; 11865 } 11866 11867 if (!ret) 11868 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11869 btf_field_type_name(node_field_type)); 11870 return ret; 11871 } 11872 11873 static int 11874 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11875 struct bpf_reg_state *reg, u32 regno, 11876 struct bpf_kfunc_call_arg_meta *meta, 11877 enum btf_field_type head_field_type, 11878 struct btf_field **head_field) 11879 { 11880 const char *head_type_name; 11881 struct btf_field *field; 11882 struct btf_record *rec; 11883 u32 head_off; 11884 11885 if (meta->btf != btf_vmlinux) { 11886 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11887 return -EFAULT; 11888 } 11889 11890 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11891 return -EFAULT; 11892 11893 head_type_name = btf_field_type_name(head_field_type); 11894 if (!tnum_is_const(reg->var_off)) { 11895 verbose(env, 11896 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11897 regno, head_type_name); 11898 return -EINVAL; 11899 } 11900 11901 rec = reg_btf_record(reg); 11902 head_off = reg->var_off.value; 11903 field = btf_record_find(rec, head_off, head_field_type); 11904 if (!field) { 11905 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11906 return -EINVAL; 11907 } 11908 11909 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11910 if (check_reg_allocation_locked(env, reg)) { 11911 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11912 rec->spin_lock_off, head_type_name); 11913 return -EINVAL; 11914 } 11915 11916 if (*head_field) { 11917 verifier_bug(env, "repeating %s arg", head_type_name); 11918 return -EFAULT; 11919 } 11920 *head_field = field; 11921 return 0; 11922 } 11923 11924 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11925 struct bpf_reg_state *reg, u32 regno, 11926 struct bpf_kfunc_call_arg_meta *meta) 11927 { 11928 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11929 &meta->arg_list_head.field); 11930 } 11931 11932 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11933 struct bpf_reg_state *reg, u32 regno, 11934 struct bpf_kfunc_call_arg_meta *meta) 11935 { 11936 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11937 &meta->arg_rbtree_root.field); 11938 } 11939 11940 static int 11941 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11942 struct bpf_reg_state *reg, u32 regno, 11943 struct bpf_kfunc_call_arg_meta *meta, 11944 enum btf_field_type head_field_type, 11945 enum btf_field_type node_field_type, 11946 struct btf_field **node_field) 11947 { 11948 const char *node_type_name; 11949 const struct btf_type *et, *t; 11950 struct btf_field *field; 11951 u32 node_off; 11952 11953 if (meta->btf != btf_vmlinux) { 11954 verifier_bug(env, "unexpected btf mismatch in kfunc call"); 11955 return -EFAULT; 11956 } 11957 11958 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11959 return -EFAULT; 11960 11961 node_type_name = btf_field_type_name(node_field_type); 11962 if (!tnum_is_const(reg->var_off)) { 11963 verbose(env, 11964 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11965 regno, node_type_name); 11966 return -EINVAL; 11967 } 11968 11969 node_off = reg->var_off.value; 11970 field = reg_find_field_offset(reg, node_off, node_field_type); 11971 if (!field) { 11972 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11973 return -EINVAL; 11974 } 11975 11976 field = *node_field; 11977 11978 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11979 t = btf_type_by_id(reg->btf, reg->btf_id); 11980 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11981 field->graph_root.value_btf_id, true)) { 11982 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11983 "in struct %s, but arg is at offset=%d in struct %s\n", 11984 btf_field_type_name(head_field_type), 11985 btf_field_type_name(node_field_type), 11986 field->graph_root.node_offset, 11987 btf_name_by_offset(field->graph_root.btf, et->name_off), 11988 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11989 return -EINVAL; 11990 } 11991 meta->arg_btf = reg->btf; 11992 meta->arg_btf_id = reg->btf_id; 11993 11994 if (node_off != field->graph_root.node_offset) { 11995 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11996 node_off, btf_field_type_name(node_field_type), 11997 field->graph_root.node_offset, 11998 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11999 return -EINVAL; 12000 } 12001 12002 return 0; 12003 } 12004 12005 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 12006 struct bpf_reg_state *reg, u32 regno, 12007 struct bpf_kfunc_call_arg_meta *meta) 12008 { 12009 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 12010 BPF_LIST_HEAD, BPF_LIST_NODE, 12011 &meta->arg_list_head.field); 12012 } 12013 12014 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 12015 struct bpf_reg_state *reg, u32 regno, 12016 struct bpf_kfunc_call_arg_meta *meta) 12017 { 12018 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 12019 BPF_RB_ROOT, BPF_RB_NODE, 12020 &meta->arg_rbtree_root.field); 12021 } 12022 12023 /* 12024 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 12025 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 12026 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 12027 * them can only be attached to some specific hook points. 12028 */ 12029 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 12030 { 12031 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12032 12033 switch (prog_type) { 12034 case BPF_PROG_TYPE_LSM: 12035 return true; 12036 case BPF_PROG_TYPE_TRACING: 12037 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 12038 return true; 12039 fallthrough; 12040 default: 12041 return in_sleepable(env); 12042 } 12043 } 12044 12045 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 12046 int insn_idx) 12047 { 12048 const char *func_name = meta->func_name, *ref_tname; 12049 const struct btf *btf = meta->btf; 12050 const struct btf_param *args; 12051 struct btf_record *rec; 12052 u32 i, nargs; 12053 int ret; 12054 12055 args = (const struct btf_param *)(meta->func_proto + 1); 12056 nargs = btf_type_vlen(meta->func_proto); 12057 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 12058 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 12059 MAX_BPF_FUNC_REG_ARGS); 12060 return -EINVAL; 12061 } 12062 12063 /* Check that BTF function arguments match actual types that the 12064 * verifier sees. 12065 */ 12066 for (i = 0; i < nargs; i++) { 12067 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 12068 const struct btf_type *t, *ref_t, *resolve_ret; 12069 enum bpf_arg_type arg_type = ARG_DONTCARE; 12070 u32 regno = i + 1, ref_id, type_size; 12071 bool is_ret_buf_sz = false; 12072 int kf_arg_type; 12073 12074 if (is_kfunc_arg_prog_aux(btf, &args[i])) { 12075 /* Reject repeated use bpf_prog_aux */ 12076 if (meta->arg_prog) { 12077 verifier_bug(env, "Only 1 prog->aux argument supported per-kfunc"); 12078 return -EFAULT; 12079 } 12080 meta->arg_prog = true; 12081 cur_aux(env)->arg_prog = regno; 12082 continue; 12083 } 12084 12085 if (is_kfunc_arg_ignore(btf, &args[i]) || is_kfunc_arg_implicit(meta, i)) 12086 continue; 12087 12088 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 12089 12090 if (btf_type_is_scalar(t)) { 12091 if (reg->type != SCALAR_VALUE) { 12092 verbose(env, "R%d is not a scalar\n", regno); 12093 return -EINVAL; 12094 } 12095 12096 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 12097 if (meta->arg_constant.found) { 12098 verifier_bug(env, "only one constant argument permitted"); 12099 return -EFAULT; 12100 } 12101 if (!tnum_is_const(reg->var_off)) { 12102 verbose(env, "R%d must be a known constant\n", regno); 12103 return -EINVAL; 12104 } 12105 ret = mark_chain_precision(env, regno); 12106 if (ret < 0) 12107 return ret; 12108 meta->arg_constant.found = true; 12109 meta->arg_constant.value = reg->var_off.value; 12110 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 12111 meta->r0_rdonly = true; 12112 is_ret_buf_sz = true; 12113 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 12114 is_ret_buf_sz = true; 12115 } 12116 12117 if (is_ret_buf_sz) { 12118 if (meta->r0_size) { 12119 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 12120 return -EINVAL; 12121 } 12122 12123 if (!tnum_is_const(reg->var_off)) { 12124 verbose(env, "R%d is not a const\n", regno); 12125 return -EINVAL; 12126 } 12127 12128 meta->r0_size = reg->var_off.value; 12129 ret = mark_chain_precision(env, regno); 12130 if (ret) 12131 return ret; 12132 } 12133 continue; 12134 } 12135 12136 if (!btf_type_is_ptr(t)) { 12137 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 12138 return -EINVAL; 12139 } 12140 12141 if ((bpf_register_is_null(reg) || type_may_be_null(reg->type)) && 12142 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 12143 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 12144 return -EACCES; 12145 } 12146 12147 if (reg->ref_obj_id) { 12148 if (is_kfunc_release(meta) && meta->ref_obj_id) { 12149 verifier_bug(env, "more than one arg with ref_obj_id R%d %u %u", 12150 regno, reg->ref_obj_id, 12151 meta->ref_obj_id); 12152 return -EFAULT; 12153 } 12154 meta->ref_obj_id = reg->ref_obj_id; 12155 if (is_kfunc_release(meta)) 12156 meta->release_regno = regno; 12157 } 12158 12159 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 12160 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12161 12162 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 12163 if (kf_arg_type < 0) 12164 return kf_arg_type; 12165 12166 switch (kf_arg_type) { 12167 case KF_ARG_PTR_TO_NULL: 12168 continue; 12169 case KF_ARG_PTR_TO_MAP: 12170 if (!reg->map_ptr) { 12171 verbose(env, "pointer in R%d isn't map pointer\n", regno); 12172 return -EINVAL; 12173 } 12174 if (meta->map.ptr && (reg->map_ptr->record->wq_off >= 0 || 12175 reg->map_ptr->record->task_work_off >= 0)) { 12176 /* Use map_uid (which is unique id of inner map) to reject: 12177 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 12178 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 12179 * if (inner_map1 && inner_map2) { 12180 * wq = bpf_map_lookup_elem(inner_map1); 12181 * if (wq) 12182 * // mismatch would have been allowed 12183 * bpf_wq_init(wq, inner_map2); 12184 * } 12185 * 12186 * Comparing map_ptr is enough to distinguish normal and outer maps. 12187 */ 12188 if (meta->map.ptr != reg->map_ptr || 12189 meta->map.uid != reg->map_uid) { 12190 if (reg->map_ptr->record->task_work_off >= 0) { 12191 verbose(env, 12192 "bpf_task_work pointer in R2 map_uid=%d doesn't match map pointer in R3 map_uid=%d\n", 12193 meta->map.uid, reg->map_uid); 12194 return -EINVAL; 12195 } 12196 verbose(env, 12197 "workqueue pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 12198 meta->map.uid, reg->map_uid); 12199 return -EINVAL; 12200 } 12201 } 12202 meta->map.ptr = reg->map_ptr; 12203 meta->map.uid = reg->map_uid; 12204 fallthrough; 12205 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12206 case KF_ARG_PTR_TO_BTF_ID: 12207 if (!is_trusted_reg(reg)) { 12208 if (!is_kfunc_rcu(meta)) { 12209 verbose(env, "R%d must be referenced or trusted\n", regno); 12210 return -EINVAL; 12211 } 12212 if (!is_rcu_reg(reg)) { 12213 verbose(env, "R%d must be a rcu pointer\n", regno); 12214 return -EINVAL; 12215 } 12216 } 12217 fallthrough; 12218 case KF_ARG_PTR_TO_DYNPTR: 12219 case KF_ARG_PTR_TO_ITER: 12220 case KF_ARG_PTR_TO_LIST_HEAD: 12221 case KF_ARG_PTR_TO_LIST_NODE: 12222 case KF_ARG_PTR_TO_RB_ROOT: 12223 case KF_ARG_PTR_TO_RB_NODE: 12224 case KF_ARG_PTR_TO_MEM: 12225 case KF_ARG_PTR_TO_MEM_SIZE: 12226 case KF_ARG_PTR_TO_CALLBACK: 12227 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12228 case KF_ARG_PTR_TO_CONST_STR: 12229 case KF_ARG_PTR_TO_WORKQUEUE: 12230 case KF_ARG_PTR_TO_TIMER: 12231 case KF_ARG_PTR_TO_TASK_WORK: 12232 case KF_ARG_PTR_TO_IRQ_FLAG: 12233 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12234 break; 12235 case KF_ARG_PTR_TO_CTX: 12236 arg_type = ARG_PTR_TO_CTX; 12237 break; 12238 default: 12239 verifier_bug(env, "unknown kfunc arg type %d", kf_arg_type); 12240 return -EFAULT; 12241 } 12242 12243 if (is_kfunc_release(meta) && reg->ref_obj_id) 12244 arg_type |= OBJ_RELEASE; 12245 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 12246 if (ret < 0) 12247 return ret; 12248 12249 switch (kf_arg_type) { 12250 case KF_ARG_PTR_TO_CTX: 12251 if (reg->type != PTR_TO_CTX) { 12252 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", 12253 i, reg_type_str(env, reg->type)); 12254 return -EINVAL; 12255 } 12256 12257 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12258 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 12259 if (ret < 0) 12260 return -EINVAL; 12261 meta->ret_btf_id = ret; 12262 } 12263 break; 12264 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 12265 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 12266 if (!is_bpf_obj_drop_kfunc(meta->func_id)) { 12267 verbose(env, "arg#%d expected for bpf_obj_drop()\n", i); 12268 return -EINVAL; 12269 } 12270 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 12271 if (!is_bpf_percpu_obj_drop_kfunc(meta->func_id)) { 12272 verbose(env, "arg#%d expected for bpf_percpu_obj_drop()\n", i); 12273 return -EINVAL; 12274 } 12275 } else { 12276 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12277 return -EINVAL; 12278 } 12279 if (!reg->ref_obj_id) { 12280 verbose(env, "allocated object must be referenced\n"); 12281 return -EINVAL; 12282 } 12283 if (meta->btf == btf_vmlinux) { 12284 meta->arg_btf = reg->btf; 12285 meta->arg_btf_id = reg->btf_id; 12286 } 12287 break; 12288 case KF_ARG_PTR_TO_DYNPTR: 12289 { 12290 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 12291 int clone_ref_obj_id = 0; 12292 12293 if (reg->type == CONST_PTR_TO_DYNPTR) 12294 dynptr_arg_type |= MEM_RDONLY; 12295 12296 if (is_kfunc_arg_uninit(btf, &args[i])) 12297 dynptr_arg_type |= MEM_UNINIT; 12298 12299 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 12300 dynptr_arg_type |= DYNPTR_TYPE_SKB; 12301 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 12302 dynptr_arg_type |= DYNPTR_TYPE_XDP; 12303 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) { 12304 dynptr_arg_type |= DYNPTR_TYPE_SKB_META; 12305 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 12306 dynptr_arg_type |= DYNPTR_TYPE_FILE; 12307 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) { 12308 dynptr_arg_type |= DYNPTR_TYPE_FILE; 12309 meta->release_regno = regno; 12310 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 12311 (dynptr_arg_type & MEM_UNINIT)) { 12312 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 12313 12314 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 12315 verifier_bug(env, "no dynptr type for parent of clone"); 12316 return -EFAULT; 12317 } 12318 12319 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 12320 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 12321 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 12322 verifier_bug(env, "missing ref obj id for parent of clone"); 12323 return -EFAULT; 12324 } 12325 } 12326 12327 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 12328 if (ret < 0) 12329 return ret; 12330 12331 if (!(dynptr_arg_type & MEM_UNINIT)) { 12332 int id = dynptr_id(env, reg); 12333 12334 if (id < 0) { 12335 verifier_bug(env, "failed to obtain dynptr id"); 12336 return id; 12337 } 12338 meta->initialized_dynptr.id = id; 12339 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 12340 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 12341 } 12342 12343 break; 12344 } 12345 case KF_ARG_PTR_TO_ITER: 12346 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 12347 if (!check_css_task_iter_allowlist(env)) { 12348 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 12349 return -EINVAL; 12350 } 12351 } 12352 ret = process_iter_arg(env, regno, insn_idx, meta); 12353 if (ret < 0) 12354 return ret; 12355 break; 12356 case KF_ARG_PTR_TO_LIST_HEAD: 12357 if (reg->type != PTR_TO_MAP_VALUE && 12358 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12359 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12360 return -EINVAL; 12361 } 12362 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12363 verbose(env, "allocated object must be referenced\n"); 12364 return -EINVAL; 12365 } 12366 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 12367 if (ret < 0) 12368 return ret; 12369 break; 12370 case KF_ARG_PTR_TO_RB_ROOT: 12371 if (reg->type != PTR_TO_MAP_VALUE && 12372 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12373 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 12374 return -EINVAL; 12375 } 12376 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 12377 verbose(env, "allocated object must be referenced\n"); 12378 return -EINVAL; 12379 } 12380 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 12381 if (ret < 0) 12382 return ret; 12383 break; 12384 case KF_ARG_PTR_TO_LIST_NODE: 12385 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12386 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12387 return -EINVAL; 12388 } 12389 if (!reg->ref_obj_id) { 12390 verbose(env, "allocated object must be referenced\n"); 12391 return -EINVAL; 12392 } 12393 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 12394 if (ret < 0) 12395 return ret; 12396 break; 12397 case KF_ARG_PTR_TO_RB_NODE: 12398 if (is_bpf_rbtree_add_kfunc(meta->func_id)) { 12399 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12400 verbose(env, "arg#%d expected pointer to allocated object\n", i); 12401 return -EINVAL; 12402 } 12403 if (!reg->ref_obj_id) { 12404 verbose(env, "allocated object must be referenced\n"); 12405 return -EINVAL; 12406 } 12407 } else { 12408 if (!type_is_non_owning_ref(reg->type) && !reg->ref_obj_id) { 12409 verbose(env, "%s can only take non-owning or refcounted bpf_rb_node pointer\n", func_name); 12410 return -EINVAL; 12411 } 12412 if (in_rbtree_lock_required_cb(env)) { 12413 verbose(env, "%s not allowed in rbtree cb\n", func_name); 12414 return -EINVAL; 12415 } 12416 } 12417 12418 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 12419 if (ret < 0) 12420 return ret; 12421 break; 12422 case KF_ARG_PTR_TO_MAP: 12423 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 12424 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 12425 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 12426 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 12427 fallthrough; 12428 case KF_ARG_PTR_TO_BTF_ID: 12429 /* Only base_type is checked, further checks are done here */ 12430 if ((base_type(reg->type) != PTR_TO_BTF_ID || 12431 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 12432 !reg2btf_ids[base_type(reg->type)]) { 12433 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 12434 verbose(env, "expected %s or socket\n", 12435 reg_type_str(env, base_type(reg->type) | 12436 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 12437 return -EINVAL; 12438 } 12439 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 12440 if (ret < 0) 12441 return ret; 12442 break; 12443 case KF_ARG_PTR_TO_MEM: 12444 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 12445 if (IS_ERR(resolve_ret)) { 12446 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 12447 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 12448 return -EINVAL; 12449 } 12450 ret = check_mem_reg(env, reg, regno, type_size); 12451 if (ret < 0) 12452 return ret; 12453 break; 12454 case KF_ARG_PTR_TO_MEM_SIZE: 12455 { 12456 struct bpf_reg_state *buff_reg = ®s[regno]; 12457 const struct btf_param *buff_arg = &args[i]; 12458 struct bpf_reg_state *size_reg = ®s[regno + 1]; 12459 const struct btf_param *size_arg = &args[i + 1]; 12460 12461 if (!bpf_register_is_null(buff_reg) || !is_kfunc_arg_nullable(meta->btf, buff_arg)) { 12462 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 12463 if (ret < 0) { 12464 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 12465 return ret; 12466 } 12467 } 12468 12469 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 12470 if (meta->arg_constant.found) { 12471 verifier_bug(env, "only one constant argument permitted"); 12472 return -EFAULT; 12473 } 12474 if (!tnum_is_const(size_reg->var_off)) { 12475 verbose(env, "R%d must be a known constant\n", regno + 1); 12476 return -EINVAL; 12477 } 12478 meta->arg_constant.found = true; 12479 meta->arg_constant.value = size_reg->var_off.value; 12480 } 12481 12482 /* Skip next '__sz' or '__szk' argument */ 12483 i++; 12484 break; 12485 } 12486 case KF_ARG_PTR_TO_CALLBACK: 12487 if (reg->type != PTR_TO_FUNC) { 12488 verbose(env, "arg%d expected pointer to func\n", i); 12489 return -EINVAL; 12490 } 12491 meta->subprogno = reg->subprogno; 12492 break; 12493 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12494 if (!type_is_ptr_alloc_obj(reg->type)) { 12495 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 12496 return -EINVAL; 12497 } 12498 if (!type_is_non_owning_ref(reg->type)) 12499 meta->arg_owning_ref = true; 12500 12501 rec = reg_btf_record(reg); 12502 if (!rec) { 12503 verifier_bug(env, "Couldn't find btf_record"); 12504 return -EFAULT; 12505 } 12506 12507 if (rec->refcount_off < 0) { 12508 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 12509 return -EINVAL; 12510 } 12511 12512 meta->arg_btf = reg->btf; 12513 meta->arg_btf_id = reg->btf_id; 12514 break; 12515 case KF_ARG_PTR_TO_CONST_STR: 12516 if (reg->type != PTR_TO_MAP_VALUE) { 12517 verbose(env, "arg#%d doesn't point to a const string\n", i); 12518 return -EINVAL; 12519 } 12520 ret = check_reg_const_str(env, reg, regno); 12521 if (ret) 12522 return ret; 12523 break; 12524 case KF_ARG_PTR_TO_WORKQUEUE: 12525 if (reg->type != PTR_TO_MAP_VALUE) { 12526 verbose(env, "arg#%d doesn't point to a map value\n", i); 12527 return -EINVAL; 12528 } 12529 ret = check_map_field_pointer(env, regno, BPF_WORKQUEUE, &meta->map); 12530 if (ret < 0) 12531 return ret; 12532 break; 12533 case KF_ARG_PTR_TO_TIMER: 12534 if (reg->type != PTR_TO_MAP_VALUE) { 12535 verbose(env, "arg#%d doesn't point to a map value\n", i); 12536 return -EINVAL; 12537 } 12538 ret = process_timer_kfunc(env, regno, meta); 12539 if (ret < 0) 12540 return ret; 12541 break; 12542 case KF_ARG_PTR_TO_TASK_WORK: 12543 if (reg->type != PTR_TO_MAP_VALUE) { 12544 verbose(env, "arg#%d doesn't point to a map value\n", i); 12545 return -EINVAL; 12546 } 12547 ret = check_map_field_pointer(env, regno, BPF_TASK_WORK, &meta->map); 12548 if (ret < 0) 12549 return ret; 12550 break; 12551 case KF_ARG_PTR_TO_IRQ_FLAG: 12552 if (reg->type != PTR_TO_STACK) { 12553 verbose(env, "arg#%d doesn't point to an irq flag on stack\n", i); 12554 return -EINVAL; 12555 } 12556 ret = process_irq_flag(env, regno, meta); 12557 if (ret < 0) 12558 return ret; 12559 break; 12560 case KF_ARG_PTR_TO_RES_SPIN_LOCK: 12561 { 12562 int flags = PROCESS_RES_LOCK; 12563 12564 if (reg->type != PTR_TO_MAP_VALUE && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 12565 verbose(env, "arg#%d doesn't point to map value or allocated object\n", i); 12566 return -EINVAL; 12567 } 12568 12569 if (!is_bpf_res_spin_lock_kfunc(meta->func_id)) 12570 return -EFAULT; 12571 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 12572 meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave]) 12573 flags |= PROCESS_SPIN_LOCK; 12574 if (meta->func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave] || 12575 meta->func_id == special_kfunc_list[KF_bpf_res_spin_unlock_irqrestore]) 12576 flags |= PROCESS_LOCK_IRQ; 12577 ret = process_spin_lock(env, regno, flags); 12578 if (ret < 0) 12579 return ret; 12580 break; 12581 } 12582 } 12583 } 12584 12585 if (is_kfunc_release(meta) && !meta->release_regno) { 12586 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 12587 func_name); 12588 return -EINVAL; 12589 } 12590 12591 return 0; 12592 } 12593 12594 int bpf_fetch_kfunc_arg_meta(struct bpf_verifier_env *env, 12595 s32 func_id, 12596 s16 offset, 12597 struct bpf_kfunc_call_arg_meta *meta) 12598 { 12599 struct bpf_kfunc_meta kfunc; 12600 int err; 12601 12602 err = fetch_kfunc_meta(env, func_id, offset, &kfunc); 12603 if (err) 12604 return err; 12605 12606 memset(meta, 0, sizeof(*meta)); 12607 meta->btf = kfunc.btf; 12608 meta->func_id = kfunc.id; 12609 meta->func_proto = kfunc.proto; 12610 meta->func_name = kfunc.name; 12611 12612 if (!kfunc.flags || !btf_kfunc_is_allowed(kfunc.btf, kfunc.id, env->prog)) 12613 return -EACCES; 12614 12615 meta->kfunc_flags = *kfunc.flags; 12616 12617 return 0; 12618 } 12619 12620 /* 12621 * Determine how many bytes a helper accesses through a stack pointer at 12622 * argument position @arg (0-based, corresponding to R1-R5). 12623 * 12624 * Returns: 12625 * > 0 known read access size in bytes 12626 * 0 doesn't read anything directly 12627 * S64_MIN unknown 12628 * < 0 known write access of (-return) bytes 12629 */ 12630 s64 bpf_helper_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12631 int arg, int insn_idx) 12632 { 12633 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12634 const struct bpf_func_proto *fn; 12635 enum bpf_arg_type at; 12636 s64 size; 12637 12638 if (bpf_get_helper_proto(env, insn->imm, &fn) < 0) 12639 return S64_MIN; 12640 12641 at = fn->arg_type[arg]; 12642 12643 switch (base_type(at)) { 12644 case ARG_PTR_TO_MAP_KEY: 12645 case ARG_PTR_TO_MAP_VALUE: { 12646 bool is_key = base_type(at) == ARG_PTR_TO_MAP_KEY; 12647 u64 val; 12648 int i, map_reg; 12649 12650 for (i = 0; i < arg; i++) { 12651 if (base_type(fn->arg_type[i]) == ARG_CONST_MAP_PTR) 12652 break; 12653 } 12654 if (i >= arg) 12655 goto scan_all_maps; 12656 12657 map_reg = BPF_REG_1 + i; 12658 12659 if (!(aux->const_reg_map_mask & BIT(map_reg))) 12660 goto scan_all_maps; 12661 12662 i = aux->const_reg_vals[map_reg]; 12663 if (i < env->used_map_cnt) { 12664 size = is_key ? env->used_maps[i]->key_size 12665 : env->used_maps[i]->value_size; 12666 goto out; 12667 } 12668 scan_all_maps: 12669 /* 12670 * Map pointer is not known at this call site (e.g. different 12671 * maps on merged paths). Conservatively return the largest 12672 * key_size or value_size across all maps used by the program. 12673 */ 12674 val = 0; 12675 for (i = 0; i < env->used_map_cnt; i++) { 12676 struct bpf_map *map = env->used_maps[i]; 12677 u32 sz = is_key ? map->key_size : map->value_size; 12678 12679 if (sz > val) 12680 val = sz; 12681 if (map->inner_map_meta) { 12682 sz = is_key ? map->inner_map_meta->key_size 12683 : map->inner_map_meta->value_size; 12684 if (sz > val) 12685 val = sz; 12686 } 12687 } 12688 if (!val) 12689 return S64_MIN; 12690 size = val; 12691 goto out; 12692 } 12693 case ARG_PTR_TO_MEM: 12694 if (at & MEM_FIXED_SIZE) { 12695 size = fn->arg_size[arg]; 12696 goto out; 12697 } 12698 if (arg + 1 < ARRAY_SIZE(fn->arg_type) && 12699 arg_type_is_mem_size(fn->arg_type[arg + 1])) { 12700 int size_reg = BPF_REG_1 + arg + 1; 12701 12702 if (aux->const_reg_mask & BIT(size_reg)) { 12703 size = (s64)aux->const_reg_vals[size_reg]; 12704 goto out; 12705 } 12706 /* 12707 * Size arg is const on each path but differs across merged 12708 * paths. MAX_BPF_STACK is a safe upper bound for reads. 12709 */ 12710 if (at & MEM_UNINIT) 12711 return 0; 12712 return MAX_BPF_STACK; 12713 } 12714 return S64_MIN; 12715 case ARG_PTR_TO_DYNPTR: 12716 size = BPF_DYNPTR_SIZE; 12717 break; 12718 case ARG_PTR_TO_STACK: 12719 /* 12720 * Only used by bpf_calls_callback() helpers. The helper itself 12721 * doesn't access stack. The callback subprog does and it's 12722 * analyzed separately. 12723 */ 12724 return 0; 12725 default: 12726 return S64_MIN; 12727 } 12728 out: 12729 /* 12730 * MEM_UNINIT args are write-only: the helper initializes the 12731 * buffer without reading it. 12732 */ 12733 if (at & MEM_UNINIT) 12734 return -size; 12735 return size; 12736 } 12737 12738 /* 12739 * Determine how many bytes a kfunc accesses through a stack pointer at 12740 * argument position @arg (0-based, corresponding to R1-R5). 12741 * 12742 * Returns: 12743 * > 0 known read access size in bytes 12744 * 0 doesn't access memory through that argument (ex: not a pointer) 12745 * S64_MIN unknown 12746 * < 0 known write access of (-return) bytes 12747 */ 12748 s64 bpf_kfunc_stack_access_bytes(struct bpf_verifier_env *env, struct bpf_insn *insn, 12749 int arg, int insn_idx) 12750 { 12751 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 12752 struct bpf_kfunc_call_arg_meta meta; 12753 const struct btf_param *args; 12754 const struct btf_type *t, *ref_t; 12755 const struct btf *btf; 12756 u32 nargs, type_size; 12757 s64 size; 12758 12759 if (bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) < 0) 12760 return S64_MIN; 12761 12762 btf = meta.btf; 12763 args = btf_params(meta.func_proto); 12764 nargs = btf_type_vlen(meta.func_proto); 12765 if (arg >= nargs) 12766 return 0; 12767 12768 t = btf_type_skip_modifiers(btf, args[arg].type, NULL); 12769 if (!btf_type_is_ptr(t)) 12770 return 0; 12771 12772 /* dynptr: fixed 16-byte on-stack representation */ 12773 if (is_kfunc_arg_dynptr(btf, &args[arg])) { 12774 size = BPF_DYNPTR_SIZE; 12775 goto out; 12776 } 12777 12778 /* ptr + __sz/__szk pair: size is in the next register */ 12779 if (arg + 1 < nargs && 12780 (btf_param_match_suffix(btf, &args[arg + 1], "__sz") || 12781 btf_param_match_suffix(btf, &args[arg + 1], "__szk"))) { 12782 int size_reg = BPF_REG_1 + arg + 1; 12783 12784 if (aux->const_reg_mask & BIT(size_reg)) { 12785 size = (s64)aux->const_reg_vals[size_reg]; 12786 goto out; 12787 } 12788 return MAX_BPF_STACK; 12789 } 12790 12791 /* fixed-size pointed-to type: resolve via BTF */ 12792 ref_t = btf_type_skip_modifiers(btf, t->type, NULL); 12793 if (!IS_ERR(btf_resolve_size(btf, ref_t, &type_size))) { 12794 size = type_size; 12795 goto out; 12796 } 12797 12798 return S64_MIN; 12799 out: 12800 /* KF_ITER_NEW kfuncs initialize the iterator state at arg 0 */ 12801 if (arg == 0 && meta.kfunc_flags & KF_ITER_NEW) 12802 return -size; 12803 if (is_kfunc_arg_uninit(btf, &args[arg])) 12804 return -size; 12805 return size; 12806 } 12807 12808 /* check special kfuncs and return: 12809 * 1 - not fall-through to 'else' branch, continue verification 12810 * 0 - fall-through to 'else' branch 12811 * < 0 - not fall-through to 'else' branch, return error 12812 */ 12813 static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 12814 struct bpf_reg_state *regs, struct bpf_insn_aux_data *insn_aux, 12815 const struct btf_type *ptr_type, struct btf *desc_btf) 12816 { 12817 const struct btf_type *ret_t; 12818 int err = 0; 12819 12820 if (meta->btf != btf_vmlinux) 12821 return 0; 12822 12823 if (is_bpf_obj_new_kfunc(meta->func_id) || is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12824 struct btf_struct_meta *struct_meta; 12825 struct btf *ret_btf; 12826 u32 ret_btf_id; 12827 12828 if (is_bpf_obj_new_kfunc(meta->func_id) && !bpf_global_ma_set) 12829 return -ENOMEM; 12830 12831 if (((u64)(u32)meta->arg_constant.value) != meta->arg_constant.value) { 12832 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12833 return -EINVAL; 12834 } 12835 12836 ret_btf = env->prog->aux->btf; 12837 ret_btf_id = meta->arg_constant.value; 12838 12839 /* This may be NULL due to user not supplying a BTF */ 12840 if (!ret_btf) { 12841 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12842 return -EINVAL; 12843 } 12844 12845 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12846 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12847 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12848 return -EINVAL; 12849 } 12850 12851 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12852 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12853 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12854 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12855 return -EINVAL; 12856 } 12857 12858 if (!bpf_global_percpu_ma_set) { 12859 mutex_lock(&bpf_percpu_ma_lock); 12860 if (!bpf_global_percpu_ma_set) { 12861 /* Charge memory allocated with bpf_global_percpu_ma to 12862 * root memcg. The obj_cgroup for root memcg is NULL. 12863 */ 12864 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12865 if (!err) 12866 bpf_global_percpu_ma_set = true; 12867 } 12868 mutex_unlock(&bpf_percpu_ma_lock); 12869 if (err) 12870 return err; 12871 } 12872 12873 mutex_lock(&bpf_percpu_ma_lock); 12874 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12875 mutex_unlock(&bpf_percpu_ma_lock); 12876 if (err) 12877 return err; 12878 } 12879 12880 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12881 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) { 12882 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12883 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12884 return -EINVAL; 12885 } 12886 12887 if (struct_meta) { 12888 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12889 return -EINVAL; 12890 } 12891 } 12892 12893 mark_reg_known_zero(env, regs, BPF_REG_0); 12894 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12895 regs[BPF_REG_0].btf = ret_btf; 12896 regs[BPF_REG_0].btf_id = ret_btf_id; 12897 if (is_bpf_percpu_obj_new_kfunc(meta->func_id)) 12898 regs[BPF_REG_0].type |= MEM_PERCPU; 12899 12900 insn_aux->obj_new_size = ret_t->size; 12901 insn_aux->kptr_struct_meta = struct_meta; 12902 } else if (is_bpf_refcount_acquire_kfunc(meta->func_id)) { 12903 mark_reg_known_zero(env, regs, BPF_REG_0); 12904 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12905 regs[BPF_REG_0].btf = meta->arg_btf; 12906 regs[BPF_REG_0].btf_id = meta->arg_btf_id; 12907 12908 insn_aux->kptr_struct_meta = 12909 btf_find_struct_meta(meta->arg_btf, 12910 meta->arg_btf_id); 12911 } else if (is_list_node_type(ptr_type)) { 12912 struct btf_field *field = meta->arg_list_head.field; 12913 12914 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12915 } else if (is_rbtree_node_type(ptr_type)) { 12916 struct btf_field *field = meta->arg_rbtree_root.field; 12917 12918 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12919 } else if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12920 mark_reg_known_zero(env, regs, BPF_REG_0); 12921 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12922 regs[BPF_REG_0].btf = desc_btf; 12923 regs[BPF_REG_0].btf_id = meta->ret_btf_id; 12924 } else if (meta->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12925 ret_t = btf_type_by_id(desc_btf, meta->arg_constant.value); 12926 if (!ret_t) { 12927 verbose(env, "Unknown type ID %lld passed to kfunc bpf_rdonly_cast\n", 12928 meta->arg_constant.value); 12929 return -EINVAL; 12930 } else if (btf_type_is_struct(ret_t)) { 12931 mark_reg_known_zero(env, regs, BPF_REG_0); 12932 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12933 regs[BPF_REG_0].btf = desc_btf; 12934 regs[BPF_REG_0].btf_id = meta->arg_constant.value; 12935 } else if (btf_type_is_void(ret_t)) { 12936 mark_reg_known_zero(env, regs, BPF_REG_0); 12937 regs[BPF_REG_0].type = PTR_TO_MEM | MEM_RDONLY | PTR_UNTRUSTED; 12938 regs[BPF_REG_0].mem_size = 0; 12939 } else { 12940 verbose(env, 12941 "kfunc bpf_rdonly_cast type ID argument must be of a struct or void\n"); 12942 return -EINVAL; 12943 } 12944 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12945 meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12946 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta->initialized_dynptr.type); 12947 12948 mark_reg_known_zero(env, regs, BPF_REG_0); 12949 12950 if (!meta->arg_constant.found) { 12951 verifier_bug(env, "bpf_dynptr_slice(_rdwr) no constant size"); 12952 return -EFAULT; 12953 } 12954 12955 regs[BPF_REG_0].mem_size = meta->arg_constant.value; 12956 12957 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12958 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12959 12960 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12961 regs[BPF_REG_0].type |= MEM_RDONLY; 12962 } else { 12963 /* this will set env->seen_direct_write to true */ 12964 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12965 verbose(env, "the prog does not allow writes to packet data\n"); 12966 return -EINVAL; 12967 } 12968 } 12969 12970 if (!meta->initialized_dynptr.id) { 12971 verifier_bug(env, "no dynptr id"); 12972 return -EFAULT; 12973 } 12974 regs[BPF_REG_0].dynptr_id = meta->initialized_dynptr.id; 12975 12976 /* we don't need to set BPF_REG_0's ref obj id 12977 * because packet slices are not refcounted (see 12978 * dynptr_type_refcounted) 12979 */ 12980 } else { 12981 return 0; 12982 } 12983 12984 return 1; 12985 } 12986 12987 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12988 12989 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12990 int *insn_idx_p) 12991 { 12992 bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable; 12993 u32 i, nargs, ptr_type_id, release_ref_obj_id; 12994 struct bpf_reg_state *regs = cur_regs(env); 12995 const char *func_name, *ptr_type_name; 12996 const struct btf_type *t, *ptr_type; 12997 struct bpf_kfunc_call_arg_meta meta; 12998 struct bpf_insn_aux_data *insn_aux; 12999 int err, insn_idx = *insn_idx_p; 13000 const struct btf_param *args; 13001 struct btf *desc_btf; 13002 13003 /* skip for now, but return error when we find this in fixup_kfunc_call */ 13004 if (!insn->imm) 13005 return 0; 13006 13007 err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta); 13008 if (err == -EACCES && meta.func_name) 13009 verbose(env, "calling kernel function %s is not allowed\n", meta.func_name); 13010 if (err) 13011 return err; 13012 desc_btf = meta.btf; 13013 func_name = meta.func_name; 13014 insn_aux = &env->insn_aux_data[insn_idx]; 13015 13016 insn_aux->is_iter_next = bpf_is_iter_next_kfunc(&meta); 13017 13018 if (!insn->off && 13019 (insn->imm == special_kfunc_list[KF_bpf_res_spin_lock] || 13020 insn->imm == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) { 13021 struct bpf_verifier_state *branch; 13022 struct bpf_reg_state *regs; 13023 13024 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 13025 if (IS_ERR(branch)) { 13026 verbose(env, "failed to push state for failed lock acquisition\n"); 13027 return PTR_ERR(branch); 13028 } 13029 13030 regs = branch->frame[branch->curframe]->regs; 13031 13032 /* Clear r0-r5 registers in forked state */ 13033 for (i = 0; i < CALLER_SAVED_REGS; i++) 13034 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 13035 13036 mark_reg_unknown(env, regs, BPF_REG_0); 13037 err = __mark_reg_s32_range(env, regs, BPF_REG_0, -MAX_ERRNO, -1); 13038 if (err) { 13039 verbose(env, "failed to mark s32 range for retval in forked state for lock\n"); 13040 return err; 13041 } 13042 __mark_btf_func_reg_size(env, regs, BPF_REG_0, sizeof(u32)); 13043 } else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) { 13044 verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n"); 13045 return -EFAULT; 13046 } 13047 13048 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 13049 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 13050 return -EACCES; 13051 } 13052 13053 sleepable = bpf_is_kfunc_sleepable(&meta); 13054 if (sleepable && !in_sleepable(env)) { 13055 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 13056 return -EACCES; 13057 } 13058 13059 /* Track non-sleepable context for kfuncs, same as for helpers. */ 13060 if (!in_sleepable_context(env)) 13061 insn_aux->non_sleepable = true; 13062 13063 /* Check the arguments */ 13064 err = check_kfunc_args(env, &meta, insn_idx); 13065 if (err < 0) 13066 return err; 13067 13068 if (is_bpf_rbtree_add_kfunc(meta.func_id)) { 13069 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13070 set_rbtree_add_callback_state); 13071 if (err) { 13072 verbose(env, "kfunc %s#%d failed callback verification\n", 13073 func_name, meta.func_id); 13074 return err; 13075 } 13076 } 13077 13078 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) { 13079 meta.r0_size = sizeof(u64); 13080 meta.r0_rdonly = false; 13081 } 13082 13083 if (is_bpf_wq_set_callback_kfunc(meta.func_id)) { 13084 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13085 set_timer_callback_state); 13086 if (err) { 13087 verbose(env, "kfunc %s#%d failed callback verification\n", 13088 func_name, meta.func_id); 13089 return err; 13090 } 13091 } 13092 13093 if (is_task_work_add_kfunc(meta.func_id)) { 13094 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 13095 set_task_work_schedule_callback_state); 13096 if (err) { 13097 verbose(env, "kfunc %s#%d failed callback verification\n", 13098 func_name, meta.func_id); 13099 return err; 13100 } 13101 } 13102 13103 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 13104 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 13105 13106 preempt_disable = is_kfunc_bpf_preempt_disable(&meta); 13107 preempt_enable = is_kfunc_bpf_preempt_enable(&meta); 13108 13109 if (rcu_lock) { 13110 env->cur_state->active_rcu_locks++; 13111 } else if (rcu_unlock) { 13112 struct bpf_func_state *state; 13113 struct bpf_reg_state *reg; 13114 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 13115 13116 if (env->cur_state->active_rcu_locks == 0) { 13117 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 13118 return -EINVAL; 13119 } 13120 if (--env->cur_state->active_rcu_locks == 0) { 13121 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 13122 if (reg->type & MEM_RCU) { 13123 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 13124 reg->type |= PTR_UNTRUSTED; 13125 } 13126 })); 13127 } 13128 } else if (preempt_disable) { 13129 env->cur_state->active_preempt_locks++; 13130 } else if (preempt_enable) { 13131 if (env->cur_state->active_preempt_locks == 0) { 13132 verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name); 13133 return -EINVAL; 13134 } 13135 env->cur_state->active_preempt_locks--; 13136 } 13137 13138 if (sleepable && !in_sleepable_context(env)) { 13139 verbose(env, "kernel func %s is sleepable within %s\n", 13140 func_name, non_sleepable_context_description(env)); 13141 return -EACCES; 13142 } 13143 13144 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 13145 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 13146 return -EACCES; 13147 } 13148 13149 if (is_kfunc_rcu_protected(&meta) && !in_rcu_cs(env)) { 13150 verbose(env, "kernel func %s requires RCU critical section protection\n", func_name); 13151 return -EACCES; 13152 } 13153 13154 /* In case of release function, we get register number of refcounted 13155 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 13156 */ 13157 if (meta.release_regno) { 13158 struct bpf_reg_state *reg = ®s[meta.release_regno]; 13159 13160 if (meta.initialized_dynptr.ref_obj_id) { 13161 err = unmark_stack_slots_dynptr(env, reg); 13162 } else { 13163 err = release_reference(env, reg->ref_obj_id); 13164 if (err) 13165 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13166 func_name, meta.func_id); 13167 } 13168 if (err) 13169 return err; 13170 } 13171 13172 if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) { 13173 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 13174 insn_aux->insert_off = regs[BPF_REG_2].var_off.value; 13175 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 13176 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 13177 if (err) { 13178 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 13179 func_name, meta.func_id); 13180 return err; 13181 } 13182 13183 err = release_reference(env, release_ref_obj_id); 13184 if (err) { 13185 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 13186 func_name, meta.func_id); 13187 return err; 13188 } 13189 } 13190 13191 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 13192 if (!bpf_jit_supports_exceptions()) { 13193 verbose(env, "JIT does not support calling kfunc %s#%d\n", 13194 func_name, meta.func_id); 13195 return -ENOTSUPP; 13196 } 13197 env->seen_exception = true; 13198 13199 /* In the case of the default callback, the cookie value passed 13200 * to bpf_throw becomes the return value of the program. 13201 */ 13202 if (!env->exception_callback_subprog) { 13203 err = check_return_code(env, BPF_REG_1, "R1"); 13204 if (err < 0) 13205 return err; 13206 } 13207 } 13208 13209 for (i = 0; i < CALLER_SAVED_REGS; i++) { 13210 u32 regno = caller_saved[i]; 13211 13212 bpf_mark_reg_not_init(env, ®s[regno]); 13213 regs[regno].subreg_def = DEF_NOT_SUBREG; 13214 } 13215 13216 /* Check return type */ 13217 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 13218 13219 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 13220 if (meta.btf != btf_vmlinux || 13221 (!is_bpf_obj_new_kfunc(meta.func_id) && 13222 !is_bpf_percpu_obj_new_kfunc(meta.func_id) && 13223 !is_bpf_refcount_acquire_kfunc(meta.func_id))) { 13224 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 13225 return -EINVAL; 13226 } 13227 } 13228 13229 if (btf_type_is_scalar(t)) { 13230 mark_reg_unknown(env, regs, BPF_REG_0); 13231 if (meta.btf == btf_vmlinux && (meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock] || 13232 meta.func_id == special_kfunc_list[KF_bpf_res_spin_lock_irqsave])) 13233 __mark_reg_const_zero(env, ®s[BPF_REG_0]); 13234 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 13235 } else if (btf_type_is_ptr(t)) { 13236 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 13237 err = check_special_kfunc(env, &meta, regs, insn_aux, ptr_type, desc_btf); 13238 if (err) { 13239 if (err < 0) 13240 return err; 13241 } else if (btf_type_is_void(ptr_type)) { 13242 /* kfunc returning 'void *' is equivalent to returning scalar */ 13243 mark_reg_unknown(env, regs, BPF_REG_0); 13244 } else if (!__btf_type_is_struct(ptr_type)) { 13245 if (!meta.r0_size) { 13246 __u32 sz; 13247 13248 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 13249 meta.r0_size = sz; 13250 meta.r0_rdonly = true; 13251 } 13252 } 13253 if (!meta.r0_size) { 13254 ptr_type_name = btf_name_by_offset(desc_btf, 13255 ptr_type->name_off); 13256 verbose(env, 13257 "kernel function %s returns pointer type %s %s is not supported\n", 13258 func_name, 13259 btf_type_str(ptr_type), 13260 ptr_type_name); 13261 return -EINVAL; 13262 } 13263 13264 mark_reg_known_zero(env, regs, BPF_REG_0); 13265 regs[BPF_REG_0].type = PTR_TO_MEM; 13266 regs[BPF_REG_0].mem_size = meta.r0_size; 13267 13268 if (meta.r0_rdonly) 13269 regs[BPF_REG_0].type |= MEM_RDONLY; 13270 13271 /* Ensures we don't access the memory after a release_reference() */ 13272 if (meta.ref_obj_id) 13273 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 13274 13275 if (is_kfunc_rcu_protected(&meta)) 13276 regs[BPF_REG_0].type |= MEM_RCU; 13277 } else { 13278 enum bpf_reg_type type = PTR_TO_BTF_ID; 13279 13280 if (meta.func_id == special_kfunc_list[KF_bpf_get_kmem_cache]) 13281 type |= PTR_UNTRUSTED; 13282 else if (is_kfunc_rcu_protected(&meta) || 13283 (bpf_is_iter_next_kfunc(&meta) && 13284 (get_iter_from_state(env->cur_state, &meta) 13285 ->type & MEM_RCU))) { 13286 /* 13287 * If the iterator's constructor (the _new 13288 * function e.g., bpf_iter_task_new) has been 13289 * annotated with BPF kfunc flag 13290 * KF_RCU_PROTECTED and was called within a RCU 13291 * read-side critical section, also propagate 13292 * the MEM_RCU flag to the pointer returned from 13293 * the iterator's next function (e.g., 13294 * bpf_iter_task_next). 13295 */ 13296 type |= MEM_RCU; 13297 } else { 13298 /* 13299 * Any PTR_TO_BTF_ID that is returned from a BPF 13300 * kfunc should by default be treated as 13301 * implicitly trusted. 13302 */ 13303 type |= PTR_TRUSTED; 13304 } 13305 13306 mark_reg_known_zero(env, regs, BPF_REG_0); 13307 regs[BPF_REG_0].btf = desc_btf; 13308 regs[BPF_REG_0].type = type; 13309 regs[BPF_REG_0].btf_id = ptr_type_id; 13310 } 13311 13312 if (is_kfunc_ret_null(&meta)) { 13313 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 13314 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 13315 regs[BPF_REG_0].id = ++env->id_gen; 13316 } 13317 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 13318 if (is_kfunc_acquire(&meta)) { 13319 int id = acquire_reference(env, insn_idx); 13320 13321 if (id < 0) 13322 return id; 13323 if (is_kfunc_ret_null(&meta)) 13324 regs[BPF_REG_0].id = id; 13325 regs[BPF_REG_0].ref_obj_id = id; 13326 } else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) { 13327 ref_set_non_owning(env, ®s[BPF_REG_0]); 13328 } 13329 13330 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 13331 regs[BPF_REG_0].id = ++env->id_gen; 13332 } else if (btf_type_is_void(t)) { 13333 if (meta.btf == btf_vmlinux) { 13334 if (is_bpf_obj_drop_kfunc(meta.func_id) || 13335 is_bpf_percpu_obj_drop_kfunc(meta.func_id)) { 13336 insn_aux->kptr_struct_meta = 13337 btf_find_struct_meta(meta.arg_btf, 13338 meta.arg_btf_id); 13339 } 13340 } 13341 } 13342 13343 if (bpf_is_kfunc_pkt_changing(&meta)) 13344 clear_all_pkt_pointers(env); 13345 13346 nargs = btf_type_vlen(meta.func_proto); 13347 args = (const struct btf_param *)(meta.func_proto + 1); 13348 for (i = 0; i < nargs; i++) { 13349 u32 regno = i + 1; 13350 13351 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 13352 if (btf_type_is_ptr(t)) 13353 mark_btf_func_reg_size(env, regno, sizeof(void *)); 13354 else 13355 /* scalar. ensured by check_kfunc_args() */ 13356 mark_btf_func_reg_size(env, regno, t->size); 13357 } 13358 13359 if (bpf_is_iter_next_kfunc(&meta)) { 13360 err = process_iter_next_call(env, insn_idx, &meta); 13361 if (err) 13362 return err; 13363 } 13364 13365 if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie]) 13366 env->prog->call_session_cookie = true; 13367 13368 if (bpf_is_throw_kfunc(insn)) 13369 return process_bpf_exit_full(env, NULL, true); 13370 13371 return 0; 13372 } 13373 13374 static bool check_reg_sane_offset_scalar(struct bpf_verifier_env *env, 13375 const struct bpf_reg_state *reg, 13376 enum bpf_reg_type type) 13377 { 13378 bool known = tnum_is_const(reg->var_off); 13379 s64 val = reg->var_off.value; 13380 s64 smin = reg->smin_value; 13381 13382 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13383 verbose(env, "math between %s pointer and %lld is not allowed\n", 13384 reg_type_str(env, type), val); 13385 return false; 13386 } 13387 13388 if (smin == S64_MIN) { 13389 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 13390 reg_type_str(env, type)); 13391 return false; 13392 } 13393 13394 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13395 verbose(env, "value %lld makes %s pointer be out of bounds\n", 13396 smin, reg_type_str(env, type)); 13397 return false; 13398 } 13399 13400 return true; 13401 } 13402 13403 static bool check_reg_sane_offset_ptr(struct bpf_verifier_env *env, 13404 const struct bpf_reg_state *reg, 13405 enum bpf_reg_type type) 13406 { 13407 bool known = tnum_is_const(reg->var_off); 13408 s64 val = reg->var_off.value; 13409 s64 smin = reg->smin_value; 13410 13411 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 13412 verbose(env, "%s pointer offset %lld is not allowed\n", 13413 reg_type_str(env, type), val); 13414 return false; 13415 } 13416 13417 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 13418 verbose(env, "%s pointer offset %lld is not allowed\n", 13419 reg_type_str(env, type), smin); 13420 return false; 13421 } 13422 13423 return true; 13424 } 13425 13426 enum { 13427 REASON_BOUNDS = -1, 13428 REASON_TYPE = -2, 13429 REASON_PATHS = -3, 13430 REASON_LIMIT = -4, 13431 REASON_STACK = -5, 13432 }; 13433 13434 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 13435 u32 *alu_limit, bool mask_to_left) 13436 { 13437 u32 max = 0, ptr_limit = 0; 13438 13439 switch (ptr_reg->type) { 13440 case PTR_TO_STACK: 13441 /* Offset 0 is out-of-bounds, but acceptable start for the 13442 * left direction, see BPF_REG_FP. Also, unknown scalar 13443 * offset where we would need to deal with min/max bounds is 13444 * currently prohibited for unprivileged. 13445 */ 13446 max = MAX_BPF_STACK + mask_to_left; 13447 ptr_limit = -ptr_reg->var_off.value; 13448 break; 13449 case PTR_TO_MAP_VALUE: 13450 max = ptr_reg->map_ptr->value_size; 13451 ptr_limit = mask_to_left ? ptr_reg->smin_value : ptr_reg->umax_value; 13452 break; 13453 default: 13454 return REASON_TYPE; 13455 } 13456 13457 if (ptr_limit >= max) 13458 return REASON_LIMIT; 13459 *alu_limit = ptr_limit; 13460 return 0; 13461 } 13462 13463 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 13464 const struct bpf_insn *insn) 13465 { 13466 return env->bypass_spec_v1 || 13467 BPF_SRC(insn->code) == BPF_K || 13468 cur_aux(env)->nospec; 13469 } 13470 13471 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 13472 u32 alu_state, u32 alu_limit) 13473 { 13474 /* If we arrived here from different branches with different 13475 * state or limits to sanitize, then this won't work. 13476 */ 13477 if (aux->alu_state && 13478 (aux->alu_state != alu_state || 13479 aux->alu_limit != alu_limit)) 13480 return REASON_PATHS; 13481 13482 /* Corresponding fixup done in do_misc_fixups(). */ 13483 aux->alu_state = alu_state; 13484 aux->alu_limit = alu_limit; 13485 return 0; 13486 } 13487 13488 static int sanitize_val_alu(struct bpf_verifier_env *env, 13489 struct bpf_insn *insn) 13490 { 13491 struct bpf_insn_aux_data *aux = cur_aux(env); 13492 13493 if (can_skip_alu_sanitation(env, insn)) 13494 return 0; 13495 13496 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 13497 } 13498 13499 static bool sanitize_needed(u8 opcode) 13500 { 13501 return opcode == BPF_ADD || opcode == BPF_SUB; 13502 } 13503 13504 struct bpf_sanitize_info { 13505 struct bpf_insn_aux_data aux; 13506 bool mask_to_left; 13507 }; 13508 13509 static int sanitize_speculative_path(struct bpf_verifier_env *env, 13510 const struct bpf_insn *insn, 13511 u32 next_idx, u32 curr_idx) 13512 { 13513 struct bpf_verifier_state *branch; 13514 struct bpf_reg_state *regs; 13515 13516 branch = push_stack(env, next_idx, curr_idx, true); 13517 if (!IS_ERR(branch) && insn) { 13518 regs = branch->frame[branch->curframe]->regs; 13519 if (BPF_SRC(insn->code) == BPF_K) { 13520 mark_reg_unknown(env, regs, insn->dst_reg); 13521 } else if (BPF_SRC(insn->code) == BPF_X) { 13522 mark_reg_unknown(env, regs, insn->dst_reg); 13523 mark_reg_unknown(env, regs, insn->src_reg); 13524 } 13525 } 13526 return PTR_ERR_OR_ZERO(branch); 13527 } 13528 13529 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 13530 struct bpf_insn *insn, 13531 const struct bpf_reg_state *ptr_reg, 13532 const struct bpf_reg_state *off_reg, 13533 struct bpf_reg_state *dst_reg, 13534 struct bpf_sanitize_info *info, 13535 const bool commit_window) 13536 { 13537 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 13538 struct bpf_verifier_state *vstate = env->cur_state; 13539 bool off_is_imm = tnum_is_const(off_reg->var_off); 13540 bool off_is_neg = off_reg->smin_value < 0; 13541 bool ptr_is_dst_reg = ptr_reg == dst_reg; 13542 u8 opcode = BPF_OP(insn->code); 13543 u32 alu_state, alu_limit; 13544 struct bpf_reg_state tmp; 13545 int err; 13546 13547 if (can_skip_alu_sanitation(env, insn)) 13548 return 0; 13549 13550 /* We already marked aux for masking from non-speculative 13551 * paths, thus we got here in the first place. We only care 13552 * to explore bad access from here. 13553 */ 13554 if (vstate->speculative) 13555 goto do_sim; 13556 13557 if (!commit_window) { 13558 if (!tnum_is_const(off_reg->var_off) && 13559 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 13560 return REASON_BOUNDS; 13561 13562 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 13563 (opcode == BPF_SUB && !off_is_neg); 13564 } 13565 13566 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 13567 if (err < 0) 13568 return err; 13569 13570 if (commit_window) { 13571 /* In commit phase we narrow the masking window based on 13572 * the observed pointer move after the simulated operation. 13573 */ 13574 alu_state = info->aux.alu_state; 13575 alu_limit = abs(info->aux.alu_limit - alu_limit); 13576 } else { 13577 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 13578 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 13579 alu_state |= ptr_is_dst_reg ? 13580 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 13581 13582 /* Limit pruning on unknown scalars to enable deep search for 13583 * potential masking differences from other program paths. 13584 */ 13585 if (!off_is_imm) 13586 env->explore_alu_limits = true; 13587 } 13588 13589 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 13590 if (err < 0) 13591 return err; 13592 do_sim: 13593 /* If we're in commit phase, we're done here given we already 13594 * pushed the truncated dst_reg into the speculative verification 13595 * stack. 13596 * 13597 * Also, when register is a known constant, we rewrite register-based 13598 * operation to immediate-based, and thus do not need masking (and as 13599 * a consequence, do not need to simulate the zero-truncation either). 13600 */ 13601 if (commit_window || off_is_imm) 13602 return 0; 13603 13604 /* Simulate and find potential out-of-bounds access under 13605 * speculative execution from truncation as a result of 13606 * masking when off was not within expected range. If off 13607 * sits in dst, then we temporarily need to move ptr there 13608 * to simulate dst (== 0) +/-= ptr. Needed, for example, 13609 * for cases where we use K-based arithmetic in one direction 13610 * and truncated reg-based in the other in order to explore 13611 * bad access. 13612 */ 13613 if (!ptr_is_dst_reg) { 13614 tmp = *dst_reg; 13615 copy_register_state(dst_reg, ptr_reg); 13616 } 13617 err = sanitize_speculative_path(env, NULL, env->insn_idx + 1, env->insn_idx); 13618 if (err < 0) 13619 return REASON_STACK; 13620 if (!ptr_is_dst_reg) 13621 *dst_reg = tmp; 13622 return 0; 13623 } 13624 13625 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 13626 { 13627 struct bpf_verifier_state *vstate = env->cur_state; 13628 13629 /* If we simulate paths under speculation, we don't update the 13630 * insn as 'seen' such that when we verify unreachable paths in 13631 * the non-speculative domain, sanitize_dead_code() can still 13632 * rewrite/sanitize them. 13633 */ 13634 if (!vstate->speculative) 13635 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 13636 } 13637 13638 static int sanitize_err(struct bpf_verifier_env *env, 13639 const struct bpf_insn *insn, int reason, 13640 const struct bpf_reg_state *off_reg, 13641 const struct bpf_reg_state *dst_reg) 13642 { 13643 static const char *err = "pointer arithmetic with it prohibited for !root"; 13644 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 13645 u32 dst = insn->dst_reg, src = insn->src_reg; 13646 13647 switch (reason) { 13648 case REASON_BOUNDS: 13649 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 13650 off_reg == dst_reg ? dst : src, err); 13651 break; 13652 case REASON_TYPE: 13653 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 13654 off_reg == dst_reg ? src : dst, err); 13655 break; 13656 case REASON_PATHS: 13657 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 13658 dst, op, err); 13659 break; 13660 case REASON_LIMIT: 13661 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 13662 dst, op, err); 13663 break; 13664 case REASON_STACK: 13665 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 13666 dst, err); 13667 return -ENOMEM; 13668 default: 13669 verifier_bug(env, "unknown reason (%d)", reason); 13670 break; 13671 } 13672 13673 return -EACCES; 13674 } 13675 13676 /* check that stack access falls within stack limits and that 'reg' doesn't 13677 * have a variable offset. 13678 * 13679 * Variable offset is prohibited for unprivileged mode for simplicity since it 13680 * requires corresponding support in Spectre masking for stack ALU. See also 13681 * retrieve_ptr_limit(). 13682 */ 13683 static int check_stack_access_for_ptr_arithmetic( 13684 struct bpf_verifier_env *env, 13685 int regno, 13686 const struct bpf_reg_state *reg, 13687 int off) 13688 { 13689 if (!tnum_is_const(reg->var_off)) { 13690 char tn_buf[48]; 13691 13692 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 13693 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 13694 regno, tn_buf, off); 13695 return -EACCES; 13696 } 13697 13698 if (off >= 0 || off < -MAX_BPF_STACK) { 13699 verbose(env, "R%d stack pointer arithmetic goes out of range, " 13700 "prohibited for !root; off=%d\n", regno, off); 13701 return -EACCES; 13702 } 13703 13704 return 0; 13705 } 13706 13707 static int sanitize_check_bounds(struct bpf_verifier_env *env, 13708 const struct bpf_insn *insn, 13709 const struct bpf_reg_state *dst_reg) 13710 { 13711 u32 dst = insn->dst_reg; 13712 13713 /* For unprivileged we require that resulting offset must be in bounds 13714 * in order to be able to sanitize access later on. 13715 */ 13716 if (env->bypass_spec_v1) 13717 return 0; 13718 13719 switch (dst_reg->type) { 13720 case PTR_TO_STACK: 13721 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 13722 dst_reg->var_off.value)) 13723 return -EACCES; 13724 break; 13725 case PTR_TO_MAP_VALUE: 13726 if (check_map_access(env, dst, 0, 1, false, ACCESS_HELPER)) { 13727 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 13728 "prohibited for !root\n", dst); 13729 return -EACCES; 13730 } 13731 break; 13732 default: 13733 return -EOPNOTSUPP; 13734 } 13735 13736 return 0; 13737 } 13738 13739 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 13740 * Caller should also handle BPF_MOV case separately. 13741 * If we return -EACCES, caller may want to try again treating pointer as a 13742 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 13743 */ 13744 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 13745 struct bpf_insn *insn, 13746 const struct bpf_reg_state *ptr_reg, 13747 const struct bpf_reg_state *off_reg) 13748 { 13749 struct bpf_verifier_state *vstate = env->cur_state; 13750 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13751 struct bpf_reg_state *regs = state->regs, *dst_reg; 13752 bool known = tnum_is_const(off_reg->var_off); 13753 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 13754 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 13755 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 13756 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 13757 struct bpf_sanitize_info info = {}; 13758 u8 opcode = BPF_OP(insn->code); 13759 u32 dst = insn->dst_reg; 13760 int ret, bounds_ret; 13761 13762 dst_reg = ®s[dst]; 13763 13764 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 13765 smin_val > smax_val || umin_val > umax_val) { 13766 /* Taint dst register if offset had invalid bounds derived from 13767 * e.g. dead branches. 13768 */ 13769 __mark_reg_unknown(env, dst_reg); 13770 return 0; 13771 } 13772 13773 if (BPF_CLASS(insn->code) != BPF_ALU64) { 13774 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 13775 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13776 __mark_reg_unknown(env, dst_reg); 13777 return 0; 13778 } 13779 13780 verbose(env, 13781 "R%d 32-bit pointer arithmetic prohibited\n", 13782 dst); 13783 return -EACCES; 13784 } 13785 13786 if (ptr_reg->type & PTR_MAYBE_NULL) { 13787 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 13788 dst, reg_type_str(env, ptr_reg->type)); 13789 return -EACCES; 13790 } 13791 13792 /* 13793 * Accesses to untrusted PTR_TO_MEM are done through probe 13794 * instructions, hence no need to track offsets. 13795 */ 13796 if (base_type(ptr_reg->type) == PTR_TO_MEM && (ptr_reg->type & PTR_UNTRUSTED)) 13797 return 0; 13798 13799 switch (base_type(ptr_reg->type)) { 13800 case PTR_TO_CTX: 13801 case PTR_TO_MAP_VALUE: 13802 case PTR_TO_MAP_KEY: 13803 case PTR_TO_STACK: 13804 case PTR_TO_PACKET_META: 13805 case PTR_TO_PACKET: 13806 case PTR_TO_TP_BUFFER: 13807 case PTR_TO_BTF_ID: 13808 case PTR_TO_MEM: 13809 case PTR_TO_BUF: 13810 case PTR_TO_FUNC: 13811 case CONST_PTR_TO_DYNPTR: 13812 break; 13813 case PTR_TO_FLOW_KEYS: 13814 if (known) 13815 break; 13816 fallthrough; 13817 case CONST_PTR_TO_MAP: 13818 /* smin_val represents the known value */ 13819 if (known && smin_val == 0 && opcode == BPF_ADD) 13820 break; 13821 fallthrough; 13822 default: 13823 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 13824 dst, reg_type_str(env, ptr_reg->type)); 13825 return -EACCES; 13826 } 13827 13828 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 13829 * The id may be overwritten later if we create a new variable offset. 13830 */ 13831 dst_reg->type = ptr_reg->type; 13832 dst_reg->id = ptr_reg->id; 13833 13834 if (!check_reg_sane_offset_scalar(env, off_reg, ptr_reg->type) || 13835 !check_reg_sane_offset_ptr(env, ptr_reg, ptr_reg->type)) 13836 return -EINVAL; 13837 13838 /* pointer types do not carry 32-bit bounds at the moment. */ 13839 __mark_reg32_unbounded(dst_reg); 13840 13841 if (sanitize_needed(opcode)) { 13842 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 13843 &info, false); 13844 if (ret < 0) 13845 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13846 } 13847 13848 switch (opcode) { 13849 case BPF_ADD: 13850 /* 13851 * dst_reg gets the pointer type and since some positive 13852 * integer value was added to the pointer, give it a new 'id' 13853 * if it's a PTR_TO_PACKET. 13854 * this creates a new 'base' pointer, off_reg (variable) gets 13855 * added into the variable offset, and we copy the fixed offset 13856 * from ptr_reg. 13857 */ 13858 if (check_add_overflow(smin_ptr, smin_val, &dst_reg->smin_value) || 13859 check_add_overflow(smax_ptr, smax_val, &dst_reg->smax_value)) { 13860 dst_reg->smin_value = S64_MIN; 13861 dst_reg->smax_value = S64_MAX; 13862 } 13863 if (check_add_overflow(umin_ptr, umin_val, &dst_reg->umin_value) || 13864 check_add_overflow(umax_ptr, umax_val, &dst_reg->umax_value)) { 13865 dst_reg->umin_value = 0; 13866 dst_reg->umax_value = U64_MAX; 13867 } 13868 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13869 dst_reg->raw = ptr_reg->raw; 13870 if (reg_is_pkt_pointer(ptr_reg)) { 13871 if (!known) 13872 dst_reg->id = ++env->id_gen; 13873 /* 13874 * Clear range for unknown addends since we can't know 13875 * where the pkt pointer ended up. Also clear AT_PKT_END / 13876 * BEYOND_PKT_END from prior comparison as any pointer 13877 * arithmetic invalidates them. 13878 */ 13879 if (!known || dst_reg->range < 0) 13880 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13881 } 13882 break; 13883 case BPF_SUB: 13884 if (dst_reg == off_reg) { 13885 /* scalar -= pointer. Creates an unknown scalar */ 13886 verbose(env, "R%d tried to subtract pointer from scalar\n", 13887 dst); 13888 return -EACCES; 13889 } 13890 /* We don't allow subtraction from FP, because (according to 13891 * test_verifier.c test "invalid fp arithmetic", JITs might not 13892 * be able to deal with it. 13893 */ 13894 if (ptr_reg->type == PTR_TO_STACK) { 13895 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13896 dst); 13897 return -EACCES; 13898 } 13899 /* A new variable offset is created. If the subtrahend is known 13900 * nonnegative, then any reg->range we had before is still good. 13901 */ 13902 if (check_sub_overflow(smin_ptr, smax_val, &dst_reg->smin_value) || 13903 check_sub_overflow(smax_ptr, smin_val, &dst_reg->smax_value)) { 13904 /* Overflow possible, we know nothing */ 13905 dst_reg->smin_value = S64_MIN; 13906 dst_reg->smax_value = S64_MAX; 13907 } 13908 if (umin_ptr < umax_val) { 13909 /* Overflow possible, we know nothing */ 13910 dst_reg->umin_value = 0; 13911 dst_reg->umax_value = U64_MAX; 13912 } else { 13913 /* Cannot overflow (as long as bounds are consistent) */ 13914 dst_reg->umin_value = umin_ptr - umax_val; 13915 dst_reg->umax_value = umax_ptr - umin_val; 13916 } 13917 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13918 dst_reg->raw = ptr_reg->raw; 13919 if (reg_is_pkt_pointer(ptr_reg)) { 13920 if (!known) 13921 dst_reg->id = ++env->id_gen; 13922 /* 13923 * Clear range if the subtrahend may be negative since 13924 * pkt pointer could move past its bounds. A positive 13925 * subtrahend moves it backwards keeping positive range 13926 * intact. Also clear AT_PKT_END / BEYOND_PKT_END from 13927 * prior comparison as arithmetic invalidates them. 13928 */ 13929 if ((!known && smin_val < 0) || dst_reg->range < 0) 13930 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13931 } 13932 break; 13933 case BPF_AND: 13934 case BPF_OR: 13935 case BPF_XOR: 13936 /* bitwise ops on pointers are troublesome, prohibit. */ 13937 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13938 dst, bpf_alu_string[opcode >> 4]); 13939 return -EACCES; 13940 default: 13941 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13942 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13943 dst, bpf_alu_string[opcode >> 4]); 13944 return -EACCES; 13945 } 13946 13947 if (!check_reg_sane_offset_ptr(env, dst_reg, ptr_reg->type)) 13948 return -EINVAL; 13949 reg_bounds_sync(dst_reg); 13950 bounds_ret = sanitize_check_bounds(env, insn, dst_reg); 13951 if (bounds_ret == -EACCES) 13952 return bounds_ret; 13953 if (sanitize_needed(opcode)) { 13954 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13955 &info, true); 13956 if (verifier_bug_if(!can_skip_alu_sanitation(env, insn) 13957 && !env->cur_state->speculative 13958 && bounds_ret 13959 && !ret, 13960 env, "Pointer type unsupported by sanitize_check_bounds() not rejected by retrieve_ptr_limit() as required")) { 13961 return -EFAULT; 13962 } 13963 if (ret < 0) 13964 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13965 } 13966 13967 return 0; 13968 } 13969 13970 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13971 struct bpf_reg_state *src_reg) 13972 { 13973 s32 *dst_smin = &dst_reg->s32_min_value; 13974 s32 *dst_smax = &dst_reg->s32_max_value; 13975 u32 *dst_umin = &dst_reg->u32_min_value; 13976 u32 *dst_umax = &dst_reg->u32_max_value; 13977 u32 umin_val = src_reg->u32_min_value; 13978 u32 umax_val = src_reg->u32_max_value; 13979 bool min_overflow, max_overflow; 13980 13981 if (check_add_overflow(*dst_smin, src_reg->s32_min_value, dst_smin) || 13982 check_add_overflow(*dst_smax, src_reg->s32_max_value, dst_smax)) { 13983 *dst_smin = S32_MIN; 13984 *dst_smax = S32_MAX; 13985 } 13986 13987 /* If either all additions overflow or no additions overflow, then 13988 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax = 13989 * dst_umax + src_umax. Otherwise (some additions overflow), set 13990 * the output bounds to unbounded. 13991 */ 13992 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin); 13993 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax); 13994 13995 if (!min_overflow && max_overflow) { 13996 *dst_umin = 0; 13997 *dst_umax = U32_MAX; 13998 } 13999 } 14000 14001 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 14002 struct bpf_reg_state *src_reg) 14003 { 14004 s64 *dst_smin = &dst_reg->smin_value; 14005 s64 *dst_smax = &dst_reg->smax_value; 14006 u64 *dst_umin = &dst_reg->umin_value; 14007 u64 *dst_umax = &dst_reg->umax_value; 14008 u64 umin_val = src_reg->umin_value; 14009 u64 umax_val = src_reg->umax_value; 14010 bool min_overflow, max_overflow; 14011 14012 if (check_add_overflow(*dst_smin, src_reg->smin_value, dst_smin) || 14013 check_add_overflow(*dst_smax, src_reg->smax_value, dst_smax)) { 14014 *dst_smin = S64_MIN; 14015 *dst_smax = S64_MAX; 14016 } 14017 14018 /* If either all additions overflow or no additions overflow, then 14019 * it is okay to set: dst_umin = dst_umin + src_umin, dst_umax = 14020 * dst_umax + src_umax. Otherwise (some additions overflow), set 14021 * the output bounds to unbounded. 14022 */ 14023 min_overflow = check_add_overflow(*dst_umin, umin_val, dst_umin); 14024 max_overflow = check_add_overflow(*dst_umax, umax_val, dst_umax); 14025 14026 if (!min_overflow && max_overflow) { 14027 *dst_umin = 0; 14028 *dst_umax = U64_MAX; 14029 } 14030 } 14031 14032 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 14033 struct bpf_reg_state *src_reg) 14034 { 14035 s32 *dst_smin = &dst_reg->s32_min_value; 14036 s32 *dst_smax = &dst_reg->s32_max_value; 14037 u32 *dst_umin = &dst_reg->u32_min_value; 14038 u32 *dst_umax = &dst_reg->u32_max_value; 14039 u32 umin_val = src_reg->u32_min_value; 14040 u32 umax_val = src_reg->u32_max_value; 14041 bool min_underflow, max_underflow; 14042 14043 if (check_sub_overflow(*dst_smin, src_reg->s32_max_value, dst_smin) || 14044 check_sub_overflow(*dst_smax, src_reg->s32_min_value, dst_smax)) { 14045 /* Overflow possible, we know nothing */ 14046 *dst_smin = S32_MIN; 14047 *dst_smax = S32_MAX; 14048 } 14049 14050 /* If either all subtractions underflow or no subtractions 14051 * underflow, it is okay to set: dst_umin = dst_umin - src_umax, 14052 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions 14053 * underflow), set the output bounds to unbounded. 14054 */ 14055 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin); 14056 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax); 14057 14058 if (min_underflow && !max_underflow) { 14059 *dst_umin = 0; 14060 *dst_umax = U32_MAX; 14061 } 14062 } 14063 14064 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 14065 struct bpf_reg_state *src_reg) 14066 { 14067 s64 *dst_smin = &dst_reg->smin_value; 14068 s64 *dst_smax = &dst_reg->smax_value; 14069 u64 *dst_umin = &dst_reg->umin_value; 14070 u64 *dst_umax = &dst_reg->umax_value; 14071 u64 umin_val = src_reg->umin_value; 14072 u64 umax_val = src_reg->umax_value; 14073 bool min_underflow, max_underflow; 14074 14075 if (check_sub_overflow(*dst_smin, src_reg->smax_value, dst_smin) || 14076 check_sub_overflow(*dst_smax, src_reg->smin_value, dst_smax)) { 14077 /* Overflow possible, we know nothing */ 14078 *dst_smin = S64_MIN; 14079 *dst_smax = S64_MAX; 14080 } 14081 14082 /* If either all subtractions underflow or no subtractions 14083 * underflow, it is okay to set: dst_umin = dst_umin - src_umax, 14084 * dst_umax = dst_umax - src_umin. Otherwise (some subtractions 14085 * underflow), set the output bounds to unbounded. 14086 */ 14087 min_underflow = check_sub_overflow(*dst_umin, umax_val, dst_umin); 14088 max_underflow = check_sub_overflow(*dst_umax, umin_val, dst_umax); 14089 14090 if (min_underflow && !max_underflow) { 14091 *dst_umin = 0; 14092 *dst_umax = U64_MAX; 14093 } 14094 } 14095 14096 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 14097 struct bpf_reg_state *src_reg) 14098 { 14099 s32 *dst_smin = &dst_reg->s32_min_value; 14100 s32 *dst_smax = &dst_reg->s32_max_value; 14101 u32 *dst_umin = &dst_reg->u32_min_value; 14102 u32 *dst_umax = &dst_reg->u32_max_value; 14103 s32 tmp_prod[4]; 14104 14105 if (check_mul_overflow(*dst_umax, src_reg->u32_max_value, dst_umax) || 14106 check_mul_overflow(*dst_umin, src_reg->u32_min_value, dst_umin)) { 14107 /* Overflow possible, we know nothing */ 14108 *dst_umin = 0; 14109 *dst_umax = U32_MAX; 14110 } 14111 if (check_mul_overflow(*dst_smin, src_reg->s32_min_value, &tmp_prod[0]) || 14112 check_mul_overflow(*dst_smin, src_reg->s32_max_value, &tmp_prod[1]) || 14113 check_mul_overflow(*dst_smax, src_reg->s32_min_value, &tmp_prod[2]) || 14114 check_mul_overflow(*dst_smax, src_reg->s32_max_value, &tmp_prod[3])) { 14115 /* Overflow possible, we know nothing */ 14116 *dst_smin = S32_MIN; 14117 *dst_smax = S32_MAX; 14118 } else { 14119 *dst_smin = min_array(tmp_prod, 4); 14120 *dst_smax = max_array(tmp_prod, 4); 14121 } 14122 } 14123 14124 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 14125 struct bpf_reg_state *src_reg) 14126 { 14127 s64 *dst_smin = &dst_reg->smin_value; 14128 s64 *dst_smax = &dst_reg->smax_value; 14129 u64 *dst_umin = &dst_reg->umin_value; 14130 u64 *dst_umax = &dst_reg->umax_value; 14131 s64 tmp_prod[4]; 14132 14133 if (check_mul_overflow(*dst_umax, src_reg->umax_value, dst_umax) || 14134 check_mul_overflow(*dst_umin, src_reg->umin_value, dst_umin)) { 14135 /* Overflow possible, we know nothing */ 14136 *dst_umin = 0; 14137 *dst_umax = U64_MAX; 14138 } 14139 if (check_mul_overflow(*dst_smin, src_reg->smin_value, &tmp_prod[0]) || 14140 check_mul_overflow(*dst_smin, src_reg->smax_value, &tmp_prod[1]) || 14141 check_mul_overflow(*dst_smax, src_reg->smin_value, &tmp_prod[2]) || 14142 check_mul_overflow(*dst_smax, src_reg->smax_value, &tmp_prod[3])) { 14143 /* Overflow possible, we know nothing */ 14144 *dst_smin = S64_MIN; 14145 *dst_smax = S64_MAX; 14146 } else { 14147 *dst_smin = min_array(tmp_prod, 4); 14148 *dst_smax = max_array(tmp_prod, 4); 14149 } 14150 } 14151 14152 static void scalar32_min_max_udiv(struct bpf_reg_state *dst_reg, 14153 struct bpf_reg_state *src_reg) 14154 { 14155 u32 *dst_umin = &dst_reg->u32_min_value; 14156 u32 *dst_umax = &dst_reg->u32_max_value; 14157 u32 src_val = src_reg->u32_min_value; /* non-zero, const divisor */ 14158 14159 *dst_umin = *dst_umin / src_val; 14160 *dst_umax = *dst_umax / src_val; 14161 14162 /* Reset other ranges/tnum to unbounded/unknown. */ 14163 dst_reg->s32_min_value = S32_MIN; 14164 dst_reg->s32_max_value = S32_MAX; 14165 reset_reg64_and_tnum(dst_reg); 14166 } 14167 14168 static void scalar_min_max_udiv(struct bpf_reg_state *dst_reg, 14169 struct bpf_reg_state *src_reg) 14170 { 14171 u64 *dst_umin = &dst_reg->umin_value; 14172 u64 *dst_umax = &dst_reg->umax_value; 14173 u64 src_val = src_reg->umin_value; /* non-zero, const divisor */ 14174 14175 *dst_umin = div64_u64(*dst_umin, src_val); 14176 *dst_umax = div64_u64(*dst_umax, src_val); 14177 14178 /* Reset other ranges/tnum to unbounded/unknown. */ 14179 dst_reg->smin_value = S64_MIN; 14180 dst_reg->smax_value = S64_MAX; 14181 reset_reg32_and_tnum(dst_reg); 14182 } 14183 14184 static void scalar32_min_max_sdiv(struct bpf_reg_state *dst_reg, 14185 struct bpf_reg_state *src_reg) 14186 { 14187 s32 *dst_smin = &dst_reg->s32_min_value; 14188 s32 *dst_smax = &dst_reg->s32_max_value; 14189 s32 src_val = src_reg->s32_min_value; /* non-zero, const divisor */ 14190 s32 res1, res2; 14191 14192 /* BPF div specification: S32_MIN / -1 = S32_MIN */ 14193 if (*dst_smin == S32_MIN && src_val == -1) { 14194 /* 14195 * If the dividend range contains more than just S32_MIN, 14196 * we cannot precisely track the result, so it becomes unbounded. 14197 * e.g., [S32_MIN, S32_MIN+10]/(-1), 14198 * = {S32_MIN} U [-(S32_MIN+10), -(S32_MIN+1)] 14199 * = {S32_MIN} U [S32_MAX-9, S32_MAX] = [S32_MIN, S32_MAX] 14200 * Otherwise (if dividend is exactly S32_MIN), result remains S32_MIN. 14201 */ 14202 if (*dst_smax != S32_MIN) { 14203 *dst_smin = S32_MIN; 14204 *dst_smax = S32_MAX; 14205 } 14206 goto reset; 14207 } 14208 14209 res1 = *dst_smin / src_val; 14210 res2 = *dst_smax / src_val; 14211 *dst_smin = min(res1, res2); 14212 *dst_smax = max(res1, res2); 14213 14214 reset: 14215 /* Reset other ranges/tnum to unbounded/unknown. */ 14216 dst_reg->u32_min_value = 0; 14217 dst_reg->u32_max_value = U32_MAX; 14218 reset_reg64_and_tnum(dst_reg); 14219 } 14220 14221 static void scalar_min_max_sdiv(struct bpf_reg_state *dst_reg, 14222 struct bpf_reg_state *src_reg) 14223 { 14224 s64 *dst_smin = &dst_reg->smin_value; 14225 s64 *dst_smax = &dst_reg->smax_value; 14226 s64 src_val = src_reg->smin_value; /* non-zero, const divisor */ 14227 s64 res1, res2; 14228 14229 /* BPF div specification: S64_MIN / -1 = S64_MIN */ 14230 if (*dst_smin == S64_MIN && src_val == -1) { 14231 /* 14232 * If the dividend range contains more than just S64_MIN, 14233 * we cannot precisely track the result, so it becomes unbounded. 14234 * e.g., [S64_MIN, S64_MIN+10]/(-1), 14235 * = {S64_MIN} U [-(S64_MIN+10), -(S64_MIN+1)] 14236 * = {S64_MIN} U [S64_MAX-9, S64_MAX] = [S64_MIN, S64_MAX] 14237 * Otherwise (if dividend is exactly S64_MIN), result remains S64_MIN. 14238 */ 14239 if (*dst_smax != S64_MIN) { 14240 *dst_smin = S64_MIN; 14241 *dst_smax = S64_MAX; 14242 } 14243 goto reset; 14244 } 14245 14246 res1 = div64_s64(*dst_smin, src_val); 14247 res2 = div64_s64(*dst_smax, src_val); 14248 *dst_smin = min(res1, res2); 14249 *dst_smax = max(res1, res2); 14250 14251 reset: 14252 /* Reset other ranges/tnum to unbounded/unknown. */ 14253 dst_reg->umin_value = 0; 14254 dst_reg->umax_value = U64_MAX; 14255 reset_reg32_and_tnum(dst_reg); 14256 } 14257 14258 static void scalar32_min_max_umod(struct bpf_reg_state *dst_reg, 14259 struct bpf_reg_state *src_reg) 14260 { 14261 u32 *dst_umin = &dst_reg->u32_min_value; 14262 u32 *dst_umax = &dst_reg->u32_max_value; 14263 u32 src_val = src_reg->u32_min_value; /* non-zero, const divisor */ 14264 u32 res_max = src_val - 1; 14265 14266 /* 14267 * If dst_umax <= res_max, the result remains unchanged. 14268 * e.g., [2, 5] % 10 = [2, 5]. 14269 */ 14270 if (*dst_umax <= res_max) 14271 return; 14272 14273 *dst_umin = 0; 14274 *dst_umax = min(*dst_umax, res_max); 14275 14276 /* Reset other ranges/tnum to unbounded/unknown. */ 14277 dst_reg->s32_min_value = S32_MIN; 14278 dst_reg->s32_max_value = S32_MAX; 14279 reset_reg64_and_tnum(dst_reg); 14280 } 14281 14282 static void scalar_min_max_umod(struct bpf_reg_state *dst_reg, 14283 struct bpf_reg_state *src_reg) 14284 { 14285 u64 *dst_umin = &dst_reg->umin_value; 14286 u64 *dst_umax = &dst_reg->umax_value; 14287 u64 src_val = src_reg->umin_value; /* non-zero, const divisor */ 14288 u64 res_max = src_val - 1; 14289 14290 /* 14291 * If dst_umax <= res_max, the result remains unchanged. 14292 * e.g., [2, 5] % 10 = [2, 5]. 14293 */ 14294 if (*dst_umax <= res_max) 14295 return; 14296 14297 *dst_umin = 0; 14298 *dst_umax = min(*dst_umax, res_max); 14299 14300 /* Reset other ranges/tnum to unbounded/unknown. */ 14301 dst_reg->smin_value = S64_MIN; 14302 dst_reg->smax_value = S64_MAX; 14303 reset_reg32_and_tnum(dst_reg); 14304 } 14305 14306 static void scalar32_min_max_smod(struct bpf_reg_state *dst_reg, 14307 struct bpf_reg_state *src_reg) 14308 { 14309 s32 *dst_smin = &dst_reg->s32_min_value; 14310 s32 *dst_smax = &dst_reg->s32_max_value; 14311 s32 src_val = src_reg->s32_min_value; /* non-zero, const divisor */ 14312 14313 /* 14314 * Safe absolute value calculation: 14315 * If src_val == S32_MIN (-2147483648), src_abs becomes 2147483648. 14316 * Here use unsigned integer to avoid overflow. 14317 */ 14318 u32 src_abs = (src_val > 0) ? (u32)src_val : -(u32)src_val; 14319 14320 /* 14321 * Calculate the maximum possible absolute value of the result. 14322 * Even if src_abs is 2147483648 (S32_MIN), subtracting 1 gives 14323 * 2147483647 (S32_MAX), which fits perfectly in s32. 14324 */ 14325 s32 res_max_abs = src_abs - 1; 14326 14327 /* 14328 * If the dividend is already within the result range, 14329 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14330 */ 14331 if (*dst_smin >= -res_max_abs && *dst_smax <= res_max_abs) 14332 return; 14333 14334 /* General case: result has the same sign as the dividend. */ 14335 if (*dst_smin >= 0) { 14336 *dst_smin = 0; 14337 *dst_smax = min(*dst_smax, res_max_abs); 14338 } else if (*dst_smax <= 0) { 14339 *dst_smax = 0; 14340 *dst_smin = max(*dst_smin, -res_max_abs); 14341 } else { 14342 *dst_smin = -res_max_abs; 14343 *dst_smax = res_max_abs; 14344 } 14345 14346 /* Reset other ranges/tnum to unbounded/unknown. */ 14347 dst_reg->u32_min_value = 0; 14348 dst_reg->u32_max_value = U32_MAX; 14349 reset_reg64_and_tnum(dst_reg); 14350 } 14351 14352 static void scalar_min_max_smod(struct bpf_reg_state *dst_reg, 14353 struct bpf_reg_state *src_reg) 14354 { 14355 s64 *dst_smin = &dst_reg->smin_value; 14356 s64 *dst_smax = &dst_reg->smax_value; 14357 s64 src_val = src_reg->smin_value; /* non-zero, const divisor */ 14358 14359 /* 14360 * Safe absolute value calculation: 14361 * If src_val == S64_MIN (-2^63), src_abs becomes 2^63. 14362 * Here use unsigned integer to avoid overflow. 14363 */ 14364 u64 src_abs = (src_val > 0) ? (u64)src_val : -(u64)src_val; 14365 14366 /* 14367 * Calculate the maximum possible absolute value of the result. 14368 * Even if src_abs is 2^63 (S64_MIN), subtracting 1 gives 14369 * 2^63 - 1 (S64_MAX), which fits perfectly in s64. 14370 */ 14371 s64 res_max_abs = src_abs - 1; 14372 14373 /* 14374 * If the dividend is already within the result range, 14375 * the result remains unchanged. e.g., [-2, 5] % 10 = [-2, 5]. 14376 */ 14377 if (*dst_smin >= -res_max_abs && *dst_smax <= res_max_abs) 14378 return; 14379 14380 /* General case: result has the same sign as the dividend. */ 14381 if (*dst_smin >= 0) { 14382 *dst_smin = 0; 14383 *dst_smax = min(*dst_smax, res_max_abs); 14384 } else if (*dst_smax <= 0) { 14385 *dst_smax = 0; 14386 *dst_smin = max(*dst_smin, -res_max_abs); 14387 } else { 14388 *dst_smin = -res_max_abs; 14389 *dst_smax = res_max_abs; 14390 } 14391 14392 /* Reset other ranges/tnum to unbounded/unknown. */ 14393 dst_reg->umin_value = 0; 14394 dst_reg->umax_value = U64_MAX; 14395 reset_reg32_and_tnum(dst_reg); 14396 } 14397 14398 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 14399 struct bpf_reg_state *src_reg) 14400 { 14401 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14402 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14403 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14404 u32 umax_val = src_reg->u32_max_value; 14405 14406 if (src_known && dst_known) { 14407 __mark_reg32_known(dst_reg, var32_off.value); 14408 return; 14409 } 14410 14411 /* We get our minimum from the var_off, since that's inherently 14412 * bitwise. Our maximum is the minimum of the operands' maxima. 14413 */ 14414 dst_reg->u32_min_value = var32_off.value; 14415 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 14416 14417 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14418 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14419 */ 14420 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14421 dst_reg->s32_min_value = dst_reg->u32_min_value; 14422 dst_reg->s32_max_value = dst_reg->u32_max_value; 14423 } else { 14424 dst_reg->s32_min_value = S32_MIN; 14425 dst_reg->s32_max_value = S32_MAX; 14426 } 14427 } 14428 14429 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 14430 struct bpf_reg_state *src_reg) 14431 { 14432 bool src_known = tnum_is_const(src_reg->var_off); 14433 bool dst_known = tnum_is_const(dst_reg->var_off); 14434 u64 umax_val = src_reg->umax_value; 14435 14436 if (src_known && dst_known) { 14437 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14438 return; 14439 } 14440 14441 /* We get our minimum from the var_off, since that's inherently 14442 * bitwise. Our maximum is the minimum of the operands' maxima. 14443 */ 14444 dst_reg->umin_value = dst_reg->var_off.value; 14445 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 14446 14447 /* Safe to set s64 bounds by casting u64 result into s64 when u64 14448 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 14449 */ 14450 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 14451 dst_reg->smin_value = dst_reg->umin_value; 14452 dst_reg->smax_value = dst_reg->umax_value; 14453 } else { 14454 dst_reg->smin_value = S64_MIN; 14455 dst_reg->smax_value = S64_MAX; 14456 } 14457 /* We may learn something more from the var_off */ 14458 __update_reg_bounds(dst_reg); 14459 } 14460 14461 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 14462 struct bpf_reg_state *src_reg) 14463 { 14464 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14465 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14466 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14467 u32 umin_val = src_reg->u32_min_value; 14468 14469 if (src_known && dst_known) { 14470 __mark_reg32_known(dst_reg, var32_off.value); 14471 return; 14472 } 14473 14474 /* We get our maximum from the var_off, and our minimum is the 14475 * maximum of the operands' minima 14476 */ 14477 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 14478 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 14479 14480 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14481 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14482 */ 14483 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14484 dst_reg->s32_min_value = dst_reg->u32_min_value; 14485 dst_reg->s32_max_value = dst_reg->u32_max_value; 14486 } else { 14487 dst_reg->s32_min_value = S32_MIN; 14488 dst_reg->s32_max_value = S32_MAX; 14489 } 14490 } 14491 14492 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 14493 struct bpf_reg_state *src_reg) 14494 { 14495 bool src_known = tnum_is_const(src_reg->var_off); 14496 bool dst_known = tnum_is_const(dst_reg->var_off); 14497 u64 umin_val = src_reg->umin_value; 14498 14499 if (src_known && dst_known) { 14500 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14501 return; 14502 } 14503 14504 /* We get our maximum from the var_off, and our minimum is the 14505 * maximum of the operands' minima 14506 */ 14507 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 14508 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 14509 14510 /* Safe to set s64 bounds by casting u64 result into s64 when u64 14511 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 14512 */ 14513 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 14514 dst_reg->smin_value = dst_reg->umin_value; 14515 dst_reg->smax_value = dst_reg->umax_value; 14516 } else { 14517 dst_reg->smin_value = S64_MIN; 14518 dst_reg->smax_value = S64_MAX; 14519 } 14520 /* We may learn something more from the var_off */ 14521 __update_reg_bounds(dst_reg); 14522 } 14523 14524 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 14525 struct bpf_reg_state *src_reg) 14526 { 14527 bool src_known = tnum_subreg_is_const(src_reg->var_off); 14528 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 14529 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 14530 14531 if (src_known && dst_known) { 14532 __mark_reg32_known(dst_reg, var32_off.value); 14533 return; 14534 } 14535 14536 /* We get both minimum and maximum from the var32_off. */ 14537 dst_reg->u32_min_value = var32_off.value; 14538 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 14539 14540 /* Safe to set s32 bounds by casting u32 result into s32 when u32 14541 * doesn't cross sign boundary. Otherwise set s32 bounds to unbounded. 14542 */ 14543 if ((s32)dst_reg->u32_min_value <= (s32)dst_reg->u32_max_value) { 14544 dst_reg->s32_min_value = dst_reg->u32_min_value; 14545 dst_reg->s32_max_value = dst_reg->u32_max_value; 14546 } else { 14547 dst_reg->s32_min_value = S32_MIN; 14548 dst_reg->s32_max_value = S32_MAX; 14549 } 14550 } 14551 14552 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 14553 struct bpf_reg_state *src_reg) 14554 { 14555 bool src_known = tnum_is_const(src_reg->var_off); 14556 bool dst_known = tnum_is_const(dst_reg->var_off); 14557 14558 if (src_known && dst_known) { 14559 /* dst_reg->var_off.value has been updated earlier */ 14560 __mark_reg_known(dst_reg, dst_reg->var_off.value); 14561 return; 14562 } 14563 14564 /* We get both minimum and maximum from the var_off. */ 14565 dst_reg->umin_value = dst_reg->var_off.value; 14566 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 14567 14568 /* Safe to set s64 bounds by casting u64 result into s64 when u64 14569 * doesn't cross sign boundary. Otherwise set s64 bounds to unbounded. 14570 */ 14571 if ((s64)dst_reg->umin_value <= (s64)dst_reg->umax_value) { 14572 dst_reg->smin_value = dst_reg->umin_value; 14573 dst_reg->smax_value = dst_reg->umax_value; 14574 } else { 14575 dst_reg->smin_value = S64_MIN; 14576 dst_reg->smax_value = S64_MAX; 14577 } 14578 14579 __update_reg_bounds(dst_reg); 14580 } 14581 14582 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14583 u64 umin_val, u64 umax_val) 14584 { 14585 /* We lose all sign bit information (except what we can pick 14586 * up from var_off) 14587 */ 14588 dst_reg->s32_min_value = S32_MIN; 14589 dst_reg->s32_max_value = S32_MAX; 14590 /* If we might shift our top bit out, then we know nothing */ 14591 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 14592 dst_reg->u32_min_value = 0; 14593 dst_reg->u32_max_value = U32_MAX; 14594 } else { 14595 dst_reg->u32_min_value <<= umin_val; 14596 dst_reg->u32_max_value <<= umax_val; 14597 } 14598 } 14599 14600 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 14601 struct bpf_reg_state *src_reg) 14602 { 14603 u32 umax_val = src_reg->u32_max_value; 14604 u32 umin_val = src_reg->u32_min_value; 14605 /* u32 alu operation will zext upper bits */ 14606 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14607 14608 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14609 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 14610 /* Not required but being careful mark reg64 bounds as unknown so 14611 * that we are forced to pick them up from tnum and zext later and 14612 * if some path skips this step we are still safe. 14613 */ 14614 __mark_reg64_unbounded(dst_reg); 14615 __update_reg32_bounds(dst_reg); 14616 } 14617 14618 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 14619 u64 umin_val, u64 umax_val) 14620 { 14621 /* Special case <<32 because it is a common compiler pattern to sign 14622 * extend subreg by doing <<32 s>>32. smin/smax assignments are correct 14623 * because s32 bounds don't flip sign when shifting to the left by 14624 * 32bits. 14625 */ 14626 if (umin_val == 32 && umax_val == 32) { 14627 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 14628 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 14629 } else { 14630 dst_reg->smax_value = S64_MAX; 14631 dst_reg->smin_value = S64_MIN; 14632 } 14633 14634 /* If we might shift our top bit out, then we know nothing */ 14635 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 14636 dst_reg->umin_value = 0; 14637 dst_reg->umax_value = U64_MAX; 14638 } else { 14639 dst_reg->umin_value <<= umin_val; 14640 dst_reg->umax_value <<= umax_val; 14641 } 14642 } 14643 14644 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 14645 struct bpf_reg_state *src_reg) 14646 { 14647 u64 umax_val = src_reg->umax_value; 14648 u64 umin_val = src_reg->umin_value; 14649 14650 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 14651 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 14652 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 14653 14654 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 14655 /* We may learn something more from the var_off */ 14656 __update_reg_bounds(dst_reg); 14657 } 14658 14659 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 14660 struct bpf_reg_state *src_reg) 14661 { 14662 struct tnum subreg = tnum_subreg(dst_reg->var_off); 14663 u32 umax_val = src_reg->u32_max_value; 14664 u32 umin_val = src_reg->u32_min_value; 14665 14666 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14667 * be negative, then either: 14668 * 1) src_reg might be zero, so the sign bit of the result is 14669 * unknown, so we lose our signed bounds 14670 * 2) it's known negative, thus the unsigned bounds capture the 14671 * signed bounds 14672 * 3) the signed bounds cross zero, so they tell us nothing 14673 * about the result 14674 * If the value in dst_reg is known nonnegative, then again the 14675 * unsigned bounds capture the signed bounds. 14676 * Thus, in all cases it suffices to blow away our signed bounds 14677 * and rely on inferring new ones from the unsigned bounds and 14678 * var_off of the result. 14679 */ 14680 dst_reg->s32_min_value = S32_MIN; 14681 dst_reg->s32_max_value = S32_MAX; 14682 14683 dst_reg->var_off = tnum_rshift(subreg, umin_val); 14684 dst_reg->u32_min_value >>= umax_val; 14685 dst_reg->u32_max_value >>= umin_val; 14686 14687 __mark_reg64_unbounded(dst_reg); 14688 __update_reg32_bounds(dst_reg); 14689 } 14690 14691 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 14692 struct bpf_reg_state *src_reg) 14693 { 14694 u64 umax_val = src_reg->umax_value; 14695 u64 umin_val = src_reg->umin_value; 14696 14697 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 14698 * be negative, then either: 14699 * 1) src_reg might be zero, so the sign bit of the result is 14700 * unknown, so we lose our signed bounds 14701 * 2) it's known negative, thus the unsigned bounds capture the 14702 * signed bounds 14703 * 3) the signed bounds cross zero, so they tell us nothing 14704 * about the result 14705 * If the value in dst_reg is known nonnegative, then again the 14706 * unsigned bounds capture the signed bounds. 14707 * Thus, in all cases it suffices to blow away our signed bounds 14708 * and rely on inferring new ones from the unsigned bounds and 14709 * var_off of the result. 14710 */ 14711 dst_reg->smin_value = S64_MIN; 14712 dst_reg->smax_value = S64_MAX; 14713 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 14714 dst_reg->umin_value >>= umax_val; 14715 dst_reg->umax_value >>= umin_val; 14716 14717 /* Its not easy to operate on alu32 bounds here because it depends 14718 * on bits being shifted in. Take easy way out and mark unbounded 14719 * so we can recalculate later from tnum. 14720 */ 14721 __mark_reg32_unbounded(dst_reg); 14722 __update_reg_bounds(dst_reg); 14723 } 14724 14725 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 14726 struct bpf_reg_state *src_reg) 14727 { 14728 u64 umin_val = src_reg->u32_min_value; 14729 14730 /* Upon reaching here, src_known is true and 14731 * umax_val is equal to umin_val. 14732 */ 14733 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 14734 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 14735 14736 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 14737 14738 /* blow away the dst_reg umin_value/umax_value and rely on 14739 * dst_reg var_off to refine the result. 14740 */ 14741 dst_reg->u32_min_value = 0; 14742 dst_reg->u32_max_value = U32_MAX; 14743 14744 __mark_reg64_unbounded(dst_reg); 14745 __update_reg32_bounds(dst_reg); 14746 } 14747 14748 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 14749 struct bpf_reg_state *src_reg) 14750 { 14751 u64 umin_val = src_reg->umin_value; 14752 14753 /* Upon reaching here, src_known is true and umax_val is equal 14754 * to umin_val. 14755 */ 14756 dst_reg->smin_value >>= umin_val; 14757 dst_reg->smax_value >>= umin_val; 14758 14759 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 14760 14761 /* blow away the dst_reg umin_value/umax_value and rely on 14762 * dst_reg var_off to refine the result. 14763 */ 14764 dst_reg->umin_value = 0; 14765 dst_reg->umax_value = U64_MAX; 14766 14767 /* Its not easy to operate on alu32 bounds here because it depends 14768 * on bits being shifted in from upper 32-bits. Take easy way out 14769 * and mark unbounded so we can recalculate later from tnum. 14770 */ 14771 __mark_reg32_unbounded(dst_reg); 14772 __update_reg_bounds(dst_reg); 14773 } 14774 14775 static void scalar_byte_swap(struct bpf_reg_state *dst_reg, struct bpf_insn *insn) 14776 { 14777 /* 14778 * Byte swap operation - update var_off using tnum_bswap. 14779 * Three cases: 14780 * 1. bswap(16|32|64): opcode=0xd7 (BPF_END | BPF_ALU64 | BPF_TO_LE) 14781 * unconditional swap 14782 * 2. to_le(16|32|64): opcode=0xd4 (BPF_END | BPF_ALU | BPF_TO_LE) 14783 * swap on big-endian, truncation or no-op on little-endian 14784 * 3. to_be(16|32|64): opcode=0xdc (BPF_END | BPF_ALU | BPF_TO_BE) 14785 * swap on little-endian, truncation or no-op on big-endian 14786 */ 14787 14788 bool alu64 = BPF_CLASS(insn->code) == BPF_ALU64; 14789 bool to_le = BPF_SRC(insn->code) == BPF_TO_LE; 14790 bool is_big_endian; 14791 #ifdef CONFIG_CPU_BIG_ENDIAN 14792 is_big_endian = true; 14793 #else 14794 is_big_endian = false; 14795 #endif 14796 /* Apply bswap if alu64 or switch between big-endian and little-endian machines */ 14797 bool need_bswap = alu64 || (to_le == is_big_endian); 14798 14799 /* 14800 * If the register is mutated, manually reset its scalar ID to break 14801 * any existing ties and avoid incorrect bounds propagation. 14802 */ 14803 if (need_bswap || insn->imm == 16 || insn->imm == 32) 14804 clear_scalar_id(dst_reg); 14805 14806 if (need_bswap) { 14807 if (insn->imm == 16) 14808 dst_reg->var_off = tnum_bswap16(dst_reg->var_off); 14809 else if (insn->imm == 32) 14810 dst_reg->var_off = tnum_bswap32(dst_reg->var_off); 14811 else if (insn->imm == 64) 14812 dst_reg->var_off = tnum_bswap64(dst_reg->var_off); 14813 /* 14814 * Byteswap scrambles the range, so we must reset bounds. 14815 * Bounds will be re-derived from the new tnum later. 14816 */ 14817 __mark_reg_unbounded(dst_reg); 14818 } 14819 /* For bswap16/32, truncate dst register to match the swapped size */ 14820 if (insn->imm == 16 || insn->imm == 32) 14821 coerce_reg_to_size(dst_reg, insn->imm / 8); 14822 } 14823 14824 static bool is_safe_to_compute_dst_reg_range(struct bpf_insn *insn, 14825 const struct bpf_reg_state *src_reg) 14826 { 14827 bool src_is_const = false; 14828 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 14829 14830 if (insn_bitness == 32) { 14831 if (tnum_subreg_is_const(src_reg->var_off) 14832 && src_reg->s32_min_value == src_reg->s32_max_value 14833 && src_reg->u32_min_value == src_reg->u32_max_value) 14834 src_is_const = true; 14835 } else { 14836 if (tnum_is_const(src_reg->var_off) 14837 && src_reg->smin_value == src_reg->smax_value 14838 && src_reg->umin_value == src_reg->umax_value) 14839 src_is_const = true; 14840 } 14841 14842 switch (BPF_OP(insn->code)) { 14843 case BPF_ADD: 14844 case BPF_SUB: 14845 case BPF_NEG: 14846 case BPF_AND: 14847 case BPF_XOR: 14848 case BPF_OR: 14849 case BPF_MUL: 14850 case BPF_END: 14851 return true; 14852 14853 /* 14854 * Division and modulo operators range is only safe to compute when the 14855 * divisor is a constant. 14856 */ 14857 case BPF_DIV: 14858 case BPF_MOD: 14859 return src_is_const; 14860 14861 /* Shift operators range is only computable if shift dimension operand 14862 * is a constant. Shifts greater than 31 or 63 are undefined. This 14863 * includes shifts by a negative number. 14864 */ 14865 case BPF_LSH: 14866 case BPF_RSH: 14867 case BPF_ARSH: 14868 return (src_is_const && src_reg->umax_value < insn_bitness); 14869 default: 14870 return false; 14871 } 14872 } 14873 14874 static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *insn, 14875 struct bpf_reg_state *dst_reg) 14876 { 14877 struct bpf_verifier_state *branch; 14878 struct bpf_reg_state *regs; 14879 bool alu32; 14880 14881 if (dst_reg->smin_value == -1 && dst_reg->smax_value == 0) 14882 alu32 = false; 14883 else if (dst_reg->s32_min_value == -1 && dst_reg->s32_max_value == 0) 14884 alu32 = true; 14885 else 14886 return 0; 14887 14888 branch = push_stack(env, env->insn_idx, env->insn_idx, false); 14889 if (IS_ERR(branch)) 14890 return PTR_ERR(branch); 14891 14892 regs = branch->frame[branch->curframe]->regs; 14893 if (alu32) { 14894 __mark_reg32_known(®s[insn->dst_reg], 0); 14895 __mark_reg32_known(dst_reg, -1ull); 14896 } else { 14897 __mark_reg_known(®s[insn->dst_reg], 0); 14898 __mark_reg_known(dst_reg, -1ull); 14899 } 14900 return 0; 14901 } 14902 14903 /* WARNING: This function does calculations on 64-bit values, but the actual 14904 * execution may occur on 32-bit values. Therefore, things like bitshifts 14905 * need extra checks in the 32-bit case. 14906 */ 14907 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 14908 struct bpf_insn *insn, 14909 struct bpf_reg_state *dst_reg, 14910 struct bpf_reg_state src_reg) 14911 { 14912 u8 opcode = BPF_OP(insn->code); 14913 s16 off = insn->off; 14914 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 14915 int ret; 14916 14917 if (!is_safe_to_compute_dst_reg_range(insn, &src_reg)) { 14918 __mark_reg_unknown(env, dst_reg); 14919 return 0; 14920 } 14921 14922 if (sanitize_needed(opcode)) { 14923 ret = sanitize_val_alu(env, insn); 14924 if (ret < 0) 14925 return sanitize_err(env, insn, ret, NULL, NULL); 14926 } 14927 14928 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 14929 * There are two classes of instructions: The first class we track both 14930 * alu32 and alu64 sign/unsigned bounds independently this provides the 14931 * greatest amount of precision when alu operations are mixed with jmp32 14932 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 14933 * and BPF_OR. This is possible because these ops have fairly easy to 14934 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 14935 * See alu32 verifier tests for examples. The second class of 14936 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 14937 * with regards to tracking sign/unsigned bounds because the bits may 14938 * cross subreg boundaries in the alu64 case. When this happens we mark 14939 * the reg unbounded in the subreg bound space and use the resulting 14940 * tnum to calculate an approximation of the sign/unsigned bounds. 14941 */ 14942 switch (opcode) { 14943 case BPF_ADD: 14944 scalar32_min_max_add(dst_reg, &src_reg); 14945 scalar_min_max_add(dst_reg, &src_reg); 14946 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 14947 break; 14948 case BPF_SUB: 14949 scalar32_min_max_sub(dst_reg, &src_reg); 14950 scalar_min_max_sub(dst_reg, &src_reg); 14951 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 14952 break; 14953 case BPF_NEG: 14954 env->fake_reg[0] = *dst_reg; 14955 __mark_reg_known(dst_reg, 0); 14956 scalar32_min_max_sub(dst_reg, &env->fake_reg[0]); 14957 scalar_min_max_sub(dst_reg, &env->fake_reg[0]); 14958 dst_reg->var_off = tnum_neg(env->fake_reg[0].var_off); 14959 break; 14960 case BPF_MUL: 14961 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 14962 scalar32_min_max_mul(dst_reg, &src_reg); 14963 scalar_min_max_mul(dst_reg, &src_reg); 14964 break; 14965 case BPF_DIV: 14966 /* BPF div specification: x / 0 = 0 */ 14967 if ((alu32 && src_reg.u32_min_value == 0) || (!alu32 && src_reg.umin_value == 0)) { 14968 ___mark_reg_known(dst_reg, 0); 14969 break; 14970 } 14971 if (alu32) 14972 if (off == 1) 14973 scalar32_min_max_sdiv(dst_reg, &src_reg); 14974 else 14975 scalar32_min_max_udiv(dst_reg, &src_reg); 14976 else 14977 if (off == 1) 14978 scalar_min_max_sdiv(dst_reg, &src_reg); 14979 else 14980 scalar_min_max_udiv(dst_reg, &src_reg); 14981 break; 14982 case BPF_MOD: 14983 /* BPF mod specification: x % 0 = x */ 14984 if ((alu32 && src_reg.u32_min_value == 0) || (!alu32 && src_reg.umin_value == 0)) 14985 break; 14986 if (alu32) 14987 if (off == 1) 14988 scalar32_min_max_smod(dst_reg, &src_reg); 14989 else 14990 scalar32_min_max_umod(dst_reg, &src_reg); 14991 else 14992 if (off == 1) 14993 scalar_min_max_smod(dst_reg, &src_reg); 14994 else 14995 scalar_min_max_umod(dst_reg, &src_reg); 14996 break; 14997 case BPF_AND: 14998 if (tnum_is_const(src_reg.var_off)) { 14999 ret = maybe_fork_scalars(env, insn, dst_reg); 15000 if (ret) 15001 return ret; 15002 } 15003 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 15004 scalar32_min_max_and(dst_reg, &src_reg); 15005 scalar_min_max_and(dst_reg, &src_reg); 15006 break; 15007 case BPF_OR: 15008 if (tnum_is_const(src_reg.var_off)) { 15009 ret = maybe_fork_scalars(env, insn, dst_reg); 15010 if (ret) 15011 return ret; 15012 } 15013 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 15014 scalar32_min_max_or(dst_reg, &src_reg); 15015 scalar_min_max_or(dst_reg, &src_reg); 15016 break; 15017 case BPF_XOR: 15018 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 15019 scalar32_min_max_xor(dst_reg, &src_reg); 15020 scalar_min_max_xor(dst_reg, &src_reg); 15021 break; 15022 case BPF_LSH: 15023 if (alu32) 15024 scalar32_min_max_lsh(dst_reg, &src_reg); 15025 else 15026 scalar_min_max_lsh(dst_reg, &src_reg); 15027 break; 15028 case BPF_RSH: 15029 if (alu32) 15030 scalar32_min_max_rsh(dst_reg, &src_reg); 15031 else 15032 scalar_min_max_rsh(dst_reg, &src_reg); 15033 break; 15034 case BPF_ARSH: 15035 if (alu32) 15036 scalar32_min_max_arsh(dst_reg, &src_reg); 15037 else 15038 scalar_min_max_arsh(dst_reg, &src_reg); 15039 break; 15040 case BPF_END: 15041 scalar_byte_swap(dst_reg, insn); 15042 break; 15043 default: 15044 break; 15045 } 15046 15047 /* 15048 * ALU32 ops are zero extended into 64bit register. 15049 * 15050 * BPF_END is already handled inside the helper (truncation), 15051 * so skip zext here to avoid unexpected zero extension. 15052 * e.g., le64: opcode=(BPF_END|BPF_ALU|BPF_TO_LE), imm=0x40 15053 * This is a 64bit byte swap operation with alu32==true, 15054 * but we should not zero extend the result. 15055 */ 15056 if (alu32 && opcode != BPF_END) 15057 zext_32_to_64(dst_reg); 15058 reg_bounds_sync(dst_reg); 15059 return 0; 15060 } 15061 15062 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 15063 * and var_off. 15064 */ 15065 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 15066 struct bpf_insn *insn) 15067 { 15068 struct bpf_verifier_state *vstate = env->cur_state; 15069 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 15070 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 15071 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 15072 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 15073 u8 opcode = BPF_OP(insn->code); 15074 int err; 15075 15076 dst_reg = ®s[insn->dst_reg]; 15077 if (BPF_SRC(insn->code) == BPF_X) 15078 src_reg = ®s[insn->src_reg]; 15079 else 15080 src_reg = NULL; 15081 15082 /* Case where at least one operand is an arena. */ 15083 if (dst_reg->type == PTR_TO_ARENA || (src_reg && src_reg->type == PTR_TO_ARENA)) { 15084 struct bpf_insn_aux_data *aux = cur_aux(env); 15085 15086 if (dst_reg->type != PTR_TO_ARENA) 15087 *dst_reg = *src_reg; 15088 15089 dst_reg->subreg_def = env->insn_idx + 1; 15090 15091 if (BPF_CLASS(insn->code) == BPF_ALU64) 15092 /* 15093 * 32-bit operations zero upper bits automatically. 15094 * 64-bit operations need to be converted to 32. 15095 */ 15096 aux->needs_zext = true; 15097 15098 /* Any arithmetic operations are allowed on arena pointers */ 15099 return 0; 15100 } 15101 15102 if (dst_reg->type != SCALAR_VALUE) 15103 ptr_reg = dst_reg; 15104 15105 if (BPF_SRC(insn->code) == BPF_X) { 15106 if (src_reg->type != SCALAR_VALUE) { 15107 if (dst_reg->type != SCALAR_VALUE) { 15108 /* Combining two pointers by any ALU op yields 15109 * an arbitrary scalar. Disallow all math except 15110 * pointer subtraction 15111 */ 15112 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 15113 mark_reg_unknown(env, regs, insn->dst_reg); 15114 return 0; 15115 } 15116 verbose(env, "R%d pointer %s pointer prohibited\n", 15117 insn->dst_reg, 15118 bpf_alu_string[opcode >> 4]); 15119 return -EACCES; 15120 } else { 15121 /* scalar += pointer 15122 * This is legal, but we have to reverse our 15123 * src/dest handling in computing the range 15124 */ 15125 err = mark_chain_precision(env, insn->dst_reg); 15126 if (err) 15127 return err; 15128 return adjust_ptr_min_max_vals(env, insn, 15129 src_reg, dst_reg); 15130 } 15131 } else if (ptr_reg) { 15132 /* pointer += scalar */ 15133 err = mark_chain_precision(env, insn->src_reg); 15134 if (err) 15135 return err; 15136 return adjust_ptr_min_max_vals(env, insn, 15137 dst_reg, src_reg); 15138 } else if (dst_reg->precise) { 15139 /* if dst_reg is precise, src_reg should be precise as well */ 15140 err = mark_chain_precision(env, insn->src_reg); 15141 if (err) 15142 return err; 15143 } 15144 } else { 15145 /* Pretend the src is a reg with a known value, since we only 15146 * need to be able to read from this state. 15147 */ 15148 off_reg.type = SCALAR_VALUE; 15149 __mark_reg_known(&off_reg, insn->imm); 15150 src_reg = &off_reg; 15151 if (ptr_reg) /* pointer += K */ 15152 return adjust_ptr_min_max_vals(env, insn, 15153 ptr_reg, src_reg); 15154 } 15155 15156 /* Got here implies adding two SCALAR_VALUEs */ 15157 if (WARN_ON_ONCE(ptr_reg)) { 15158 print_verifier_state(env, vstate, vstate->curframe, true); 15159 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 15160 return -EFAULT; 15161 } 15162 if (WARN_ON(!src_reg)) { 15163 print_verifier_state(env, vstate, vstate->curframe, true); 15164 verbose(env, "verifier internal error: no src_reg\n"); 15165 return -EFAULT; 15166 } 15167 /* 15168 * For alu32 linked register tracking, we need to check dst_reg's 15169 * umax_value before the ALU operation. After adjust_scalar_min_max_vals(), 15170 * alu32 ops will have zero-extended the result, making umax_value <= U32_MAX. 15171 */ 15172 u64 dst_umax = dst_reg->umax_value; 15173 15174 err = adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 15175 if (err) 15176 return err; 15177 /* 15178 * Compilers can generate the code 15179 * r1 = r2 15180 * r1 += 0x1 15181 * if r2 < 1000 goto ... 15182 * use r1 in memory access 15183 * So remember constant delta between r2 and r1 and update r1 after 15184 * 'if' condition. 15185 */ 15186 if (env->bpf_capable && 15187 (BPF_OP(insn->code) == BPF_ADD || BPF_OP(insn->code) == BPF_SUB) && 15188 dst_reg->id && is_reg_const(src_reg, alu32) && 15189 !(BPF_SRC(insn->code) == BPF_X && insn->src_reg == insn->dst_reg)) { 15190 u64 val = reg_const_value(src_reg, alu32); 15191 s32 off; 15192 15193 if (!alu32 && ((s64)val < S32_MIN || (s64)val > S32_MAX)) 15194 goto clear_id; 15195 15196 if (alu32 && (dst_umax > U32_MAX)) 15197 goto clear_id; 15198 15199 off = (s32)val; 15200 15201 if (BPF_OP(insn->code) == BPF_SUB) { 15202 /* Negating S32_MIN would overflow */ 15203 if (off == S32_MIN) 15204 goto clear_id; 15205 off = -off; 15206 } 15207 15208 if (dst_reg->id & BPF_ADD_CONST) { 15209 /* 15210 * If the register already went through rX += val 15211 * we cannot accumulate another val into rx->off. 15212 */ 15213 clear_id: 15214 clear_scalar_id(dst_reg); 15215 } else { 15216 if (alu32) 15217 dst_reg->id |= BPF_ADD_CONST32; 15218 else 15219 dst_reg->id |= BPF_ADD_CONST64; 15220 dst_reg->delta = off; 15221 } 15222 } else { 15223 /* 15224 * Make sure ID is cleared otherwise dst_reg min/max could be 15225 * incorrectly propagated into other registers by sync_linked_regs() 15226 */ 15227 clear_scalar_id(dst_reg); 15228 } 15229 return 0; 15230 } 15231 15232 /* check validity of 32-bit and 64-bit arithmetic operations */ 15233 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 15234 { 15235 struct bpf_reg_state *regs = cur_regs(env); 15236 u8 opcode = BPF_OP(insn->code); 15237 int err; 15238 15239 if (opcode == BPF_END || opcode == BPF_NEG) { 15240 /* check src operand */ 15241 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15242 if (err) 15243 return err; 15244 15245 if (is_pointer_value(env, insn->dst_reg)) { 15246 verbose(env, "R%d pointer arithmetic prohibited\n", 15247 insn->dst_reg); 15248 return -EACCES; 15249 } 15250 15251 /* check dest operand */ 15252 if (regs[insn->dst_reg].type == SCALAR_VALUE) { 15253 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15254 err = err ?: adjust_scalar_min_max_vals(env, insn, 15255 ®s[insn->dst_reg], 15256 regs[insn->dst_reg]); 15257 } else { 15258 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15259 } 15260 if (err) 15261 return err; 15262 15263 } else if (opcode == BPF_MOV) { 15264 15265 if (BPF_SRC(insn->code) == BPF_X) { 15266 if (insn->off == BPF_ADDR_SPACE_CAST) { 15267 if (!env->prog->aux->arena) { 15268 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 15269 return -EINVAL; 15270 } 15271 } 15272 15273 /* check src operand */ 15274 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15275 if (err) 15276 return err; 15277 } 15278 15279 /* check dest operand, mark as required later */ 15280 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15281 if (err) 15282 return err; 15283 15284 if (BPF_SRC(insn->code) == BPF_X) { 15285 struct bpf_reg_state *src_reg = regs + insn->src_reg; 15286 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 15287 15288 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15289 if (insn->imm) { 15290 /* off == BPF_ADDR_SPACE_CAST */ 15291 mark_reg_unknown(env, regs, insn->dst_reg); 15292 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 15293 dst_reg->type = PTR_TO_ARENA; 15294 /* PTR_TO_ARENA is 32-bit */ 15295 dst_reg->subreg_def = env->insn_idx + 1; 15296 } 15297 } else if (insn->off == 0) { 15298 /* case: R1 = R2 15299 * copy register state to dest reg 15300 */ 15301 assign_scalar_id_before_mov(env, src_reg); 15302 copy_register_state(dst_reg, src_reg); 15303 dst_reg->subreg_def = DEF_NOT_SUBREG; 15304 } else { 15305 /* case: R1 = (s8, s16 s32)R2 */ 15306 if (is_pointer_value(env, insn->src_reg)) { 15307 verbose(env, 15308 "R%d sign-extension part of pointer\n", 15309 insn->src_reg); 15310 return -EACCES; 15311 } else if (src_reg->type == SCALAR_VALUE) { 15312 bool no_sext; 15313 15314 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 15315 if (no_sext) 15316 assign_scalar_id_before_mov(env, src_reg); 15317 copy_register_state(dst_reg, src_reg); 15318 if (!no_sext) 15319 clear_scalar_id(dst_reg); 15320 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 15321 dst_reg->subreg_def = DEF_NOT_SUBREG; 15322 } else { 15323 mark_reg_unknown(env, regs, insn->dst_reg); 15324 } 15325 } 15326 } else { 15327 /* R1 = (u32) R2 */ 15328 if (is_pointer_value(env, insn->src_reg)) { 15329 verbose(env, 15330 "R%d partial copy of pointer\n", 15331 insn->src_reg); 15332 return -EACCES; 15333 } else if (src_reg->type == SCALAR_VALUE) { 15334 if (insn->off == 0) { 15335 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 15336 15337 if (is_src_reg_u32) 15338 assign_scalar_id_before_mov(env, src_reg); 15339 copy_register_state(dst_reg, src_reg); 15340 /* Make sure ID is cleared if src_reg is not in u32 15341 * range otherwise dst_reg min/max could be incorrectly 15342 * propagated into src_reg by sync_linked_regs() 15343 */ 15344 if (!is_src_reg_u32) 15345 clear_scalar_id(dst_reg); 15346 dst_reg->subreg_def = env->insn_idx + 1; 15347 } else { 15348 /* case: W1 = (s8, s16)W2 */ 15349 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 15350 15351 if (no_sext) 15352 assign_scalar_id_before_mov(env, src_reg); 15353 copy_register_state(dst_reg, src_reg); 15354 if (!no_sext) 15355 clear_scalar_id(dst_reg); 15356 dst_reg->subreg_def = env->insn_idx + 1; 15357 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 15358 } 15359 } else { 15360 mark_reg_unknown(env, regs, 15361 insn->dst_reg); 15362 } 15363 zext_32_to_64(dst_reg); 15364 reg_bounds_sync(dst_reg); 15365 } 15366 } else { 15367 /* case: R = imm 15368 * remember the value we stored into this reg 15369 */ 15370 /* clear any state __mark_reg_known doesn't set */ 15371 mark_reg_unknown(env, regs, insn->dst_reg); 15372 regs[insn->dst_reg].type = SCALAR_VALUE; 15373 if (BPF_CLASS(insn->code) == BPF_ALU64) { 15374 __mark_reg_known(regs + insn->dst_reg, 15375 insn->imm); 15376 } else { 15377 __mark_reg_known(regs + insn->dst_reg, 15378 (u32)insn->imm); 15379 } 15380 } 15381 15382 } else { /* all other ALU ops: and, sub, xor, add, ... */ 15383 15384 if (BPF_SRC(insn->code) == BPF_X) { 15385 /* check src1 operand */ 15386 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15387 if (err) 15388 return err; 15389 } 15390 15391 /* check src2 operand */ 15392 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15393 if (err) 15394 return err; 15395 15396 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 15397 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 15398 verbose(env, "div by zero\n"); 15399 return -EINVAL; 15400 } 15401 15402 if ((opcode == BPF_LSH || opcode == BPF_RSH || 15403 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 15404 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 15405 15406 if (insn->imm < 0 || insn->imm >= size) { 15407 verbose(env, "invalid shift %d\n", insn->imm); 15408 return -EINVAL; 15409 } 15410 } 15411 15412 /* check dest operand */ 15413 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15414 err = err ?: adjust_reg_min_max_vals(env, insn); 15415 if (err) 15416 return err; 15417 } 15418 15419 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 15420 } 15421 15422 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 15423 struct bpf_reg_state *dst_reg, 15424 enum bpf_reg_type type, 15425 bool range_right_open) 15426 { 15427 struct bpf_func_state *state; 15428 struct bpf_reg_state *reg; 15429 int new_range; 15430 15431 if (dst_reg->umax_value == 0 && range_right_open) 15432 /* This doesn't give us any range */ 15433 return; 15434 15435 if (dst_reg->umax_value > MAX_PACKET_OFF) 15436 /* Risk of overflow. For instance, ptr + (1<<63) may be less 15437 * than pkt_end, but that's because it's also less than pkt. 15438 */ 15439 return; 15440 15441 new_range = dst_reg->umax_value; 15442 if (range_right_open) 15443 new_range++; 15444 15445 /* Examples for register markings: 15446 * 15447 * pkt_data in dst register: 15448 * 15449 * r2 = r3; 15450 * r2 += 8; 15451 * if (r2 > pkt_end) goto <handle exception> 15452 * <access okay> 15453 * 15454 * r2 = r3; 15455 * r2 += 8; 15456 * if (r2 < pkt_end) goto <access okay> 15457 * <handle exception> 15458 * 15459 * Where: 15460 * r2 == dst_reg, pkt_end == src_reg 15461 * r2=pkt(id=n,off=8,r=0) 15462 * r3=pkt(id=n,off=0,r=0) 15463 * 15464 * pkt_data in src register: 15465 * 15466 * r2 = r3; 15467 * r2 += 8; 15468 * if (pkt_end >= r2) goto <access okay> 15469 * <handle exception> 15470 * 15471 * r2 = r3; 15472 * r2 += 8; 15473 * if (pkt_end <= r2) goto <handle exception> 15474 * <access okay> 15475 * 15476 * Where: 15477 * pkt_end == dst_reg, r2 == src_reg 15478 * r2=pkt(id=n,off=8,r=0) 15479 * r3=pkt(id=n,off=0,r=0) 15480 * 15481 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 15482 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 15483 * and [r3, r3 + 8-1) respectively is safe to access depending on 15484 * the check. 15485 */ 15486 15487 /* If our ids match, then we must have the same max_value. And we 15488 * don't care about the other reg's fixed offset, since if it's too big 15489 * the range won't allow anything. 15490 * dst_reg->umax_value is known < MAX_PACKET_OFF, therefore it fits in a u16. 15491 */ 15492 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 15493 if (reg->type == type && reg->id == dst_reg->id) 15494 /* keep the maximum range already checked */ 15495 reg->range = max(reg->range, new_range); 15496 })); 15497 } 15498 15499 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15500 u8 opcode, bool is_jmp32); 15501 static u8 rev_opcode(u8 opcode); 15502 15503 /* 15504 * Learn more information about live branches by simulating refinement on both branches. 15505 * regs_refine_cond_op() is sound, so producing ill-formed register bounds for the branch means 15506 * that branch is dead. 15507 */ 15508 static int simulate_both_branches_taken(struct bpf_verifier_env *env, u8 opcode, bool is_jmp32) 15509 { 15510 /* Fallthrough (FALSE) branch */ 15511 regs_refine_cond_op(&env->false_reg1, &env->false_reg2, rev_opcode(opcode), is_jmp32); 15512 reg_bounds_sync(&env->false_reg1); 15513 reg_bounds_sync(&env->false_reg2); 15514 /* 15515 * If there is a range bounds violation in *any* of the abstract values in either 15516 * reg_states in the FALSE branch (i.e. reg1, reg2), the FALSE branch must be dead. Only 15517 * TRUE branch will be taken. 15518 */ 15519 if (range_bounds_violation(&env->false_reg1) || range_bounds_violation(&env->false_reg2)) 15520 return 1; 15521 15522 /* Jump (TRUE) branch */ 15523 regs_refine_cond_op(&env->true_reg1, &env->true_reg2, opcode, is_jmp32); 15524 reg_bounds_sync(&env->true_reg1); 15525 reg_bounds_sync(&env->true_reg2); 15526 /* 15527 * If there is a range bounds violation in *any* of the abstract values in either 15528 * reg_states in the TRUE branch (i.e. true_reg1, true_reg2), the TRUE branch must be dead. 15529 * Only FALSE branch will be taken. 15530 */ 15531 if (range_bounds_violation(&env->true_reg1) || range_bounds_violation(&env->true_reg2)) 15532 return 0; 15533 15534 /* Both branches are possible, we can't determine which one will be taken. */ 15535 return -1; 15536 } 15537 15538 /* 15539 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 15540 */ 15541 static int is_scalar_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15542 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15543 { 15544 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 15545 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 15546 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 15547 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 15548 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 15549 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 15550 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 15551 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 15552 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 15553 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 15554 15555 if (reg1 == reg2) { 15556 switch (opcode) { 15557 case BPF_JGE: 15558 case BPF_JLE: 15559 case BPF_JSGE: 15560 case BPF_JSLE: 15561 case BPF_JEQ: 15562 return 1; 15563 case BPF_JGT: 15564 case BPF_JLT: 15565 case BPF_JSGT: 15566 case BPF_JSLT: 15567 case BPF_JNE: 15568 return 0; 15569 case BPF_JSET: 15570 if (tnum_is_const(t1)) 15571 return t1.value != 0; 15572 else 15573 return (smin1 <= 0 && smax1 >= 0) ? -1 : 1; 15574 default: 15575 return -1; 15576 } 15577 } 15578 15579 switch (opcode) { 15580 case BPF_JEQ: 15581 /* constants, umin/umax and smin/smax checks would be 15582 * redundant in this case because they all should match 15583 */ 15584 if (tnum_is_const(t1) && tnum_is_const(t2)) 15585 return t1.value == t2.value; 15586 if (!tnum_overlap(t1, t2)) 15587 return 0; 15588 /* non-overlapping ranges */ 15589 if (umin1 > umax2 || umax1 < umin2) 15590 return 0; 15591 if (smin1 > smax2 || smax1 < smin2) 15592 return 0; 15593 if (!is_jmp32) { 15594 /* if 64-bit ranges are inconclusive, see if we can 15595 * utilize 32-bit subrange knowledge to eliminate 15596 * branches that can't be taken a priori 15597 */ 15598 if (reg1->u32_min_value > reg2->u32_max_value || 15599 reg1->u32_max_value < reg2->u32_min_value) 15600 return 0; 15601 if (reg1->s32_min_value > reg2->s32_max_value || 15602 reg1->s32_max_value < reg2->s32_min_value) 15603 return 0; 15604 } 15605 break; 15606 case BPF_JNE: 15607 /* constants, umin/umax and smin/smax checks would be 15608 * redundant in this case because they all should match 15609 */ 15610 if (tnum_is_const(t1) && tnum_is_const(t2)) 15611 return t1.value != t2.value; 15612 if (!tnum_overlap(t1, t2)) 15613 return 1; 15614 /* non-overlapping ranges */ 15615 if (umin1 > umax2 || umax1 < umin2) 15616 return 1; 15617 if (smin1 > smax2 || smax1 < smin2) 15618 return 1; 15619 if (!is_jmp32) { 15620 /* if 64-bit ranges are inconclusive, see if we can 15621 * utilize 32-bit subrange knowledge to eliminate 15622 * branches that can't be taken a priori 15623 */ 15624 if (reg1->u32_min_value > reg2->u32_max_value || 15625 reg1->u32_max_value < reg2->u32_min_value) 15626 return 1; 15627 if (reg1->s32_min_value > reg2->s32_max_value || 15628 reg1->s32_max_value < reg2->s32_min_value) 15629 return 1; 15630 } 15631 break; 15632 case BPF_JSET: 15633 if (!is_reg_const(reg2, is_jmp32)) { 15634 swap(reg1, reg2); 15635 swap(t1, t2); 15636 } 15637 if (!is_reg_const(reg2, is_jmp32)) 15638 return -1; 15639 if ((~t1.mask & t1.value) & t2.value) 15640 return 1; 15641 if (!((t1.mask | t1.value) & t2.value)) 15642 return 0; 15643 break; 15644 case BPF_JGT: 15645 if (umin1 > umax2) 15646 return 1; 15647 else if (umax1 <= umin2) 15648 return 0; 15649 break; 15650 case BPF_JSGT: 15651 if (smin1 > smax2) 15652 return 1; 15653 else if (smax1 <= smin2) 15654 return 0; 15655 break; 15656 case BPF_JLT: 15657 if (umax1 < umin2) 15658 return 1; 15659 else if (umin1 >= umax2) 15660 return 0; 15661 break; 15662 case BPF_JSLT: 15663 if (smax1 < smin2) 15664 return 1; 15665 else if (smin1 >= smax2) 15666 return 0; 15667 break; 15668 case BPF_JGE: 15669 if (umin1 >= umax2) 15670 return 1; 15671 else if (umax1 < umin2) 15672 return 0; 15673 break; 15674 case BPF_JSGE: 15675 if (smin1 >= smax2) 15676 return 1; 15677 else if (smax1 < smin2) 15678 return 0; 15679 break; 15680 case BPF_JLE: 15681 if (umax1 <= umin2) 15682 return 1; 15683 else if (umin1 > umax2) 15684 return 0; 15685 break; 15686 case BPF_JSLE: 15687 if (smax1 <= smin2) 15688 return 1; 15689 else if (smin1 > smax2) 15690 return 0; 15691 break; 15692 } 15693 15694 return simulate_both_branches_taken(env, opcode, is_jmp32); 15695 } 15696 15697 static int flip_opcode(u32 opcode) 15698 { 15699 /* How can we transform "a <op> b" into "b <op> a"? */ 15700 static const u8 opcode_flip[16] = { 15701 /* these stay the same */ 15702 [BPF_JEQ >> 4] = BPF_JEQ, 15703 [BPF_JNE >> 4] = BPF_JNE, 15704 [BPF_JSET >> 4] = BPF_JSET, 15705 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 15706 [BPF_JGE >> 4] = BPF_JLE, 15707 [BPF_JGT >> 4] = BPF_JLT, 15708 [BPF_JLE >> 4] = BPF_JGE, 15709 [BPF_JLT >> 4] = BPF_JGT, 15710 [BPF_JSGE >> 4] = BPF_JSLE, 15711 [BPF_JSGT >> 4] = BPF_JSLT, 15712 [BPF_JSLE >> 4] = BPF_JSGE, 15713 [BPF_JSLT >> 4] = BPF_JSGT 15714 }; 15715 return opcode_flip[opcode >> 4]; 15716 } 15717 15718 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 15719 struct bpf_reg_state *src_reg, 15720 u8 opcode) 15721 { 15722 struct bpf_reg_state *pkt; 15723 15724 if (src_reg->type == PTR_TO_PACKET_END) { 15725 pkt = dst_reg; 15726 } else if (dst_reg->type == PTR_TO_PACKET_END) { 15727 pkt = src_reg; 15728 opcode = flip_opcode(opcode); 15729 } else { 15730 return -1; 15731 } 15732 15733 if (pkt->range >= 0) 15734 return -1; 15735 15736 switch (opcode) { 15737 case BPF_JLE: 15738 /* pkt <= pkt_end */ 15739 fallthrough; 15740 case BPF_JGT: 15741 /* pkt > pkt_end */ 15742 if (pkt->range == BEYOND_PKT_END) 15743 /* pkt has at last one extra byte beyond pkt_end */ 15744 return opcode == BPF_JGT; 15745 break; 15746 case BPF_JLT: 15747 /* pkt < pkt_end */ 15748 fallthrough; 15749 case BPF_JGE: 15750 /* pkt >= pkt_end */ 15751 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 15752 return opcode == BPF_JGE; 15753 break; 15754 } 15755 return -1; 15756 } 15757 15758 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 15759 * and return: 15760 * 1 - branch will be taken and "goto target" will be executed 15761 * 0 - branch will not be taken and fall-through to next insn 15762 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 15763 * range [0,10] 15764 */ 15765 static int is_branch_taken(struct bpf_verifier_env *env, struct bpf_reg_state *reg1, 15766 struct bpf_reg_state *reg2, u8 opcode, bool is_jmp32) 15767 { 15768 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 15769 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 15770 15771 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 15772 u64 val; 15773 15774 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 15775 if (!is_reg_const(reg2, is_jmp32)) { 15776 opcode = flip_opcode(opcode); 15777 swap(reg1, reg2); 15778 } 15779 /* and ensure that reg2 is a constant */ 15780 if (!is_reg_const(reg2, is_jmp32)) 15781 return -1; 15782 15783 if (!reg_not_null(reg1)) 15784 return -1; 15785 15786 /* If pointer is valid tests against zero will fail so we can 15787 * use this to direct branch taken. 15788 */ 15789 val = reg_const_value(reg2, is_jmp32); 15790 if (val != 0) 15791 return -1; 15792 15793 switch (opcode) { 15794 case BPF_JEQ: 15795 return 0; 15796 case BPF_JNE: 15797 return 1; 15798 default: 15799 return -1; 15800 } 15801 } 15802 15803 /* now deal with two scalars, but not necessarily constants */ 15804 return is_scalar_branch_taken(env, reg1, reg2, opcode, is_jmp32); 15805 } 15806 15807 /* Opcode that corresponds to a *false* branch condition. 15808 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 15809 */ 15810 static u8 rev_opcode(u8 opcode) 15811 { 15812 switch (opcode) { 15813 case BPF_JEQ: return BPF_JNE; 15814 case BPF_JNE: return BPF_JEQ; 15815 /* JSET doesn't have it's reverse opcode in BPF, so add 15816 * BPF_X flag to denote the reverse of that operation 15817 */ 15818 case BPF_JSET: return BPF_JSET | BPF_X; 15819 case BPF_JSET | BPF_X: return BPF_JSET; 15820 case BPF_JGE: return BPF_JLT; 15821 case BPF_JGT: return BPF_JLE; 15822 case BPF_JLE: return BPF_JGT; 15823 case BPF_JLT: return BPF_JGE; 15824 case BPF_JSGE: return BPF_JSLT; 15825 case BPF_JSGT: return BPF_JSLE; 15826 case BPF_JSLE: return BPF_JSGT; 15827 case BPF_JSLT: return BPF_JSGE; 15828 default: return 0; 15829 } 15830 } 15831 15832 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 15833 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 15834 u8 opcode, bool is_jmp32) 15835 { 15836 struct tnum t; 15837 u64 val; 15838 15839 /* In case of GE/GT/SGE/JST, reuse LE/LT/SLE/SLT logic from below */ 15840 switch (opcode) { 15841 case BPF_JGE: 15842 case BPF_JGT: 15843 case BPF_JSGE: 15844 case BPF_JSGT: 15845 opcode = flip_opcode(opcode); 15846 swap(reg1, reg2); 15847 break; 15848 default: 15849 break; 15850 } 15851 15852 switch (opcode) { 15853 case BPF_JEQ: 15854 if (is_jmp32) { 15855 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 15856 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 15857 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 15858 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 15859 reg2->u32_min_value = reg1->u32_min_value; 15860 reg2->u32_max_value = reg1->u32_max_value; 15861 reg2->s32_min_value = reg1->s32_min_value; 15862 reg2->s32_max_value = reg1->s32_max_value; 15863 15864 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 15865 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15866 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 15867 } else { 15868 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 15869 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 15870 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 15871 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 15872 reg2->umin_value = reg1->umin_value; 15873 reg2->umax_value = reg1->umax_value; 15874 reg2->smin_value = reg1->smin_value; 15875 reg2->smax_value = reg1->smax_value; 15876 15877 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 15878 reg2->var_off = reg1->var_off; 15879 } 15880 break; 15881 case BPF_JNE: 15882 if (!is_reg_const(reg2, is_jmp32)) 15883 swap(reg1, reg2); 15884 if (!is_reg_const(reg2, is_jmp32)) 15885 break; 15886 15887 /* try to recompute the bound of reg1 if reg2 is a const and 15888 * is exactly the edge of reg1. 15889 */ 15890 val = reg_const_value(reg2, is_jmp32); 15891 if (is_jmp32) { 15892 /* u32_min_value is not equal to 0xffffffff at this point, 15893 * because otherwise u32_max_value is 0xffffffff as well, 15894 * in such a case both reg1 and reg2 would be constants, 15895 * jump would be predicted and regs_refine_cond_op() 15896 * wouldn't be called. 15897 * 15898 * Same reasoning works for all {u,s}{min,max}{32,64} cases 15899 * below. 15900 */ 15901 if (reg1->u32_min_value == (u32)val) 15902 reg1->u32_min_value++; 15903 if (reg1->u32_max_value == (u32)val) 15904 reg1->u32_max_value--; 15905 if (reg1->s32_min_value == (s32)val) 15906 reg1->s32_min_value++; 15907 if (reg1->s32_max_value == (s32)val) 15908 reg1->s32_max_value--; 15909 } else { 15910 if (reg1->umin_value == (u64)val) 15911 reg1->umin_value++; 15912 if (reg1->umax_value == (u64)val) 15913 reg1->umax_value--; 15914 if (reg1->smin_value == (s64)val) 15915 reg1->smin_value++; 15916 if (reg1->smax_value == (s64)val) 15917 reg1->smax_value--; 15918 } 15919 break; 15920 case BPF_JSET: 15921 if (!is_reg_const(reg2, is_jmp32)) 15922 swap(reg1, reg2); 15923 if (!is_reg_const(reg2, is_jmp32)) 15924 break; 15925 val = reg_const_value(reg2, is_jmp32); 15926 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 15927 * requires single bit to learn something useful. E.g., if we 15928 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 15929 * are actually set? We can learn something definite only if 15930 * it's a single-bit value to begin with. 15931 * 15932 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 15933 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 15934 * bit 1 is set, which we can readily use in adjustments. 15935 */ 15936 if (!is_power_of_2(val)) 15937 break; 15938 if (is_jmp32) { 15939 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 15940 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15941 } else { 15942 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 15943 } 15944 break; 15945 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 15946 if (!is_reg_const(reg2, is_jmp32)) 15947 swap(reg1, reg2); 15948 if (!is_reg_const(reg2, is_jmp32)) 15949 break; 15950 val = reg_const_value(reg2, is_jmp32); 15951 /* Forget the ranges before narrowing tnums, to avoid invariant 15952 * violations if we're on a dead branch. 15953 */ 15954 __mark_reg_unbounded(reg1); 15955 if (is_jmp32) { 15956 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 15957 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 15958 } else { 15959 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 15960 } 15961 break; 15962 case BPF_JLE: 15963 if (is_jmp32) { 15964 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 15965 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 15966 } else { 15967 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 15968 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 15969 } 15970 break; 15971 case BPF_JLT: 15972 if (is_jmp32) { 15973 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 15974 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 15975 } else { 15976 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 15977 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 15978 } 15979 break; 15980 case BPF_JSLE: 15981 if (is_jmp32) { 15982 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 15983 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 15984 } else { 15985 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 15986 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 15987 } 15988 break; 15989 case BPF_JSLT: 15990 if (is_jmp32) { 15991 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 15992 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 15993 } else { 15994 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 15995 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 15996 } 15997 break; 15998 default: 15999 return; 16000 } 16001 } 16002 16003 /* Check for invariant violations on the registers for both branches of a condition */ 16004 static int regs_bounds_sanity_check_branches(struct bpf_verifier_env *env) 16005 { 16006 int err; 16007 16008 err = reg_bounds_sanity_check(env, &env->true_reg1, "true_reg1"); 16009 err = err ?: reg_bounds_sanity_check(env, &env->true_reg2, "true_reg2"); 16010 err = err ?: reg_bounds_sanity_check(env, &env->false_reg1, "false_reg1"); 16011 err = err ?: reg_bounds_sanity_check(env, &env->false_reg2, "false_reg2"); 16012 return err; 16013 } 16014 16015 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 16016 struct bpf_reg_state *reg, u32 id, 16017 bool is_null) 16018 { 16019 if (type_may_be_null(reg->type) && reg->id == id && 16020 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 16021 /* Old offset should have been known-zero, because we don't 16022 * allow pointer arithmetic on pointers that might be NULL. 16023 * If we see this happening, don't convert the register. 16024 * 16025 * But in some cases, some helpers that return local kptrs 16026 * advance offset for the returned pointer. In those cases, 16027 * it is fine to expect to see reg->var_off. 16028 */ 16029 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 16030 WARN_ON_ONCE(!tnum_equals_const(reg->var_off, 0))) 16031 return; 16032 if (is_null) { 16033 /* We don't need id and ref_obj_id from this point 16034 * onwards anymore, thus we should better reset it, 16035 * so that state pruning has chances to take effect. 16036 */ 16037 __mark_reg_known_zero(reg); 16038 reg->type = SCALAR_VALUE; 16039 16040 return; 16041 } 16042 16043 mark_ptr_not_null_reg(reg); 16044 16045 if (!reg_may_point_to_spin_lock(reg)) { 16046 /* For not-NULL ptr, reg->ref_obj_id will be reset 16047 * in release_reference(). 16048 * 16049 * reg->id is still used by spin_lock ptr. Other 16050 * than spin_lock ptr type, reg->id can be reset. 16051 */ 16052 reg->id = 0; 16053 } 16054 } 16055 } 16056 16057 /* The logic is similar to find_good_pkt_pointers(), both could eventually 16058 * be folded together at some point. 16059 */ 16060 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 16061 bool is_null) 16062 { 16063 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 16064 struct bpf_reg_state *regs = state->regs, *reg; 16065 u32 ref_obj_id = regs[regno].ref_obj_id; 16066 u32 id = regs[regno].id; 16067 16068 if (ref_obj_id && ref_obj_id == id && is_null) 16069 /* regs[regno] is in the " == NULL" branch. 16070 * No one could have freed the reference state before 16071 * doing the NULL check. 16072 */ 16073 WARN_ON_ONCE(release_reference_nomark(vstate, id)); 16074 16075 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 16076 mark_ptr_or_null_reg(state, reg, id, is_null); 16077 })); 16078 } 16079 16080 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 16081 struct bpf_reg_state *dst_reg, 16082 struct bpf_reg_state *src_reg, 16083 struct bpf_verifier_state *this_branch, 16084 struct bpf_verifier_state *other_branch) 16085 { 16086 if (BPF_SRC(insn->code) != BPF_X) 16087 return false; 16088 16089 /* Pointers are always 64-bit. */ 16090 if (BPF_CLASS(insn->code) == BPF_JMP32) 16091 return false; 16092 16093 switch (BPF_OP(insn->code)) { 16094 case BPF_JGT: 16095 if ((dst_reg->type == PTR_TO_PACKET && 16096 src_reg->type == PTR_TO_PACKET_END) || 16097 (dst_reg->type == PTR_TO_PACKET_META && 16098 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16099 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 16100 find_good_pkt_pointers(this_branch, dst_reg, 16101 dst_reg->type, false); 16102 mark_pkt_end(other_branch, insn->dst_reg, true); 16103 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16104 src_reg->type == PTR_TO_PACKET) || 16105 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16106 src_reg->type == PTR_TO_PACKET_META)) { 16107 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 16108 find_good_pkt_pointers(other_branch, src_reg, 16109 src_reg->type, true); 16110 mark_pkt_end(this_branch, insn->src_reg, false); 16111 } else { 16112 return false; 16113 } 16114 break; 16115 case BPF_JLT: 16116 if ((dst_reg->type == PTR_TO_PACKET && 16117 src_reg->type == PTR_TO_PACKET_END) || 16118 (dst_reg->type == PTR_TO_PACKET_META && 16119 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16120 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 16121 find_good_pkt_pointers(other_branch, dst_reg, 16122 dst_reg->type, true); 16123 mark_pkt_end(this_branch, insn->dst_reg, false); 16124 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16125 src_reg->type == PTR_TO_PACKET) || 16126 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16127 src_reg->type == PTR_TO_PACKET_META)) { 16128 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 16129 find_good_pkt_pointers(this_branch, src_reg, 16130 src_reg->type, false); 16131 mark_pkt_end(other_branch, insn->src_reg, true); 16132 } else { 16133 return false; 16134 } 16135 break; 16136 case BPF_JGE: 16137 if ((dst_reg->type == PTR_TO_PACKET && 16138 src_reg->type == PTR_TO_PACKET_END) || 16139 (dst_reg->type == PTR_TO_PACKET_META && 16140 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16141 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 16142 find_good_pkt_pointers(this_branch, dst_reg, 16143 dst_reg->type, true); 16144 mark_pkt_end(other_branch, insn->dst_reg, false); 16145 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16146 src_reg->type == PTR_TO_PACKET) || 16147 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16148 src_reg->type == PTR_TO_PACKET_META)) { 16149 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 16150 find_good_pkt_pointers(other_branch, src_reg, 16151 src_reg->type, false); 16152 mark_pkt_end(this_branch, insn->src_reg, true); 16153 } else { 16154 return false; 16155 } 16156 break; 16157 case BPF_JLE: 16158 if ((dst_reg->type == PTR_TO_PACKET && 16159 src_reg->type == PTR_TO_PACKET_END) || 16160 (dst_reg->type == PTR_TO_PACKET_META && 16161 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 16162 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 16163 find_good_pkt_pointers(other_branch, dst_reg, 16164 dst_reg->type, false); 16165 mark_pkt_end(this_branch, insn->dst_reg, true); 16166 } else if ((dst_reg->type == PTR_TO_PACKET_END && 16167 src_reg->type == PTR_TO_PACKET) || 16168 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 16169 src_reg->type == PTR_TO_PACKET_META)) { 16170 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 16171 find_good_pkt_pointers(this_branch, src_reg, 16172 src_reg->type, true); 16173 mark_pkt_end(other_branch, insn->src_reg, false); 16174 } else { 16175 return false; 16176 } 16177 break; 16178 default: 16179 return false; 16180 } 16181 16182 return true; 16183 } 16184 16185 static void __collect_linked_regs(struct linked_regs *reg_set, struct bpf_reg_state *reg, 16186 u32 id, u32 frameno, u32 spi_or_reg, bool is_reg) 16187 { 16188 struct linked_reg *e; 16189 16190 if (reg->type != SCALAR_VALUE || (reg->id & ~BPF_ADD_CONST) != id) 16191 return; 16192 16193 e = linked_regs_push(reg_set); 16194 if (e) { 16195 e->frameno = frameno; 16196 e->is_reg = is_reg; 16197 e->regno = spi_or_reg; 16198 } else { 16199 clear_scalar_id(reg); 16200 } 16201 } 16202 16203 /* For all R being scalar registers or spilled scalar registers 16204 * in verifier state, save R in linked_regs if R->id == id. 16205 * If there are too many Rs sharing same id, reset id for leftover Rs. 16206 */ 16207 static void collect_linked_regs(struct bpf_verifier_env *env, 16208 struct bpf_verifier_state *vstate, 16209 u32 id, 16210 struct linked_regs *linked_regs) 16211 { 16212 struct bpf_insn_aux_data *aux = env->insn_aux_data; 16213 struct bpf_func_state *func; 16214 struct bpf_reg_state *reg; 16215 u16 live_regs; 16216 int i, j; 16217 16218 id = id & ~BPF_ADD_CONST; 16219 for (i = vstate->curframe; i >= 0; i--) { 16220 live_regs = aux[bpf_frame_insn_idx(vstate, i)].live_regs_before; 16221 func = vstate->frame[i]; 16222 for (j = 0; j < BPF_REG_FP; j++) { 16223 if (!(live_regs & BIT(j))) 16224 continue; 16225 reg = &func->regs[j]; 16226 __collect_linked_regs(linked_regs, reg, id, i, j, true); 16227 } 16228 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 16229 if (!bpf_is_spilled_reg(&func->stack[j])) 16230 continue; 16231 reg = &func->stack[j].spilled_ptr; 16232 __collect_linked_regs(linked_regs, reg, id, i, j, false); 16233 } 16234 } 16235 } 16236 16237 /* For all R in linked_regs, copy known_reg range into R 16238 * if R->id == known_reg->id. 16239 */ 16240 static void sync_linked_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *vstate, 16241 struct bpf_reg_state *known_reg, struct linked_regs *linked_regs) 16242 { 16243 struct bpf_reg_state fake_reg; 16244 struct bpf_reg_state *reg; 16245 struct linked_reg *e; 16246 int i; 16247 16248 for (i = 0; i < linked_regs->cnt; ++i) { 16249 e = &linked_regs->entries[i]; 16250 reg = e->is_reg ? &vstate->frame[e->frameno]->regs[e->regno] 16251 : &vstate->frame[e->frameno]->stack[e->spi].spilled_ptr; 16252 if (reg->type != SCALAR_VALUE || reg == known_reg) 16253 continue; 16254 if ((reg->id & ~BPF_ADD_CONST) != (known_reg->id & ~BPF_ADD_CONST)) 16255 continue; 16256 /* 16257 * Skip mixed 32/64-bit links: the delta relationship doesn't 16258 * hold across different ALU widths. 16259 */ 16260 if (((reg->id ^ known_reg->id) & BPF_ADD_CONST) == BPF_ADD_CONST) 16261 continue; 16262 if ((!(reg->id & BPF_ADD_CONST) && !(known_reg->id & BPF_ADD_CONST)) || 16263 reg->delta == known_reg->delta) { 16264 s32 saved_subreg_def = reg->subreg_def; 16265 16266 copy_register_state(reg, known_reg); 16267 reg->subreg_def = saved_subreg_def; 16268 } else { 16269 s32 saved_subreg_def = reg->subreg_def; 16270 s32 saved_off = reg->delta; 16271 u32 saved_id = reg->id; 16272 16273 fake_reg.type = SCALAR_VALUE; 16274 __mark_reg_known(&fake_reg, (s64)reg->delta - (s64)known_reg->delta); 16275 16276 /* reg = known_reg; reg += delta */ 16277 copy_register_state(reg, known_reg); 16278 /* 16279 * Must preserve off, id and subreg_def flag, 16280 * otherwise another sync_linked_regs() will be incorrect. 16281 */ 16282 reg->delta = saved_off; 16283 reg->id = saved_id; 16284 reg->subreg_def = saved_subreg_def; 16285 16286 scalar32_min_max_add(reg, &fake_reg); 16287 scalar_min_max_add(reg, &fake_reg); 16288 reg->var_off = tnum_add(reg->var_off, fake_reg.var_off); 16289 if ((reg->id | known_reg->id) & BPF_ADD_CONST32) 16290 zext_32_to_64(reg); 16291 reg_bounds_sync(reg); 16292 } 16293 if (e->is_reg) 16294 mark_reg_scratched(env, e->regno); 16295 else 16296 mark_stack_slot_scratched(env, e->spi); 16297 } 16298 } 16299 16300 static int check_cond_jmp_op(struct bpf_verifier_env *env, 16301 struct bpf_insn *insn, int *insn_idx) 16302 { 16303 struct bpf_verifier_state *this_branch = env->cur_state; 16304 struct bpf_verifier_state *other_branch; 16305 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 16306 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 16307 struct bpf_reg_state *eq_branch_regs; 16308 struct linked_regs linked_regs = {}; 16309 u8 opcode = BPF_OP(insn->code); 16310 int insn_flags = 0; 16311 bool is_jmp32; 16312 int pred = -1; 16313 int err; 16314 16315 /* Only conditional jumps are expected to reach here. */ 16316 if (opcode == BPF_JA || opcode > BPF_JCOND) { 16317 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 16318 return -EINVAL; 16319 } 16320 16321 if (opcode == BPF_JCOND) { 16322 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 16323 int idx = *insn_idx; 16324 16325 prev_st = find_prev_entry(env, cur_st->parent, idx); 16326 16327 /* branch out 'fallthrough' insn as a new state to explore */ 16328 queued_st = push_stack(env, idx + 1, idx, false); 16329 if (IS_ERR(queued_st)) 16330 return PTR_ERR(queued_st); 16331 16332 queued_st->may_goto_depth++; 16333 if (prev_st) 16334 widen_imprecise_scalars(env, prev_st, queued_st); 16335 *insn_idx += insn->off; 16336 return 0; 16337 } 16338 16339 /* check src2 operand */ 16340 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16341 if (err) 16342 return err; 16343 16344 dst_reg = ®s[insn->dst_reg]; 16345 if (BPF_SRC(insn->code) == BPF_X) { 16346 /* check src1 operand */ 16347 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16348 if (err) 16349 return err; 16350 16351 src_reg = ®s[insn->src_reg]; 16352 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 16353 is_pointer_value(env, insn->src_reg)) { 16354 verbose(env, "R%d pointer comparison prohibited\n", 16355 insn->src_reg); 16356 return -EACCES; 16357 } 16358 16359 if (src_reg->type == PTR_TO_STACK) 16360 insn_flags |= INSN_F_SRC_REG_STACK; 16361 if (dst_reg->type == PTR_TO_STACK) 16362 insn_flags |= INSN_F_DST_REG_STACK; 16363 } else { 16364 src_reg = &env->fake_reg[0]; 16365 memset(src_reg, 0, sizeof(*src_reg)); 16366 src_reg->type = SCALAR_VALUE; 16367 __mark_reg_known(src_reg, insn->imm); 16368 16369 if (dst_reg->type == PTR_TO_STACK) 16370 insn_flags |= INSN_F_DST_REG_STACK; 16371 } 16372 16373 if (insn_flags) { 16374 err = bpf_push_jmp_history(env, this_branch, insn_flags, 0); 16375 if (err) 16376 return err; 16377 } 16378 16379 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 16380 copy_register_state(&env->false_reg1, dst_reg); 16381 copy_register_state(&env->false_reg2, src_reg); 16382 copy_register_state(&env->true_reg1, dst_reg); 16383 copy_register_state(&env->true_reg2, src_reg); 16384 pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32); 16385 if (pred >= 0) { 16386 /* If we get here with a dst_reg pointer type it is because 16387 * above is_branch_taken() special cased the 0 comparison. 16388 */ 16389 if (!__is_pointer_value(false, dst_reg)) 16390 err = mark_chain_precision(env, insn->dst_reg); 16391 if (BPF_SRC(insn->code) == BPF_X && !err && 16392 !__is_pointer_value(false, src_reg)) 16393 err = mark_chain_precision(env, insn->src_reg); 16394 if (err) 16395 return err; 16396 } 16397 16398 if (pred == 1) { 16399 /* Only follow the goto, ignore fall-through. If needed, push 16400 * the fall-through branch for simulation under speculative 16401 * execution. 16402 */ 16403 if (!env->bypass_spec_v1) { 16404 err = sanitize_speculative_path(env, insn, *insn_idx + 1, *insn_idx); 16405 if (err < 0) 16406 return err; 16407 } 16408 if (env->log.level & BPF_LOG_LEVEL) 16409 print_insn_state(env, this_branch, this_branch->curframe); 16410 *insn_idx += insn->off; 16411 return 0; 16412 } else if (pred == 0) { 16413 /* Only follow the fall-through branch, since that's where the 16414 * program will go. If needed, push the goto branch for 16415 * simulation under speculative execution. 16416 */ 16417 if (!env->bypass_spec_v1) { 16418 err = sanitize_speculative_path(env, insn, *insn_idx + insn->off + 1, 16419 *insn_idx); 16420 if (err < 0) 16421 return err; 16422 } 16423 if (env->log.level & BPF_LOG_LEVEL) 16424 print_insn_state(env, this_branch, this_branch->curframe); 16425 return 0; 16426 } 16427 16428 /* Push scalar registers sharing same ID to jump history, 16429 * do this before creating 'other_branch', so that both 16430 * 'this_branch' and 'other_branch' share this history 16431 * if parent state is created. 16432 */ 16433 if (BPF_SRC(insn->code) == BPF_X && src_reg->type == SCALAR_VALUE && src_reg->id) 16434 collect_linked_regs(env, this_branch, src_reg->id, &linked_regs); 16435 if (dst_reg->type == SCALAR_VALUE && dst_reg->id) 16436 collect_linked_regs(env, this_branch, dst_reg->id, &linked_regs); 16437 if (linked_regs.cnt > 1) { 16438 err = bpf_push_jmp_history(env, this_branch, 0, linked_regs_pack(&linked_regs)); 16439 if (err) 16440 return err; 16441 } 16442 16443 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false); 16444 if (IS_ERR(other_branch)) 16445 return PTR_ERR(other_branch); 16446 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 16447 16448 err = regs_bounds_sanity_check_branches(env); 16449 if (err) 16450 return err; 16451 16452 copy_register_state(dst_reg, &env->false_reg1); 16453 copy_register_state(src_reg, &env->false_reg2); 16454 copy_register_state(&other_branch_regs[insn->dst_reg], &env->true_reg1); 16455 if (BPF_SRC(insn->code) == BPF_X) 16456 copy_register_state(&other_branch_regs[insn->src_reg], &env->true_reg2); 16457 16458 if (BPF_SRC(insn->code) == BPF_X && 16459 src_reg->type == SCALAR_VALUE && src_reg->id && 16460 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 16461 sync_linked_regs(env, this_branch, src_reg, &linked_regs); 16462 sync_linked_regs(env, other_branch, &other_branch_regs[insn->src_reg], 16463 &linked_regs); 16464 } 16465 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 16466 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 16467 sync_linked_regs(env, this_branch, dst_reg, &linked_regs); 16468 sync_linked_regs(env, other_branch, &other_branch_regs[insn->dst_reg], 16469 &linked_regs); 16470 } 16471 16472 /* if one pointer register is compared to another pointer 16473 * register check if PTR_MAYBE_NULL could be lifted. 16474 * E.g. register A - maybe null 16475 * register B - not null 16476 * for JNE A, B, ... - A is not null in the false branch; 16477 * for JEQ A, B, ... - A is not null in the true branch. 16478 * 16479 * Since PTR_TO_BTF_ID points to a kernel struct that does 16480 * not need to be null checked by the BPF program, i.e., 16481 * could be null even without PTR_MAYBE_NULL marking, so 16482 * only propagate nullness when neither reg is that type. 16483 */ 16484 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 16485 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 16486 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 16487 base_type(src_reg->type) != PTR_TO_BTF_ID && 16488 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 16489 eq_branch_regs = NULL; 16490 switch (opcode) { 16491 case BPF_JEQ: 16492 eq_branch_regs = other_branch_regs; 16493 break; 16494 case BPF_JNE: 16495 eq_branch_regs = regs; 16496 break; 16497 default: 16498 /* do nothing */ 16499 break; 16500 } 16501 if (eq_branch_regs) { 16502 if (type_may_be_null(src_reg->type)) 16503 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 16504 else 16505 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 16506 } 16507 } 16508 16509 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 16510 * Also does the same detection for a register whose the value is 16511 * known to be 0. 16512 * NOTE: these optimizations below are related with pointer comparison 16513 * which will never be JMP32. 16514 */ 16515 if (!is_jmp32 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 16516 type_may_be_null(dst_reg->type) && 16517 ((BPF_SRC(insn->code) == BPF_K && insn->imm == 0) || 16518 (BPF_SRC(insn->code) == BPF_X && bpf_register_is_null(src_reg)))) { 16519 /* Mark all identical registers in each branch as either 16520 * safe or unknown depending R == 0 or R != 0 conditional. 16521 */ 16522 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 16523 opcode == BPF_JNE); 16524 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 16525 opcode == BPF_JEQ); 16526 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 16527 this_branch, other_branch) && 16528 is_pointer_value(env, insn->dst_reg)) { 16529 verbose(env, "R%d pointer comparison prohibited\n", 16530 insn->dst_reg); 16531 return -EACCES; 16532 } 16533 if (env->log.level & BPF_LOG_LEVEL) 16534 print_insn_state(env, this_branch, this_branch->curframe); 16535 return 0; 16536 } 16537 16538 /* verify BPF_LD_IMM64 instruction */ 16539 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 16540 { 16541 struct bpf_insn_aux_data *aux = cur_aux(env); 16542 struct bpf_reg_state *regs = cur_regs(env); 16543 struct bpf_reg_state *dst_reg; 16544 struct bpf_map *map; 16545 int err; 16546 16547 if (BPF_SIZE(insn->code) != BPF_DW) { 16548 verbose(env, "invalid BPF_LD_IMM insn\n"); 16549 return -EINVAL; 16550 } 16551 16552 err = check_reg_arg(env, insn->dst_reg, DST_OP); 16553 if (err) 16554 return err; 16555 16556 dst_reg = ®s[insn->dst_reg]; 16557 if (insn->src_reg == 0) { 16558 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 16559 16560 dst_reg->type = SCALAR_VALUE; 16561 __mark_reg_known(®s[insn->dst_reg], imm); 16562 return 0; 16563 } 16564 16565 /* All special src_reg cases are listed below. From this point onwards 16566 * we either succeed and assign a corresponding dst_reg->type after 16567 * zeroing the offset, or fail and reject the program. 16568 */ 16569 mark_reg_known_zero(env, regs, insn->dst_reg); 16570 16571 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 16572 dst_reg->type = aux->btf_var.reg_type; 16573 switch (base_type(dst_reg->type)) { 16574 case PTR_TO_MEM: 16575 dst_reg->mem_size = aux->btf_var.mem_size; 16576 break; 16577 case PTR_TO_BTF_ID: 16578 dst_reg->btf = aux->btf_var.btf; 16579 dst_reg->btf_id = aux->btf_var.btf_id; 16580 break; 16581 default: 16582 verifier_bug(env, "pseudo btf id: unexpected dst reg type"); 16583 return -EFAULT; 16584 } 16585 return 0; 16586 } 16587 16588 if (insn->src_reg == BPF_PSEUDO_FUNC) { 16589 struct bpf_prog_aux *aux = env->prog->aux; 16590 u32 subprogno = bpf_find_subprog(env, 16591 env->insn_idx + insn->imm + 1); 16592 16593 if (!aux->func_info) { 16594 verbose(env, "missing btf func_info\n"); 16595 return -EINVAL; 16596 } 16597 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 16598 verbose(env, "callback function not static\n"); 16599 return -EINVAL; 16600 } 16601 16602 dst_reg->type = PTR_TO_FUNC; 16603 dst_reg->subprogno = subprogno; 16604 return 0; 16605 } 16606 16607 map = env->used_maps[aux->map_index]; 16608 16609 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 16610 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 16611 if (map->map_type == BPF_MAP_TYPE_ARENA) { 16612 __mark_reg_unknown(env, dst_reg); 16613 dst_reg->map_ptr = map; 16614 return 0; 16615 } 16616 __mark_reg_known(dst_reg, aux->map_off); 16617 dst_reg->type = PTR_TO_MAP_VALUE; 16618 dst_reg->map_ptr = map; 16619 WARN_ON_ONCE(map->map_type != BPF_MAP_TYPE_INSN_ARRAY && 16620 map->max_entries != 1); 16621 /* We want reg->id to be same (0) as map_value is not distinct */ 16622 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 16623 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 16624 dst_reg->type = CONST_PTR_TO_MAP; 16625 dst_reg->map_ptr = map; 16626 } else { 16627 verifier_bug(env, "unexpected src reg value for ldimm64"); 16628 return -EFAULT; 16629 } 16630 16631 return 0; 16632 } 16633 16634 static bool may_access_skb(enum bpf_prog_type type) 16635 { 16636 switch (type) { 16637 case BPF_PROG_TYPE_SOCKET_FILTER: 16638 case BPF_PROG_TYPE_SCHED_CLS: 16639 case BPF_PROG_TYPE_SCHED_ACT: 16640 return true; 16641 default: 16642 return false; 16643 } 16644 } 16645 16646 /* verify safety of LD_ABS|LD_IND instructions: 16647 * - they can only appear in the programs where ctx == skb 16648 * - since they are wrappers of function calls, they scratch R1-R5 registers, 16649 * preserve R6-R9, and store return value into R0 16650 * 16651 * Implicit input: 16652 * ctx == skb == R6 == CTX 16653 * 16654 * Explicit input: 16655 * SRC == any register 16656 * IMM == 32-bit immediate 16657 * 16658 * Output: 16659 * R0 - 8/16/32-bit skb data converted to cpu endianness 16660 */ 16661 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 16662 { 16663 struct bpf_reg_state *regs = cur_regs(env); 16664 static const int ctx_reg = BPF_REG_6; 16665 u8 mode = BPF_MODE(insn->code); 16666 int i, err; 16667 16668 if (!may_access_skb(resolve_prog_type(env->prog))) { 16669 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 16670 return -EINVAL; 16671 } 16672 16673 if (!env->ops->gen_ld_abs) { 16674 verifier_bug(env, "gen_ld_abs is null"); 16675 return -EFAULT; 16676 } 16677 16678 /* check whether implicit source operand (register R6) is readable */ 16679 err = check_reg_arg(env, ctx_reg, SRC_OP); 16680 if (err) 16681 return err; 16682 16683 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 16684 * gen_ld_abs() may terminate the program at runtime, leading to 16685 * reference leak. 16686 */ 16687 err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]"); 16688 if (err) 16689 return err; 16690 16691 if (regs[ctx_reg].type != PTR_TO_CTX) { 16692 verbose(env, 16693 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 16694 return -EINVAL; 16695 } 16696 16697 if (mode == BPF_IND) { 16698 /* check explicit source operand */ 16699 err = check_reg_arg(env, insn->src_reg, SRC_OP); 16700 if (err) 16701 return err; 16702 } 16703 16704 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 16705 if (err < 0) 16706 return err; 16707 16708 /* reset caller saved regs to unreadable */ 16709 for (i = 0; i < CALLER_SAVED_REGS; i++) { 16710 bpf_mark_reg_not_init(env, ®s[caller_saved[i]]); 16711 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 16712 } 16713 16714 /* mark destination R0 register as readable, since it contains 16715 * the value fetched from the packet. 16716 * Already marked as written above. 16717 */ 16718 mark_reg_unknown(env, regs, BPF_REG_0); 16719 /* ld_abs load up to 32-bit skb data. */ 16720 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 16721 /* 16722 * See bpf_gen_ld_abs() which emits a hidden BPF_EXIT with r0=0 16723 * which must be explored by the verifier when in a subprog. 16724 */ 16725 if (env->cur_state->curframe) { 16726 struct bpf_verifier_state *branch; 16727 16728 mark_reg_scratched(env, BPF_REG_0); 16729 branch = push_stack(env, env->insn_idx + 1, env->insn_idx, false); 16730 if (IS_ERR(branch)) 16731 return PTR_ERR(branch); 16732 mark_reg_known_zero(env, regs, BPF_REG_0); 16733 err = prepare_func_exit(env, &env->insn_idx); 16734 if (err) 16735 return err; 16736 env->insn_idx--; 16737 } 16738 return 0; 16739 } 16740 16741 16742 static bool return_retval_range(struct bpf_verifier_env *env, struct bpf_retval_range *range) 16743 { 16744 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16745 16746 /* Default return value range. */ 16747 *range = retval_range(0, 1); 16748 16749 switch (prog_type) { 16750 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 16751 switch (env->prog->expected_attach_type) { 16752 case BPF_CGROUP_UDP4_RECVMSG: 16753 case BPF_CGROUP_UDP6_RECVMSG: 16754 case BPF_CGROUP_UNIX_RECVMSG: 16755 case BPF_CGROUP_INET4_GETPEERNAME: 16756 case BPF_CGROUP_INET6_GETPEERNAME: 16757 case BPF_CGROUP_UNIX_GETPEERNAME: 16758 case BPF_CGROUP_INET4_GETSOCKNAME: 16759 case BPF_CGROUP_INET6_GETSOCKNAME: 16760 case BPF_CGROUP_UNIX_GETSOCKNAME: 16761 *range = retval_range(1, 1); 16762 break; 16763 case BPF_CGROUP_INET4_BIND: 16764 case BPF_CGROUP_INET6_BIND: 16765 *range = retval_range(0, 3); 16766 break; 16767 default: 16768 break; 16769 } 16770 break; 16771 case BPF_PROG_TYPE_CGROUP_SKB: 16772 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) 16773 *range = retval_range(0, 3); 16774 break; 16775 case BPF_PROG_TYPE_CGROUP_SOCK: 16776 case BPF_PROG_TYPE_SOCK_OPS: 16777 case BPF_PROG_TYPE_CGROUP_DEVICE: 16778 case BPF_PROG_TYPE_CGROUP_SYSCTL: 16779 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 16780 break; 16781 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16782 if (!env->prog->aux->attach_btf_id) 16783 return false; 16784 *range = retval_range(0, 0); 16785 break; 16786 case BPF_PROG_TYPE_TRACING: 16787 switch (env->prog->expected_attach_type) { 16788 case BPF_TRACE_FENTRY: 16789 case BPF_TRACE_FEXIT: 16790 case BPF_TRACE_FSESSION: 16791 *range = retval_range(0, 0); 16792 break; 16793 case BPF_TRACE_RAW_TP: 16794 case BPF_MODIFY_RETURN: 16795 return false; 16796 case BPF_TRACE_ITER: 16797 default: 16798 break; 16799 } 16800 break; 16801 case BPF_PROG_TYPE_KPROBE: 16802 switch (env->prog->expected_attach_type) { 16803 case BPF_TRACE_KPROBE_SESSION: 16804 case BPF_TRACE_UPROBE_SESSION: 16805 break; 16806 default: 16807 return false; 16808 } 16809 break; 16810 case BPF_PROG_TYPE_SK_LOOKUP: 16811 *range = retval_range(SK_DROP, SK_PASS); 16812 break; 16813 16814 case BPF_PROG_TYPE_LSM: 16815 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 16816 /* no range found, any return value is allowed */ 16817 if (!get_func_retval_range(env->prog, range)) 16818 return false; 16819 /* no restricted range, any return value is allowed */ 16820 if (range->minval == S32_MIN && range->maxval == S32_MAX) 16821 return false; 16822 range->return_32bit = true; 16823 } else if (!env->prog->aux->attach_func_proto->type) { 16824 /* Make sure programs that attach to void 16825 * hooks don't try to modify return value. 16826 */ 16827 *range = retval_range(1, 1); 16828 } 16829 break; 16830 16831 case BPF_PROG_TYPE_NETFILTER: 16832 *range = retval_range(NF_DROP, NF_ACCEPT); 16833 break; 16834 case BPF_PROG_TYPE_STRUCT_OPS: 16835 *range = retval_range(0, 0); 16836 break; 16837 case BPF_PROG_TYPE_EXT: 16838 /* freplace program can return anything as its return value 16839 * depends on the to-be-replaced kernel func or bpf program. 16840 */ 16841 default: 16842 return false; 16843 } 16844 16845 /* Continue calculating. */ 16846 16847 return true; 16848 } 16849 16850 static bool program_returns_void(struct bpf_verifier_env *env) 16851 { 16852 const struct bpf_prog *prog = env->prog; 16853 enum bpf_prog_type prog_type = prog->type; 16854 16855 switch (prog_type) { 16856 case BPF_PROG_TYPE_LSM: 16857 /* See return_retval_range, for BPF_LSM_CGROUP can be 0 or 0-1 depending on hook. */ 16858 if (prog->expected_attach_type != BPF_LSM_CGROUP && 16859 !prog->aux->attach_func_proto->type) 16860 return true; 16861 break; 16862 case BPF_PROG_TYPE_STRUCT_OPS: 16863 if (!prog->aux->attach_func_proto->type) 16864 return true; 16865 break; 16866 case BPF_PROG_TYPE_EXT: 16867 /* 16868 * If the actual program is an extension, let it 16869 * return void - attaching will succeed only if the 16870 * program being replaced also returns void, and since 16871 * it has passed verification its actual type doesn't matter. 16872 */ 16873 if (subprog_returns_void(env, 0)) 16874 return true; 16875 break; 16876 default: 16877 break; 16878 } 16879 return false; 16880 } 16881 16882 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 16883 { 16884 const char *exit_ctx = "At program exit"; 16885 struct tnum enforce_attach_type_range = tnum_unknown; 16886 const struct bpf_prog *prog = env->prog; 16887 struct bpf_reg_state *reg = reg_state(env, regno); 16888 struct bpf_retval_range range = retval_range(0, 1); 16889 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 16890 struct bpf_func_state *frame = env->cur_state->frame[0]; 16891 const struct btf_type *reg_type, *ret_type = NULL; 16892 int err; 16893 16894 /* LSM and struct_ops func-ptr's return type could be "void" */ 16895 if (!frame->in_async_callback_fn && program_returns_void(env)) 16896 return 0; 16897 16898 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS) { 16899 /* Allow a struct_ops program to return a referenced kptr if it 16900 * matches the operator's return type and is in its unmodified 16901 * form. A scalar zero (i.e., a null pointer) is also allowed. 16902 */ 16903 reg_type = reg->btf ? btf_type_by_id(reg->btf, reg->btf_id) : NULL; 16904 ret_type = btf_type_resolve_ptr(prog->aux->attach_btf, 16905 prog->aux->attach_func_proto->type, 16906 NULL); 16907 if (ret_type && ret_type == reg_type && reg->ref_obj_id) 16908 return __check_ptr_off_reg(env, reg, regno, false); 16909 } 16910 16911 /* eBPF calling convention is such that R0 is used 16912 * to return the value from eBPF program. 16913 * Make sure that it's readable at this time 16914 * of bpf_exit, which means that program wrote 16915 * something into it earlier 16916 */ 16917 err = check_reg_arg(env, regno, SRC_OP); 16918 if (err) 16919 return err; 16920 16921 if (is_pointer_value(env, regno)) { 16922 verbose(env, "R%d leaks addr as return value\n", regno); 16923 return -EACCES; 16924 } 16925 16926 if (frame->in_async_callback_fn) { 16927 exit_ctx = "At async callback return"; 16928 range = frame->callback_ret_range; 16929 goto enforce_retval; 16930 } 16931 16932 if (prog_type == BPF_PROG_TYPE_STRUCT_OPS && !ret_type) 16933 return 0; 16934 16935 if (prog_type == BPF_PROG_TYPE_CGROUP_SKB && (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS)) 16936 enforce_attach_type_range = tnum_range(2, 3); 16937 16938 if (!return_retval_range(env, &range)) 16939 return 0; 16940 16941 enforce_retval: 16942 if (reg->type != SCALAR_VALUE) { 16943 verbose(env, "%s the register R%d is not a known value (%s)\n", 16944 exit_ctx, regno, reg_type_str(env, reg->type)); 16945 return -EINVAL; 16946 } 16947 16948 err = mark_chain_precision(env, regno); 16949 if (err) 16950 return err; 16951 16952 if (!retval_range_within(range, reg)) { 16953 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 16954 if (prog->expected_attach_type == BPF_LSM_CGROUP && 16955 prog_type == BPF_PROG_TYPE_LSM && 16956 !prog->aux->attach_func_proto->type) 16957 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 16958 return -EINVAL; 16959 } 16960 16961 if (!tnum_is_unknown(enforce_attach_type_range) && 16962 tnum_in(enforce_attach_type_range, reg->var_off)) 16963 env->prog->enforce_expected_attach_type = 1; 16964 return 0; 16965 } 16966 16967 static int check_global_subprog_return_code(struct bpf_verifier_env *env) 16968 { 16969 struct bpf_reg_state *reg = reg_state(env, BPF_REG_0); 16970 struct bpf_func_state *cur_frame = cur_func(env); 16971 int err; 16972 16973 if (subprog_returns_void(env, cur_frame->subprogno)) 16974 return 0; 16975 16976 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 16977 if (err) 16978 return err; 16979 16980 if (is_pointer_value(env, BPF_REG_0)) { 16981 verbose(env, "R%d leaks addr as return value\n", BPF_REG_0); 16982 return -EACCES; 16983 } 16984 16985 if (reg->type != SCALAR_VALUE) { 16986 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 16987 reg_type_str(env, reg->type)); 16988 return -EINVAL; 16989 } 16990 16991 return 0; 16992 } 16993 16994 /* Bitmask with 1s for all caller saved registers */ 16995 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1) 16996 16997 /* True if do_misc_fixups() replaces calls to helper number 'imm', 16998 * replacement patch is presumed to follow bpf_fastcall contract 16999 * (see mark_fastcall_pattern_for_call() below). 17000 */ 17001 bool bpf_verifier_inlines_helper_call(struct bpf_verifier_env *env, s32 imm) 17002 { 17003 switch (imm) { 17004 #ifdef CONFIG_X86_64 17005 case BPF_FUNC_get_smp_processor_id: 17006 #ifdef CONFIG_SMP 17007 case BPF_FUNC_get_current_task_btf: 17008 case BPF_FUNC_get_current_task: 17009 #endif 17010 return env->prog->jit_requested && bpf_jit_supports_percpu_insn(); 17011 #endif 17012 default: 17013 return false; 17014 } 17015 } 17016 17017 /* If @call is a kfunc or helper call, fills @cs and returns true, 17018 * otherwise returns false. 17019 */ 17020 bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call, 17021 struct bpf_call_summary *cs) 17022 { 17023 struct bpf_kfunc_call_arg_meta meta; 17024 const struct bpf_func_proto *fn; 17025 int i; 17026 17027 if (bpf_helper_call(call)) { 17028 17029 if (bpf_get_helper_proto(env, call->imm, &fn) < 0) 17030 /* error would be reported later */ 17031 return false; 17032 cs->fastcall = fn->allow_fastcall && 17033 (bpf_verifier_inlines_helper_call(env, call->imm) || 17034 bpf_jit_inlines_helper_call(call->imm)); 17035 cs->is_void = fn->ret_type == RET_VOID; 17036 cs->num_params = 0; 17037 for (i = 0; i < ARRAY_SIZE(fn->arg_type); ++i) { 17038 if (fn->arg_type[i] == ARG_DONTCARE) 17039 break; 17040 cs->num_params++; 17041 } 17042 return true; 17043 } 17044 17045 if (bpf_pseudo_kfunc_call(call)) { 17046 int err; 17047 17048 err = bpf_fetch_kfunc_arg_meta(env, call->imm, call->off, &meta); 17049 if (err < 0) 17050 /* error would be reported later */ 17051 return false; 17052 cs->num_params = btf_type_vlen(meta.func_proto); 17053 cs->fastcall = meta.kfunc_flags & KF_FASTCALL; 17054 cs->is_void = btf_type_is_void(btf_type_by_id(meta.btf, meta.func_proto->type)); 17055 return true; 17056 } 17057 17058 return false; 17059 } 17060 17061 /* LLVM define a bpf_fastcall function attribute. 17062 * This attribute means that function scratches only some of 17063 * the caller saved registers defined by ABI. 17064 * For BPF the set of such registers could be defined as follows: 17065 * - R0 is scratched only if function is non-void; 17066 * - R1-R5 are scratched only if corresponding parameter type is defined 17067 * in the function prototype. 17068 * 17069 * The contract between kernel and clang allows to simultaneously use 17070 * such functions and maintain backwards compatibility with old 17071 * kernels that don't understand bpf_fastcall calls: 17072 * 17073 * - for bpf_fastcall calls clang allocates registers as-if relevant r0-r5 17074 * registers are not scratched by the call; 17075 * 17076 * - as a post-processing step, clang visits each bpf_fastcall call and adds 17077 * spill/fill for every live r0-r5; 17078 * 17079 * - stack offsets used for the spill/fill are allocated as lowest 17080 * stack offsets in whole function and are not used for any other 17081 * purposes; 17082 * 17083 * - when kernel loads a program, it looks for such patterns 17084 * (bpf_fastcall function surrounded by spills/fills) and checks if 17085 * spill/fill stack offsets are used exclusively in fastcall patterns; 17086 * 17087 * - if so, and if verifier or current JIT inlines the call to the 17088 * bpf_fastcall function (e.g. a helper call), kernel removes unnecessary 17089 * spill/fill pairs; 17090 * 17091 * - when old kernel loads a program, presence of spill/fill pairs 17092 * keeps BPF program valid, albeit slightly less efficient. 17093 * 17094 * For example: 17095 * 17096 * r1 = 1; 17097 * r2 = 2; 17098 * *(u64 *)(r10 - 8) = r1; r1 = 1; 17099 * *(u64 *)(r10 - 16) = r2; r2 = 2; 17100 * call %[to_be_inlined] --> call %[to_be_inlined] 17101 * r2 = *(u64 *)(r10 - 16); r0 = r1; 17102 * r1 = *(u64 *)(r10 - 8); r0 += r2; 17103 * r0 = r1; exit; 17104 * r0 += r2; 17105 * exit; 17106 * 17107 * The purpose of mark_fastcall_pattern_for_call is to: 17108 * - look for such patterns; 17109 * - mark spill and fill instructions in env->insn_aux_data[*].fastcall_pattern; 17110 * - mark set env->insn_aux_data[*].fastcall_spills_num for call instruction; 17111 * - update env->subprog_info[*]->fastcall_stack_off to find an offset 17112 * at which bpf_fastcall spill/fill stack slots start; 17113 * - update env->subprog_info[*]->keep_fastcall_stack. 17114 * 17115 * The .fastcall_pattern and .fastcall_stack_off are used by 17116 * check_fastcall_stack_contract() to check if every stack access to 17117 * fastcall spill/fill stack slot originates from spill/fill 17118 * instructions, members of fastcall patterns. 17119 * 17120 * If such condition holds true for a subprogram, fastcall patterns could 17121 * be rewritten by remove_fastcall_spills_fills(). 17122 * Otherwise bpf_fastcall patterns are not changed in the subprogram 17123 * (code, presumably, generated by an older clang version). 17124 * 17125 * For example, it is *not* safe to remove spill/fill below: 17126 * 17127 * r1 = 1; 17128 * *(u64 *)(r10 - 8) = r1; r1 = 1; 17129 * call %[to_be_inlined] --> call %[to_be_inlined] 17130 * r1 = *(u64 *)(r10 - 8); r0 = *(u64 *)(r10 - 8); <---- wrong !!! 17131 * r0 = *(u64 *)(r10 - 8); r0 += r1; 17132 * r0 += r1; exit; 17133 * exit; 17134 */ 17135 static void mark_fastcall_pattern_for_call(struct bpf_verifier_env *env, 17136 struct bpf_subprog_info *subprog, 17137 int insn_idx, s16 lowest_off) 17138 { 17139 struct bpf_insn *insns = env->prog->insnsi, *stx, *ldx; 17140 struct bpf_insn *call = &env->prog->insnsi[insn_idx]; 17141 u32 clobbered_regs_mask; 17142 struct bpf_call_summary cs; 17143 u32 expected_regs_mask; 17144 s16 off; 17145 int i; 17146 17147 if (!bpf_get_call_summary(env, call, &cs)) 17148 return; 17149 17150 /* A bitmask specifying which caller saved registers are clobbered 17151 * by a call to a helper/kfunc *as if* this helper/kfunc follows 17152 * bpf_fastcall contract: 17153 * - includes R0 if function is non-void; 17154 * - includes R1-R5 if corresponding parameter has is described 17155 * in the function prototype. 17156 */ 17157 clobbered_regs_mask = GENMASK(cs.num_params, cs.is_void ? 1 : 0); 17158 /* e.g. if helper call clobbers r{0,1}, expect r{2,3,4,5} in the pattern */ 17159 expected_regs_mask = ~clobbered_regs_mask & ALL_CALLER_SAVED_REGS; 17160 17161 /* match pairs of form: 17162 * 17163 * *(u64 *)(r10 - Y) = rX (where Y % 8 == 0) 17164 * ... 17165 * call %[to_be_inlined] 17166 * ... 17167 * rX = *(u64 *)(r10 - Y) 17168 */ 17169 for (i = 1, off = lowest_off; i <= ARRAY_SIZE(caller_saved); ++i, off += BPF_REG_SIZE) { 17170 if (insn_idx - i < 0 || insn_idx + i >= env->prog->len) 17171 break; 17172 stx = &insns[insn_idx - i]; 17173 ldx = &insns[insn_idx + i]; 17174 /* must be a stack spill/fill pair */ 17175 if (stx->code != (BPF_STX | BPF_MEM | BPF_DW) || 17176 ldx->code != (BPF_LDX | BPF_MEM | BPF_DW) || 17177 stx->dst_reg != BPF_REG_10 || 17178 ldx->src_reg != BPF_REG_10) 17179 break; 17180 /* must be a spill/fill for the same reg */ 17181 if (stx->src_reg != ldx->dst_reg) 17182 break; 17183 /* must be one of the previously unseen registers */ 17184 if ((BIT(stx->src_reg) & expected_regs_mask) == 0) 17185 break; 17186 /* must be a spill/fill for the same expected offset, 17187 * no need to check offset alignment, BPF_DW stack access 17188 * is always 8-byte aligned. 17189 */ 17190 if (stx->off != off || ldx->off != off) 17191 break; 17192 expected_regs_mask &= ~BIT(stx->src_reg); 17193 env->insn_aux_data[insn_idx - i].fastcall_pattern = 1; 17194 env->insn_aux_data[insn_idx + i].fastcall_pattern = 1; 17195 } 17196 if (i == 1) 17197 return; 17198 17199 /* Conditionally set 'fastcall_spills_num' to allow forward 17200 * compatibility when more helper functions are marked as 17201 * bpf_fastcall at compile time than current kernel supports, e.g: 17202 * 17203 * 1: *(u64 *)(r10 - 8) = r1 17204 * 2: call A ;; assume A is bpf_fastcall for current kernel 17205 * 3: r1 = *(u64 *)(r10 - 8) 17206 * 4: *(u64 *)(r10 - 8) = r1 17207 * 5: call B ;; assume B is not bpf_fastcall for current kernel 17208 * 6: r1 = *(u64 *)(r10 - 8) 17209 * 17210 * There is no need to block bpf_fastcall rewrite for such program. 17211 * Set 'fastcall_pattern' for both calls to keep check_fastcall_stack_contract() happy, 17212 * don't set 'fastcall_spills_num' for call B so that remove_fastcall_spills_fills() 17213 * does not remove spill/fill pair {4,6}. 17214 */ 17215 if (cs.fastcall) 17216 env->insn_aux_data[insn_idx].fastcall_spills_num = i - 1; 17217 else 17218 subprog->keep_fastcall_stack = 1; 17219 subprog->fastcall_stack_off = min(subprog->fastcall_stack_off, off); 17220 } 17221 17222 static int mark_fastcall_patterns(struct bpf_verifier_env *env) 17223 { 17224 struct bpf_subprog_info *subprog = env->subprog_info; 17225 struct bpf_insn *insn; 17226 s16 lowest_off; 17227 int s, i; 17228 17229 for (s = 0; s < env->subprog_cnt; ++s, ++subprog) { 17230 /* find lowest stack spill offset used in this subprog */ 17231 lowest_off = 0; 17232 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 17233 insn = env->prog->insnsi + i; 17234 if (insn->code != (BPF_STX | BPF_MEM | BPF_DW) || 17235 insn->dst_reg != BPF_REG_10) 17236 continue; 17237 lowest_off = min(lowest_off, insn->off); 17238 } 17239 /* use this offset to find fastcall patterns */ 17240 for (i = subprog->start; i < (subprog + 1)->start; ++i) { 17241 insn = env->prog->insnsi + i; 17242 if (insn->code != (BPF_JMP | BPF_CALL)) 17243 continue; 17244 mark_fastcall_pattern_for_call(env, subprog, i, lowest_off); 17245 } 17246 } 17247 return 0; 17248 } 17249 17250 static void adjust_btf_func(struct bpf_verifier_env *env) 17251 { 17252 struct bpf_prog_aux *aux = env->prog->aux; 17253 int i; 17254 17255 if (!aux->func_info) 17256 return; 17257 17258 /* func_info is not available for hidden subprogs */ 17259 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 17260 aux->func_info[i].insn_off = env->subprog_info[i].start; 17261 } 17262 17263 /* Find id in idset and increment its count, or add new entry */ 17264 static void idset_cnt_inc(struct bpf_idset *idset, u32 id) 17265 { 17266 u32 i; 17267 17268 for (i = 0; i < idset->num_ids; i++) { 17269 if (idset->entries[i].id == id) { 17270 idset->entries[i].cnt++; 17271 return; 17272 } 17273 } 17274 /* New id */ 17275 if (idset->num_ids < BPF_ID_MAP_SIZE) { 17276 idset->entries[idset->num_ids].id = id; 17277 idset->entries[idset->num_ids].cnt = 1; 17278 idset->num_ids++; 17279 } 17280 } 17281 17282 /* Find id in idset and return its count, or 0 if not found */ 17283 static u32 idset_cnt_get(struct bpf_idset *idset, u32 id) 17284 { 17285 u32 i; 17286 17287 for (i = 0; i < idset->num_ids; i++) { 17288 if (idset->entries[i].id == id) 17289 return idset->entries[i].cnt; 17290 } 17291 return 0; 17292 } 17293 17294 /* 17295 * Clear singular scalar ids in a state. 17296 * A register with a non-zero id is called singular if no other register shares 17297 * the same base id. Such registers can be treated as independent (id=0). 17298 */ 17299 void bpf_clear_singular_ids(struct bpf_verifier_env *env, 17300 struct bpf_verifier_state *st) 17301 { 17302 struct bpf_idset *idset = &env->idset_scratch; 17303 struct bpf_func_state *func; 17304 struct bpf_reg_state *reg; 17305 17306 idset->num_ids = 0; 17307 17308 bpf_for_each_reg_in_vstate(st, func, reg, ({ 17309 if (reg->type != SCALAR_VALUE) 17310 continue; 17311 if (!reg->id) 17312 continue; 17313 idset_cnt_inc(idset, reg->id & ~BPF_ADD_CONST); 17314 })); 17315 17316 bpf_for_each_reg_in_vstate(st, func, reg, ({ 17317 if (reg->type != SCALAR_VALUE) 17318 continue; 17319 if (!reg->id) 17320 continue; 17321 if (idset_cnt_get(idset, reg->id & ~BPF_ADD_CONST) == 1) 17322 clear_scalar_id(reg); 17323 })); 17324 } 17325 17326 /* Return true if it's OK to have the same insn return a different type. */ 17327 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17328 { 17329 switch (base_type(type)) { 17330 case PTR_TO_CTX: 17331 case PTR_TO_SOCKET: 17332 case PTR_TO_SOCK_COMMON: 17333 case PTR_TO_TCP_SOCK: 17334 case PTR_TO_XDP_SOCK: 17335 case PTR_TO_BTF_ID: 17336 case PTR_TO_ARENA: 17337 return false; 17338 default: 17339 return true; 17340 } 17341 } 17342 17343 /* If an instruction was previously used with particular pointer types, then we 17344 * need to be careful to avoid cases such as the below, where it may be ok 17345 * for one branch accessing the pointer, but not ok for the other branch: 17346 * 17347 * R1 = sock_ptr 17348 * goto X; 17349 * ... 17350 * R1 = some_other_valid_ptr; 17351 * goto X; 17352 * ... 17353 * R2 = *(u32 *)(R1 + 0); 17354 */ 17355 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17356 { 17357 return src != prev && (!reg_type_mismatch_ok(src) || 17358 !reg_type_mismatch_ok(prev)); 17359 } 17360 17361 static bool is_ptr_to_mem_or_btf_id(enum bpf_reg_type type) 17362 { 17363 switch (base_type(type)) { 17364 case PTR_TO_MEM: 17365 case PTR_TO_BTF_ID: 17366 return true; 17367 default: 17368 return false; 17369 } 17370 } 17371 17372 static bool is_ptr_to_mem(enum bpf_reg_type type) 17373 { 17374 return base_type(type) == PTR_TO_MEM; 17375 } 17376 17377 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17378 bool allow_trust_mismatch) 17379 { 17380 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17381 enum bpf_reg_type merged_type; 17382 17383 if (*prev_type == NOT_INIT) { 17384 /* Saw a valid insn 17385 * dst_reg = *(u32 *)(src_reg + off) 17386 * save type to validate intersecting paths 17387 */ 17388 *prev_type = type; 17389 } else if (reg_type_mismatch(type, *prev_type)) { 17390 /* Abuser program is trying to use the same insn 17391 * dst_reg = *(u32*) (src_reg + off) 17392 * with different pointer types: 17393 * src_reg == ctx in one branch and 17394 * src_reg == stack|map in some other branch. 17395 * Reject it. 17396 */ 17397 if (allow_trust_mismatch && 17398 is_ptr_to_mem_or_btf_id(type) && 17399 is_ptr_to_mem_or_btf_id(*prev_type)) { 17400 /* 17401 * Have to support a use case when one path through 17402 * the program yields TRUSTED pointer while another 17403 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17404 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17405 * Same behavior of MEM_RDONLY flag. 17406 */ 17407 if (is_ptr_to_mem(type) || is_ptr_to_mem(*prev_type)) 17408 merged_type = PTR_TO_MEM; 17409 else 17410 merged_type = PTR_TO_BTF_ID; 17411 if ((type & PTR_UNTRUSTED) || (*prev_type & PTR_UNTRUSTED)) 17412 merged_type |= PTR_UNTRUSTED; 17413 if ((type & MEM_RDONLY) || (*prev_type & MEM_RDONLY)) 17414 merged_type |= MEM_RDONLY; 17415 *prev_type = merged_type; 17416 } else { 17417 verbose(env, "same insn cannot be used with different pointers\n"); 17418 return -EINVAL; 17419 } 17420 } 17421 17422 return 0; 17423 } 17424 17425 enum { 17426 PROCESS_BPF_EXIT = 1, 17427 INSN_IDX_UPDATED = 2, 17428 }; 17429 17430 static int process_bpf_exit_full(struct bpf_verifier_env *env, 17431 bool *do_print_state, 17432 bool exception_exit) 17433 { 17434 struct bpf_func_state *cur_frame = cur_func(env); 17435 17436 /* We must do check_reference_leak here before 17437 * prepare_func_exit to handle the case when 17438 * state->curframe > 0, it may be a callback function, 17439 * for which reference_state must match caller reference 17440 * state when it exits. 17441 */ 17442 int err = check_resource_leak(env, exception_exit, 17443 exception_exit || !env->cur_state->curframe, 17444 exception_exit ? "bpf_throw" : 17445 "BPF_EXIT instruction in main prog"); 17446 if (err) 17447 return err; 17448 17449 /* The side effect of the prepare_func_exit which is 17450 * being skipped is that it frees bpf_func_state. 17451 * Typically, process_bpf_exit will only be hit with 17452 * outermost exit. copy_verifier_state in pop_stack will 17453 * handle freeing of any extra bpf_func_state left over 17454 * from not processing all nested function exits. We 17455 * also skip return code checks as they are not needed 17456 * for exceptional exits. 17457 */ 17458 if (exception_exit) 17459 return PROCESS_BPF_EXIT; 17460 17461 if (env->cur_state->curframe) { 17462 /* exit from nested function */ 17463 err = prepare_func_exit(env, &env->insn_idx); 17464 if (err) 17465 return err; 17466 *do_print_state = true; 17467 return INSN_IDX_UPDATED; 17468 } 17469 17470 /* 17471 * Return from a regular global subprogram differs from return 17472 * from the main program or async/exception callback. 17473 * Main program exit implies return code restrictions 17474 * that depend on program type. 17475 * Exit from exception callback is equivalent to main program exit. 17476 * Exit from async callback implies return code restrictions 17477 * that depend on async scheduling mechanism. 17478 */ 17479 if (cur_frame->subprogno && 17480 !cur_frame->in_async_callback_fn && 17481 !cur_frame->in_exception_callback_fn) 17482 err = check_global_subprog_return_code(env); 17483 else 17484 err = check_return_code(env, BPF_REG_0, "R0"); 17485 if (err) 17486 return err; 17487 return PROCESS_BPF_EXIT; 17488 } 17489 17490 static int indirect_jump_min_max_index(struct bpf_verifier_env *env, 17491 int regno, 17492 struct bpf_map *map, 17493 u32 *pmin_index, u32 *pmax_index) 17494 { 17495 struct bpf_reg_state *reg = reg_state(env, regno); 17496 u64 min_index = reg->umin_value; 17497 u64 max_index = reg->umax_value; 17498 const u32 size = 8; 17499 17500 if (min_index > (u64) U32_MAX * size) { 17501 verbose(env, "the sum of R%u umin_value %llu is too big\n", regno, reg->umin_value); 17502 return -ERANGE; 17503 } 17504 if (max_index > (u64) U32_MAX * size) { 17505 verbose(env, "the sum of R%u umax_value %llu is too big\n", regno, reg->umax_value); 17506 return -ERANGE; 17507 } 17508 17509 min_index /= size; 17510 max_index /= size; 17511 17512 if (max_index >= map->max_entries) { 17513 verbose(env, "R%u points to outside of jump table: [%llu,%llu] max_entries %u\n", 17514 regno, min_index, max_index, map->max_entries); 17515 return -EINVAL; 17516 } 17517 17518 *pmin_index = min_index; 17519 *pmax_index = max_index; 17520 return 0; 17521 } 17522 17523 /* gotox *dst_reg */ 17524 static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *insn) 17525 { 17526 struct bpf_verifier_state *other_branch; 17527 struct bpf_reg_state *dst_reg; 17528 struct bpf_map *map; 17529 u32 min_index, max_index; 17530 int err = 0; 17531 int n; 17532 int i; 17533 17534 dst_reg = reg_state(env, insn->dst_reg); 17535 if (dst_reg->type != PTR_TO_INSN) { 17536 verbose(env, "R%d has type %s, expected PTR_TO_INSN\n", 17537 insn->dst_reg, reg_type_str(env, dst_reg->type)); 17538 return -EINVAL; 17539 } 17540 17541 map = dst_reg->map_ptr; 17542 if (verifier_bug_if(!map, env, "R%d has an empty map pointer", insn->dst_reg)) 17543 return -EFAULT; 17544 17545 if (verifier_bug_if(map->map_type != BPF_MAP_TYPE_INSN_ARRAY, env, 17546 "R%d has incorrect map type %d", insn->dst_reg, map->map_type)) 17547 return -EFAULT; 17548 17549 err = indirect_jump_min_max_index(env, insn->dst_reg, map, &min_index, &max_index); 17550 if (err) 17551 return err; 17552 17553 /* Ensure that the buffer is large enough */ 17554 if (!env->gotox_tmp_buf || env->gotox_tmp_buf->cnt < max_index - min_index + 1) { 17555 env->gotox_tmp_buf = bpf_iarray_realloc(env->gotox_tmp_buf, 17556 max_index - min_index + 1); 17557 if (!env->gotox_tmp_buf) 17558 return -ENOMEM; 17559 } 17560 17561 n = bpf_copy_insn_array_uniq(map, min_index, max_index, env->gotox_tmp_buf->items); 17562 if (n < 0) 17563 return n; 17564 if (n == 0) { 17565 verbose(env, "register R%d doesn't point to any offset in map id=%d\n", 17566 insn->dst_reg, map->id); 17567 return -EINVAL; 17568 } 17569 17570 for (i = 0; i < n - 1; i++) { 17571 mark_indirect_target(env, env->gotox_tmp_buf->items[i]); 17572 other_branch = push_stack(env, env->gotox_tmp_buf->items[i], 17573 env->insn_idx, env->cur_state->speculative); 17574 if (IS_ERR(other_branch)) 17575 return PTR_ERR(other_branch); 17576 } 17577 env->insn_idx = env->gotox_tmp_buf->items[n-1]; 17578 mark_indirect_target(env, env->insn_idx); 17579 return INSN_IDX_UPDATED; 17580 } 17581 17582 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state) 17583 { 17584 int err; 17585 struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx]; 17586 u8 class = BPF_CLASS(insn->code); 17587 17588 switch (class) { 17589 case BPF_ALU: 17590 case BPF_ALU64: 17591 return check_alu_op(env, insn); 17592 17593 case BPF_LDX: 17594 return check_load_mem(env, insn, false, 17595 BPF_MODE(insn->code) == BPF_MEMSX, 17596 true, "ldx"); 17597 17598 case BPF_STX: 17599 if (BPF_MODE(insn->code) == BPF_ATOMIC) 17600 return check_atomic(env, insn); 17601 return check_store_reg(env, insn, false); 17602 17603 case BPF_ST: { 17604 enum bpf_reg_type dst_reg_type; 17605 17606 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17607 if (err) 17608 return err; 17609 17610 dst_reg_type = cur_regs(env)[insn->dst_reg].type; 17611 17612 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17613 insn->off, BPF_SIZE(insn->code), 17614 BPF_WRITE, -1, false, false); 17615 if (err) 17616 return err; 17617 17618 return save_aux_ptr_type(env, dst_reg_type, false); 17619 } 17620 case BPF_JMP: 17621 case BPF_JMP32: { 17622 u8 opcode = BPF_OP(insn->code); 17623 17624 env->jmps_processed++; 17625 if (opcode == BPF_CALL) { 17626 if (env->cur_state->active_locks) { 17627 if ((insn->src_reg == BPF_REG_0 && 17628 insn->imm != BPF_FUNC_spin_unlock && 17629 insn->imm != BPF_FUNC_kptr_xchg) || 17630 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17631 (insn->off != 0 || !kfunc_spin_allowed(insn->imm)))) { 17632 verbose(env, 17633 "function calls are not allowed while holding a lock\n"); 17634 return -EINVAL; 17635 } 17636 } 17637 mark_reg_scratched(env, BPF_REG_0); 17638 if (insn->src_reg == BPF_PSEUDO_CALL) 17639 return check_func_call(env, insn, &env->insn_idx); 17640 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 17641 return check_kfunc_call(env, insn, &env->insn_idx); 17642 return check_helper_call(env, insn, &env->insn_idx); 17643 } else if (opcode == BPF_JA) { 17644 if (BPF_SRC(insn->code) == BPF_X) 17645 return check_indirect_jump(env, insn); 17646 17647 if (class == BPF_JMP) 17648 env->insn_idx += insn->off + 1; 17649 else 17650 env->insn_idx += insn->imm + 1; 17651 return INSN_IDX_UPDATED; 17652 } else if (opcode == BPF_EXIT) { 17653 return process_bpf_exit_full(env, do_print_state, false); 17654 } 17655 return check_cond_jmp_op(env, insn, &env->insn_idx); 17656 } 17657 case BPF_LD: { 17658 u8 mode = BPF_MODE(insn->code); 17659 17660 if (mode == BPF_ABS || mode == BPF_IND) 17661 return check_ld_abs(env, insn); 17662 17663 if (mode == BPF_IMM) { 17664 err = check_ld_imm(env, insn); 17665 if (err) 17666 return err; 17667 17668 env->insn_idx++; 17669 sanitize_mark_insn_seen(env); 17670 } 17671 return 0; 17672 } 17673 } 17674 /* all class values are handled above. silence compiler warning */ 17675 return -EFAULT; 17676 } 17677 17678 static int do_check(struct bpf_verifier_env *env) 17679 { 17680 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17681 struct bpf_verifier_state *state = env->cur_state; 17682 struct bpf_insn *insns = env->prog->insnsi; 17683 int insn_cnt = env->prog->len; 17684 bool do_print_state = false; 17685 int prev_insn_idx = -1; 17686 17687 for (;;) { 17688 struct bpf_insn *insn; 17689 struct bpf_insn_aux_data *insn_aux; 17690 int err; 17691 17692 /* reset current history entry on each new instruction */ 17693 env->cur_hist_ent = NULL; 17694 17695 env->prev_insn_idx = prev_insn_idx; 17696 if (env->insn_idx >= insn_cnt) { 17697 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17698 env->insn_idx, insn_cnt); 17699 return -EFAULT; 17700 } 17701 17702 insn = &insns[env->insn_idx]; 17703 insn_aux = &env->insn_aux_data[env->insn_idx]; 17704 17705 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17706 verbose(env, 17707 "BPF program is too large. Processed %d insn\n", 17708 env->insn_processed); 17709 return -E2BIG; 17710 } 17711 17712 state->last_insn_idx = env->prev_insn_idx; 17713 state->insn_idx = env->insn_idx; 17714 17715 if (bpf_is_prune_point(env, env->insn_idx)) { 17716 err = bpf_is_state_visited(env, env->insn_idx); 17717 if (err < 0) 17718 return err; 17719 if (err == 1) { 17720 /* found equivalent state, can prune the search */ 17721 if (env->log.level & BPF_LOG_LEVEL) { 17722 if (do_print_state) 17723 verbose(env, "\nfrom %d to %d%s: safe\n", 17724 env->prev_insn_idx, env->insn_idx, 17725 env->cur_state->speculative ? 17726 " (speculative execution)" : ""); 17727 else 17728 verbose(env, "%d: safe\n", env->insn_idx); 17729 } 17730 goto process_bpf_exit; 17731 } 17732 } 17733 17734 if (bpf_is_jmp_point(env, env->insn_idx)) { 17735 err = bpf_push_jmp_history(env, state, 0, 0); 17736 if (err) 17737 return err; 17738 } 17739 17740 if (signal_pending(current)) 17741 return -EAGAIN; 17742 17743 if (need_resched()) 17744 cond_resched(); 17745 17746 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17747 verbose(env, "\nfrom %d to %d%s:", 17748 env->prev_insn_idx, env->insn_idx, 17749 env->cur_state->speculative ? 17750 " (speculative execution)" : ""); 17751 print_verifier_state(env, state, state->curframe, true); 17752 do_print_state = false; 17753 } 17754 17755 if (env->log.level & BPF_LOG_LEVEL) { 17756 if (verifier_state_scratched(env)) 17757 print_insn_state(env, state, state->curframe); 17758 17759 verbose_linfo(env, env->insn_idx, "; "); 17760 env->prev_log_pos = env->log.end_pos; 17761 verbose(env, "%d: ", env->insn_idx); 17762 bpf_verbose_insn(env, insn); 17763 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17764 env->prev_log_pos = env->log.end_pos; 17765 } 17766 17767 if (bpf_prog_is_offloaded(env->prog->aux)) { 17768 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17769 env->prev_insn_idx); 17770 if (err) 17771 return err; 17772 } 17773 17774 sanitize_mark_insn_seen(env); 17775 prev_insn_idx = env->insn_idx; 17776 17777 /* Sanity check: precomputed constants must match verifier state */ 17778 if (!state->speculative && insn_aux->const_reg_mask) { 17779 struct bpf_reg_state *regs = cur_regs(env); 17780 u16 mask = insn_aux->const_reg_mask; 17781 17782 for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) { 17783 u32 cval = insn_aux->const_reg_vals[r]; 17784 17785 if (!(mask & BIT(r))) 17786 continue; 17787 if (regs[r].type != SCALAR_VALUE) 17788 continue; 17789 if (!tnum_is_const(regs[r].var_off)) 17790 continue; 17791 if (verifier_bug_if((u32)regs[r].var_off.value != cval, 17792 env, "const R%d: %u != %llu", 17793 r, cval, regs[r].var_off.value)) 17794 return -EFAULT; 17795 } 17796 } 17797 17798 /* Reduce verification complexity by stopping speculative path 17799 * verification when a nospec is encountered. 17800 */ 17801 if (state->speculative && insn_aux->nospec) 17802 goto process_bpf_exit; 17803 17804 err = do_check_insn(env, &do_print_state); 17805 if (error_recoverable_with_nospec(err) && state->speculative) { 17806 /* Prevent this speculative path from ever reaching the 17807 * insn that would have been unsafe to execute. 17808 */ 17809 insn_aux->nospec = true; 17810 /* If it was an ADD/SUB insn, potentially remove any 17811 * markings for alu sanitization. 17812 */ 17813 insn_aux->alu_state = 0; 17814 goto process_bpf_exit; 17815 } else if (err < 0) { 17816 return err; 17817 } else if (err == PROCESS_BPF_EXIT) { 17818 goto process_bpf_exit; 17819 } else if (err == INSN_IDX_UPDATED) { 17820 } else if (err == 0) { 17821 env->insn_idx++; 17822 } 17823 17824 if (state->speculative && insn_aux->nospec_result) { 17825 /* If we are on a path that performed a jump-op, this 17826 * may skip a nospec patched-in after the jump. This can 17827 * currently never happen because nospec_result is only 17828 * used for the write-ops 17829 * `*(size*)(dst_reg+off)=src_reg|imm32` and helper 17830 * calls. These must never skip the following insn 17831 * (i.e., bpf_insn_successors()'s opcode_info.can_jump 17832 * is false). Still, add a warning to document this in 17833 * case nospec_result is used elsewhere in the future. 17834 * 17835 * All non-branch instructions have a single 17836 * fall-through edge. For these, nospec_result should 17837 * already work. 17838 */ 17839 if (verifier_bug_if((BPF_CLASS(insn->code) == BPF_JMP || 17840 BPF_CLASS(insn->code) == BPF_JMP32) && 17841 BPF_OP(insn->code) != BPF_CALL, env, 17842 "speculation barrier after jump instruction may not have the desired effect")) 17843 return -EFAULT; 17844 process_bpf_exit: 17845 mark_verifier_state_scratched(env); 17846 err = bpf_update_branch_counts(env, env->cur_state); 17847 if (err) 17848 return err; 17849 err = pop_stack(env, &prev_insn_idx, &env->insn_idx, 17850 pop_log); 17851 if (err < 0) { 17852 if (err != -ENOENT) 17853 return err; 17854 break; 17855 } else { 17856 do_print_state = true; 17857 continue; 17858 } 17859 } 17860 } 17861 17862 return 0; 17863 } 17864 17865 static int find_btf_percpu_datasec(struct btf *btf) 17866 { 17867 const struct btf_type *t; 17868 const char *tname; 17869 int i, n; 17870 17871 /* 17872 * Both vmlinux and module each have their own ".data..percpu" 17873 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17874 * types to look at only module's own BTF types. 17875 */ 17876 n = btf_nr_types(btf); 17877 for (i = btf_named_start_id(btf, true); i < n; i++) { 17878 t = btf_type_by_id(btf, i); 17879 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17880 continue; 17881 17882 tname = btf_name_by_offset(btf, t->name_off); 17883 if (!strcmp(tname, ".data..percpu")) 17884 return i; 17885 } 17886 17887 return -ENOENT; 17888 } 17889 17890 /* 17891 * Add btf to the env->used_btfs array. If needed, refcount the 17892 * corresponding kernel module. To simplify caller's logic 17893 * in case of error or if btf was added before the function 17894 * decreases the btf refcount. 17895 */ 17896 static int __add_used_btf(struct bpf_verifier_env *env, struct btf *btf) 17897 { 17898 struct btf_mod_pair *btf_mod; 17899 int ret = 0; 17900 int i; 17901 17902 /* check whether we recorded this BTF (and maybe module) already */ 17903 for (i = 0; i < env->used_btf_cnt; i++) 17904 if (env->used_btfs[i].btf == btf) 17905 goto ret_put; 17906 17907 if (env->used_btf_cnt >= MAX_USED_BTFS) { 17908 verbose(env, "The total number of btfs per program has reached the limit of %u\n", 17909 MAX_USED_BTFS); 17910 ret = -E2BIG; 17911 goto ret_put; 17912 } 17913 17914 btf_mod = &env->used_btfs[env->used_btf_cnt]; 17915 btf_mod->btf = btf; 17916 btf_mod->module = NULL; 17917 17918 /* if we reference variables from kernel module, bump its refcount */ 17919 if (btf_is_module(btf)) { 17920 btf_mod->module = btf_try_get_module(btf); 17921 if (!btf_mod->module) { 17922 ret = -ENXIO; 17923 goto ret_put; 17924 } 17925 } 17926 17927 env->used_btf_cnt++; 17928 return 0; 17929 17930 ret_put: 17931 /* Either error or this BTF was already added */ 17932 btf_put(btf); 17933 return ret; 17934 } 17935 17936 /* replace pseudo btf_id with kernel symbol address */ 17937 static int __check_pseudo_btf_id(struct bpf_verifier_env *env, 17938 struct bpf_insn *insn, 17939 struct bpf_insn_aux_data *aux, 17940 struct btf *btf) 17941 { 17942 const struct btf_var_secinfo *vsi; 17943 const struct btf_type *datasec; 17944 const struct btf_type *t; 17945 const char *sym_name; 17946 bool percpu = false; 17947 u32 type, id = insn->imm; 17948 s32 datasec_id; 17949 u64 addr; 17950 int i; 17951 17952 t = btf_type_by_id(btf, id); 17953 if (!t) { 17954 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17955 return -ENOENT; 17956 } 17957 17958 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 17959 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 17960 return -EINVAL; 17961 } 17962 17963 sym_name = btf_name_by_offset(btf, t->name_off); 17964 addr = kallsyms_lookup_name(sym_name); 17965 if (!addr) { 17966 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 17967 sym_name); 17968 return -ENOENT; 17969 } 17970 insn[0].imm = (u32)addr; 17971 insn[1].imm = addr >> 32; 17972 17973 if (btf_type_is_func(t)) { 17974 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 17975 aux->btf_var.mem_size = 0; 17976 return 0; 17977 } 17978 17979 datasec_id = find_btf_percpu_datasec(btf); 17980 if (datasec_id > 0) { 17981 datasec = btf_type_by_id(btf, datasec_id); 17982 for_each_vsi(i, datasec, vsi) { 17983 if (vsi->type == id) { 17984 percpu = true; 17985 break; 17986 } 17987 } 17988 } 17989 17990 type = t->type; 17991 t = btf_type_skip_modifiers(btf, type, NULL); 17992 if (percpu) { 17993 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 17994 aux->btf_var.btf = btf; 17995 aux->btf_var.btf_id = type; 17996 } else if (!btf_type_is_struct(t)) { 17997 const struct btf_type *ret; 17998 const char *tname; 17999 u32 tsize; 18000 18001 /* resolve the type size of ksym. */ 18002 ret = btf_resolve_size(btf, t, &tsize); 18003 if (IS_ERR(ret)) { 18004 tname = btf_name_by_offset(btf, t->name_off); 18005 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 18006 tname, PTR_ERR(ret)); 18007 return -EINVAL; 18008 } 18009 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18010 aux->btf_var.mem_size = tsize; 18011 } else { 18012 aux->btf_var.reg_type = PTR_TO_BTF_ID; 18013 aux->btf_var.btf = btf; 18014 aux->btf_var.btf_id = type; 18015 } 18016 18017 return 0; 18018 } 18019 18020 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 18021 struct bpf_insn *insn, 18022 struct bpf_insn_aux_data *aux) 18023 { 18024 struct btf *btf; 18025 int btf_fd; 18026 int err; 18027 18028 btf_fd = insn[1].imm; 18029 if (btf_fd) { 18030 btf = btf_get_by_fd(btf_fd); 18031 if (IS_ERR(btf)) { 18032 verbose(env, "invalid module BTF object FD specified.\n"); 18033 return -EINVAL; 18034 } 18035 } else { 18036 if (!btf_vmlinux) { 18037 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 18038 return -EINVAL; 18039 } 18040 btf_get(btf_vmlinux); 18041 btf = btf_vmlinux; 18042 } 18043 18044 err = __check_pseudo_btf_id(env, insn, aux, btf); 18045 if (err) { 18046 btf_put(btf); 18047 return err; 18048 } 18049 18050 return __add_used_btf(env, btf); 18051 } 18052 18053 static bool is_tracing_prog_type(enum bpf_prog_type type) 18054 { 18055 switch (type) { 18056 case BPF_PROG_TYPE_KPROBE: 18057 case BPF_PROG_TYPE_TRACEPOINT: 18058 case BPF_PROG_TYPE_PERF_EVENT: 18059 case BPF_PROG_TYPE_RAW_TRACEPOINT: 18060 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 18061 return true; 18062 default: 18063 return false; 18064 } 18065 } 18066 18067 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 18068 { 18069 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 18070 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 18071 } 18072 18073 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 18074 struct bpf_map *map, 18075 struct bpf_prog *prog) 18076 18077 { 18078 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18079 18080 if (map->excl_prog_sha && 18081 memcmp(map->excl_prog_sha, prog->digest, SHA256_DIGEST_SIZE)) { 18082 verbose(env, "program's hash doesn't match map's excl_prog_hash\n"); 18083 return -EACCES; 18084 } 18085 18086 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 18087 btf_record_has_field(map->record, BPF_RB_ROOT)) { 18088 if (is_tracing_prog_type(prog_type)) { 18089 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 18090 return -EINVAL; 18091 } 18092 } 18093 18094 if (btf_record_has_field(map->record, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK)) { 18095 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 18096 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 18097 return -EINVAL; 18098 } 18099 18100 if (is_tracing_prog_type(prog_type)) { 18101 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 18102 return -EINVAL; 18103 } 18104 } 18105 18106 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 18107 !bpf_offload_prog_map_match(prog, map)) { 18108 verbose(env, "offload device mismatch between prog and map\n"); 18109 return -EINVAL; 18110 } 18111 18112 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 18113 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 18114 return -EINVAL; 18115 } 18116 18117 if (prog->sleepable) 18118 switch (map->map_type) { 18119 case BPF_MAP_TYPE_HASH: 18120 case BPF_MAP_TYPE_LRU_HASH: 18121 case BPF_MAP_TYPE_ARRAY: 18122 case BPF_MAP_TYPE_PERCPU_HASH: 18123 case BPF_MAP_TYPE_PERCPU_ARRAY: 18124 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 18125 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 18126 case BPF_MAP_TYPE_HASH_OF_MAPS: 18127 case BPF_MAP_TYPE_RINGBUF: 18128 case BPF_MAP_TYPE_USER_RINGBUF: 18129 case BPF_MAP_TYPE_INODE_STORAGE: 18130 case BPF_MAP_TYPE_SK_STORAGE: 18131 case BPF_MAP_TYPE_TASK_STORAGE: 18132 case BPF_MAP_TYPE_CGRP_STORAGE: 18133 case BPF_MAP_TYPE_QUEUE: 18134 case BPF_MAP_TYPE_STACK: 18135 case BPF_MAP_TYPE_ARENA: 18136 case BPF_MAP_TYPE_INSN_ARRAY: 18137 case BPF_MAP_TYPE_PROG_ARRAY: 18138 break; 18139 default: 18140 verbose(env, 18141 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 18142 return -EINVAL; 18143 } 18144 18145 if (bpf_map_is_cgroup_storage(map) && 18146 bpf_cgroup_storage_assign(env->prog->aux, map)) { 18147 verbose(env, "only one cgroup storage of each type is allowed\n"); 18148 return -EBUSY; 18149 } 18150 18151 if (map->map_type == BPF_MAP_TYPE_ARENA) { 18152 if (env->prog->aux->arena) { 18153 verbose(env, "Only one arena per program\n"); 18154 return -EBUSY; 18155 } 18156 if (!env->allow_ptr_leaks || !env->bpf_capable) { 18157 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 18158 return -EPERM; 18159 } 18160 if (!env->prog->jit_requested) { 18161 verbose(env, "JIT is required to use arena\n"); 18162 return -EOPNOTSUPP; 18163 } 18164 if (!bpf_jit_supports_arena()) { 18165 verbose(env, "JIT doesn't support arena\n"); 18166 return -EOPNOTSUPP; 18167 } 18168 env->prog->aux->arena = (void *)map; 18169 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 18170 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 18171 return -EINVAL; 18172 } 18173 } 18174 18175 return 0; 18176 } 18177 18178 static int __add_used_map(struct bpf_verifier_env *env, struct bpf_map *map) 18179 { 18180 int i, err; 18181 18182 /* check whether we recorded this map already */ 18183 for (i = 0; i < env->used_map_cnt; i++) 18184 if (env->used_maps[i] == map) 18185 return i; 18186 18187 if (env->used_map_cnt >= MAX_USED_MAPS) { 18188 verbose(env, "The total number of maps per program has reached the limit of %u\n", 18189 MAX_USED_MAPS); 18190 return -E2BIG; 18191 } 18192 18193 err = check_map_prog_compatibility(env, map, env->prog); 18194 if (err) 18195 return err; 18196 18197 if (env->prog->sleepable) 18198 atomic64_inc(&map->sleepable_refcnt); 18199 18200 /* hold the map. If the program is rejected by verifier, 18201 * the map will be released by release_maps() or it 18202 * will be used by the valid program until it's unloaded 18203 * and all maps are released in bpf_free_used_maps() 18204 */ 18205 bpf_map_inc(map); 18206 18207 env->used_maps[env->used_map_cnt++] = map; 18208 18209 if (map->map_type == BPF_MAP_TYPE_INSN_ARRAY) { 18210 err = bpf_insn_array_init(map, env->prog); 18211 if (err) { 18212 verbose(env, "Failed to properly initialize insn array\n"); 18213 return err; 18214 } 18215 env->insn_array_maps[env->insn_array_map_cnt++] = map; 18216 } 18217 18218 return env->used_map_cnt - 1; 18219 } 18220 18221 /* Add map behind fd to used maps list, if it's not already there, and return 18222 * its index. 18223 * Returns <0 on error, or >= 0 index, on success. 18224 */ 18225 static int add_used_map(struct bpf_verifier_env *env, int fd) 18226 { 18227 struct bpf_map *map; 18228 CLASS(fd, f)(fd); 18229 18230 map = __bpf_map_get(f); 18231 if (IS_ERR(map)) { 18232 verbose(env, "fd %d is not pointing to valid bpf_map\n", fd); 18233 return PTR_ERR(map); 18234 } 18235 18236 return __add_used_map(env, map); 18237 } 18238 18239 static int check_alu_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 18240 { 18241 u8 class = BPF_CLASS(insn->code); 18242 u8 opcode = BPF_OP(insn->code); 18243 18244 switch (opcode) { 18245 case BPF_NEG: 18246 if (BPF_SRC(insn->code) != BPF_K || insn->src_reg != BPF_REG_0 || 18247 insn->off != 0 || insn->imm != 0) { 18248 verbose(env, "BPF_NEG uses reserved fields\n"); 18249 return -EINVAL; 18250 } 18251 return 0; 18252 case BPF_END: 18253 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 18254 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 18255 (class == BPF_ALU64 && BPF_SRC(insn->code) != BPF_TO_LE)) { 18256 verbose(env, "BPF_END uses reserved fields\n"); 18257 return -EINVAL; 18258 } 18259 return 0; 18260 case BPF_MOV: 18261 if (BPF_SRC(insn->code) == BPF_X) { 18262 if (class == BPF_ALU) { 18263 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 18264 insn->imm) { 18265 verbose(env, "BPF_MOV uses reserved fields\n"); 18266 return -EINVAL; 18267 } 18268 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 18269 if (insn->imm != 1 && insn->imm != 1u << 16) { 18270 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 18271 return -EINVAL; 18272 } 18273 } else if ((insn->off != 0 && insn->off != 8 && 18274 insn->off != 16 && insn->off != 32) || insn->imm) { 18275 verbose(env, "BPF_MOV uses reserved fields\n"); 18276 return -EINVAL; 18277 } 18278 } else if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 18279 verbose(env, "BPF_MOV uses reserved fields\n"); 18280 return -EINVAL; 18281 } 18282 return 0; 18283 case BPF_ADD: 18284 case BPF_SUB: 18285 case BPF_AND: 18286 case BPF_OR: 18287 case BPF_XOR: 18288 case BPF_LSH: 18289 case BPF_RSH: 18290 case BPF_ARSH: 18291 case BPF_MUL: 18292 case BPF_DIV: 18293 case BPF_MOD: 18294 if (BPF_SRC(insn->code) == BPF_X) { 18295 if (insn->imm != 0 || (insn->off != 0 && insn->off != 1) || 18296 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 18297 verbose(env, "BPF_ALU uses reserved fields\n"); 18298 return -EINVAL; 18299 } 18300 } else if (insn->src_reg != BPF_REG_0 || 18301 (insn->off != 0 && insn->off != 1) || 18302 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 18303 verbose(env, "BPF_ALU uses reserved fields\n"); 18304 return -EINVAL; 18305 } 18306 return 0; 18307 default: 18308 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 18309 return -EINVAL; 18310 } 18311 } 18312 18313 static int check_jmp_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 18314 { 18315 u8 class = BPF_CLASS(insn->code); 18316 u8 opcode = BPF_OP(insn->code); 18317 18318 switch (opcode) { 18319 case BPF_CALL: 18320 if (BPF_SRC(insn->code) != BPF_K || 18321 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL && insn->off != 0) || 18322 (insn->src_reg != BPF_REG_0 && insn->src_reg != BPF_PSEUDO_CALL && 18323 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 18324 insn->dst_reg != BPF_REG_0 || class == BPF_JMP32) { 18325 verbose(env, "BPF_CALL uses reserved fields\n"); 18326 return -EINVAL; 18327 } 18328 return 0; 18329 case BPF_JA: 18330 if (BPF_SRC(insn->code) == BPF_X) { 18331 if (insn->src_reg != BPF_REG_0 || insn->imm != 0 || insn->off != 0) { 18332 verbose(env, "BPF_JA|BPF_X uses reserved fields\n"); 18333 return -EINVAL; 18334 } 18335 } else if (insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 18336 (class == BPF_JMP && insn->imm != 0) || 18337 (class == BPF_JMP32 && insn->off != 0)) { 18338 verbose(env, "BPF_JA uses reserved fields\n"); 18339 return -EINVAL; 18340 } 18341 return 0; 18342 case BPF_EXIT: 18343 if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || 18344 insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0 || 18345 class == BPF_JMP32) { 18346 verbose(env, "BPF_EXIT uses reserved fields\n"); 18347 return -EINVAL; 18348 } 18349 return 0; 18350 case BPF_JCOND: 18351 if (insn->code != (BPF_JMP | BPF_JCOND) || insn->src_reg != BPF_MAY_GOTO || 18352 insn->dst_reg || insn->imm) { 18353 verbose(env, "invalid may_goto imm %d\n", insn->imm); 18354 return -EINVAL; 18355 } 18356 return 0; 18357 default: 18358 if (BPF_SRC(insn->code) == BPF_X) { 18359 if (insn->imm != 0) { 18360 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18361 return -EINVAL; 18362 } 18363 } else if (insn->src_reg != BPF_REG_0) { 18364 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 18365 return -EINVAL; 18366 } 18367 return 0; 18368 } 18369 } 18370 18371 static int check_insn_fields(struct bpf_verifier_env *env, struct bpf_insn *insn) 18372 { 18373 switch (BPF_CLASS(insn->code)) { 18374 case BPF_ALU: 18375 case BPF_ALU64: 18376 return check_alu_fields(env, insn); 18377 case BPF_LDX: 18378 if ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18379 insn->imm != 0) { 18380 verbose(env, "BPF_LDX uses reserved fields\n"); 18381 return -EINVAL; 18382 } 18383 return 0; 18384 case BPF_STX: 18385 if (BPF_MODE(insn->code) == BPF_ATOMIC) 18386 return 0; 18387 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 18388 verbose(env, "BPF_STX uses reserved fields\n"); 18389 return -EINVAL; 18390 } 18391 return 0; 18392 case BPF_ST: 18393 if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { 18394 verbose(env, "BPF_ST uses reserved fields\n"); 18395 return -EINVAL; 18396 } 18397 return 0; 18398 case BPF_JMP: 18399 case BPF_JMP32: 18400 return check_jmp_fields(env, insn); 18401 case BPF_LD: { 18402 u8 mode = BPF_MODE(insn->code); 18403 18404 if (mode == BPF_ABS || mode == BPF_IND) { 18405 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 18406 BPF_SIZE(insn->code) == BPF_DW || 18407 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 18408 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 18409 return -EINVAL; 18410 } 18411 } else if (mode != BPF_IMM) { 18412 verbose(env, "invalid BPF_LD mode\n"); 18413 return -EINVAL; 18414 } 18415 return 0; 18416 } 18417 default: 18418 verbose(env, "unknown insn class %d\n", BPF_CLASS(insn->code)); 18419 return -EINVAL; 18420 } 18421 } 18422 18423 /* 18424 * Check that insns are sane and rewrite pseudo imm in ld_imm64 instructions: 18425 * 18426 * 1. if it accesses map FD, replace it with actual map pointer. 18427 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18428 * 18429 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18430 */ 18431 static int check_and_resolve_insns(struct bpf_verifier_env *env) 18432 { 18433 struct bpf_insn *insn = env->prog->insnsi; 18434 int insn_cnt = env->prog->len; 18435 int i, err; 18436 18437 err = bpf_prog_calc_tag(env->prog); 18438 if (err) 18439 return err; 18440 18441 for (i = 0; i < insn_cnt; i++, insn++) { 18442 if (insn->dst_reg >= MAX_BPF_REG) { 18443 verbose(env, "R%d is invalid\n", insn->dst_reg); 18444 return -EINVAL; 18445 } 18446 if (insn->src_reg >= MAX_BPF_REG) { 18447 verbose(env, "R%d is invalid\n", insn->src_reg); 18448 return -EINVAL; 18449 } 18450 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18451 struct bpf_insn_aux_data *aux; 18452 struct bpf_map *map; 18453 int map_idx; 18454 u64 addr; 18455 u32 fd; 18456 18457 if (i == insn_cnt - 1 || insn[1].code != 0 || 18458 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18459 insn[1].off != 0) { 18460 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18461 return -EINVAL; 18462 } 18463 18464 if (insn[0].off != 0) { 18465 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 18466 return -EINVAL; 18467 } 18468 18469 if (insn[0].src_reg == 0) 18470 /* valid generic load 64-bit imm */ 18471 goto next_insn; 18472 18473 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18474 aux = &env->insn_aux_data[i]; 18475 err = check_pseudo_btf_id(env, insn, aux); 18476 if (err) 18477 return err; 18478 goto next_insn; 18479 } 18480 18481 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18482 aux = &env->insn_aux_data[i]; 18483 aux->ptr_type = PTR_TO_FUNC; 18484 goto next_insn; 18485 } 18486 18487 /* In final convert_pseudo_ld_imm64() step, this is 18488 * converted into regular 64-bit imm load insn. 18489 */ 18490 switch (insn[0].src_reg) { 18491 case BPF_PSEUDO_MAP_VALUE: 18492 case BPF_PSEUDO_MAP_IDX_VALUE: 18493 break; 18494 case BPF_PSEUDO_MAP_FD: 18495 case BPF_PSEUDO_MAP_IDX: 18496 if (insn[1].imm == 0) 18497 break; 18498 fallthrough; 18499 default: 18500 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18501 return -EINVAL; 18502 } 18503 18504 switch (insn[0].src_reg) { 18505 case BPF_PSEUDO_MAP_IDX_VALUE: 18506 case BPF_PSEUDO_MAP_IDX: 18507 if (bpfptr_is_null(env->fd_array)) { 18508 verbose(env, "fd_idx without fd_array is invalid\n"); 18509 return -EPROTO; 18510 } 18511 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18512 insn[0].imm * sizeof(fd), 18513 sizeof(fd))) 18514 return -EFAULT; 18515 break; 18516 default: 18517 fd = insn[0].imm; 18518 break; 18519 } 18520 18521 map_idx = add_used_map(env, fd); 18522 if (map_idx < 0) 18523 return map_idx; 18524 map = env->used_maps[map_idx]; 18525 18526 aux = &env->insn_aux_data[i]; 18527 aux->map_index = map_idx; 18528 18529 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18530 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18531 addr = (unsigned long)map; 18532 } else { 18533 u32 off = insn[1].imm; 18534 18535 if (!map->ops->map_direct_value_addr) { 18536 verbose(env, "no direct value access support for this map type\n"); 18537 return -EINVAL; 18538 } 18539 18540 err = map->ops->map_direct_value_addr(map, &addr, off); 18541 if (err) { 18542 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18543 map->value_size, off); 18544 return err; 18545 } 18546 18547 aux->map_off = off; 18548 addr += off; 18549 } 18550 18551 insn[0].imm = (u32)addr; 18552 insn[1].imm = addr >> 32; 18553 18554 next_insn: 18555 insn++; 18556 i++; 18557 continue; 18558 } 18559 18560 /* Basic sanity check before we invest more work here. */ 18561 if (!bpf_opcode_in_insntable(insn->code)) { 18562 verbose(env, "unknown opcode %02x\n", insn->code); 18563 return -EINVAL; 18564 } 18565 18566 err = check_insn_fields(env, insn); 18567 if (err) 18568 return err; 18569 } 18570 18571 /* now all pseudo BPF_LD_IMM64 instructions load valid 18572 * 'struct bpf_map *' into a register instead of user map_fd. 18573 * These pointers will be used later by verifier to validate map access. 18574 */ 18575 return 0; 18576 } 18577 18578 /* drop refcnt of maps used by the rejected program */ 18579 static void release_maps(struct bpf_verifier_env *env) 18580 { 18581 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18582 env->used_map_cnt); 18583 } 18584 18585 /* drop refcnt of maps used by the rejected program */ 18586 static void release_btfs(struct bpf_verifier_env *env) 18587 { 18588 __bpf_free_used_btfs(env->used_btfs, env->used_btf_cnt); 18589 } 18590 18591 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18592 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18593 { 18594 struct bpf_insn *insn = env->prog->insnsi; 18595 int insn_cnt = env->prog->len; 18596 int i; 18597 18598 for (i = 0; i < insn_cnt; i++, insn++) { 18599 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18600 continue; 18601 if (insn->src_reg == BPF_PSEUDO_FUNC) 18602 continue; 18603 insn->src_reg = 0; 18604 } 18605 } 18606 18607 static void release_insn_arrays(struct bpf_verifier_env *env) 18608 { 18609 int i; 18610 18611 for (i = 0; i < env->insn_array_map_cnt; i++) 18612 bpf_insn_array_release(env->insn_array_maps[i]); 18613 } 18614 18615 18616 18617 /* The verifier does more data flow analysis than llvm and will not 18618 * explore branches that are dead at run time. Malicious programs can 18619 * have dead code too. Therefore replace all dead at-run-time code 18620 * with 'ja -1'. 18621 * 18622 * Just nops are not optimal, e.g. if they would sit at the end of the 18623 * program and through another bug we would manage to jump there, then 18624 * we'd execute beyond program memory otherwise. Returning exception 18625 * code also wouldn't work since we can have subprogs where the dead 18626 * code could be located. 18627 */ 18628 static void sanitize_dead_code(struct bpf_verifier_env *env) 18629 { 18630 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18631 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18632 struct bpf_insn *insn = env->prog->insnsi; 18633 const int insn_cnt = env->prog->len; 18634 int i; 18635 18636 for (i = 0; i < insn_cnt; i++) { 18637 if (aux_data[i].seen) 18638 continue; 18639 memcpy(insn + i, &trap, sizeof(trap)); 18640 aux_data[i].zext_dst = false; 18641 } 18642 } 18643 18644 18645 18646 static void free_states(struct bpf_verifier_env *env) 18647 { 18648 struct bpf_verifier_state_list *sl; 18649 struct list_head *head, *pos, *tmp; 18650 struct bpf_scc_info *info; 18651 int i, j; 18652 18653 bpf_free_verifier_state(env->cur_state, true); 18654 env->cur_state = NULL; 18655 while (!pop_stack(env, NULL, NULL, false)); 18656 18657 list_for_each_safe(pos, tmp, &env->free_list) { 18658 sl = container_of(pos, struct bpf_verifier_state_list, node); 18659 bpf_free_verifier_state(&sl->state, false); 18660 kfree(sl); 18661 } 18662 INIT_LIST_HEAD(&env->free_list); 18663 18664 for (i = 0; i < env->scc_cnt; ++i) { 18665 info = env->scc_info[i]; 18666 if (!info) 18667 continue; 18668 for (j = 0; j < info->num_visits; j++) 18669 bpf_free_backedges(&info->visits[j]); 18670 kvfree(info); 18671 env->scc_info[i] = NULL; 18672 } 18673 18674 if (!env->explored_states) 18675 return; 18676 18677 for (i = 0; i < state_htab_size(env); i++) { 18678 head = &env->explored_states[i]; 18679 18680 list_for_each_safe(pos, tmp, head) { 18681 sl = container_of(pos, struct bpf_verifier_state_list, node); 18682 bpf_free_verifier_state(&sl->state, false); 18683 kfree(sl); 18684 } 18685 INIT_LIST_HEAD(&env->explored_states[i]); 18686 } 18687 } 18688 18689 static int do_check_common(struct bpf_verifier_env *env, int subprog) 18690 { 18691 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18692 struct bpf_subprog_info *sub = subprog_info(env, subprog); 18693 struct bpf_prog_aux *aux = env->prog->aux; 18694 struct bpf_verifier_state *state; 18695 struct bpf_reg_state *regs; 18696 int ret, i; 18697 18698 env->prev_linfo = NULL; 18699 env->pass_cnt++; 18700 18701 state = kzalloc_obj(struct bpf_verifier_state, GFP_KERNEL_ACCOUNT); 18702 if (!state) 18703 return -ENOMEM; 18704 state->curframe = 0; 18705 state->speculative = false; 18706 state->branches = 1; 18707 state->in_sleepable = env->prog->sleepable; 18708 state->frame[0] = kzalloc_obj(struct bpf_func_state, GFP_KERNEL_ACCOUNT); 18709 if (!state->frame[0]) { 18710 kfree(state); 18711 return -ENOMEM; 18712 } 18713 env->cur_state = state; 18714 init_func_state(env, state->frame[0], 18715 BPF_MAIN_FUNC /* callsite */, 18716 0 /* frameno */, 18717 subprog); 18718 state->first_insn_idx = env->subprog_info[subprog].start; 18719 state->last_insn_idx = -1; 18720 18721 regs = state->frame[state->curframe]->regs; 18722 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 18723 const char *sub_name = subprog_name(env, subprog); 18724 struct bpf_subprog_arg_info *arg; 18725 struct bpf_reg_state *reg; 18726 18727 if (env->log.level & BPF_LOG_LEVEL) 18728 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 18729 ret = btf_prepare_func_args(env, subprog); 18730 if (ret) 18731 goto out; 18732 18733 if (subprog_is_exc_cb(env, subprog)) { 18734 state->frame[0]->in_exception_callback_fn = true; 18735 18736 /* 18737 * Global functions are scalar or void, make sure 18738 * we return a scalar. 18739 */ 18740 if (subprog_returns_void(env, subprog)) { 18741 verbose(env, "exception cb cannot return void\n"); 18742 ret = -EINVAL; 18743 goto out; 18744 } 18745 18746 /* Also ensure the callback only has a single scalar argument. */ 18747 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 18748 verbose(env, "exception cb only supports single integer argument\n"); 18749 ret = -EINVAL; 18750 goto out; 18751 } 18752 } 18753 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 18754 arg = &sub->args[i - BPF_REG_1]; 18755 reg = ®s[i]; 18756 18757 if (arg->arg_type == ARG_PTR_TO_CTX) { 18758 reg->type = PTR_TO_CTX; 18759 mark_reg_known_zero(env, regs, i); 18760 } else if (arg->arg_type == ARG_ANYTHING) { 18761 reg->type = SCALAR_VALUE; 18762 mark_reg_unknown(env, regs, i); 18763 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 18764 /* assume unspecial LOCAL dynptr type */ 18765 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 18766 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 18767 reg->type = PTR_TO_MEM; 18768 reg->type |= arg->arg_type & 18769 (PTR_MAYBE_NULL | PTR_UNTRUSTED | MEM_RDONLY); 18770 mark_reg_known_zero(env, regs, i); 18771 reg->mem_size = arg->mem_size; 18772 if (arg->arg_type & PTR_MAYBE_NULL) 18773 reg->id = ++env->id_gen; 18774 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 18775 reg->type = PTR_TO_BTF_ID; 18776 if (arg->arg_type & PTR_MAYBE_NULL) 18777 reg->type |= PTR_MAYBE_NULL; 18778 if (arg->arg_type & PTR_UNTRUSTED) 18779 reg->type |= PTR_UNTRUSTED; 18780 if (arg->arg_type & PTR_TRUSTED) 18781 reg->type |= PTR_TRUSTED; 18782 mark_reg_known_zero(env, regs, i); 18783 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 18784 reg->btf_id = arg->btf_id; 18785 reg->id = ++env->id_gen; 18786 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 18787 /* caller can pass either PTR_TO_ARENA or SCALAR */ 18788 mark_reg_unknown(env, regs, i); 18789 } else { 18790 verifier_bug(env, "unhandled arg#%d type %d", 18791 i - BPF_REG_1, arg->arg_type); 18792 ret = -EFAULT; 18793 goto out; 18794 } 18795 } 18796 } else { 18797 /* if main BPF program has associated BTF info, validate that 18798 * it's matching expected signature, and otherwise mark BTF 18799 * info for main program as unreliable 18800 */ 18801 if (env->prog->aux->func_info_aux) { 18802 ret = btf_prepare_func_args(env, 0); 18803 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 18804 env->prog->aux->func_info_aux[0].unreliable = true; 18805 } 18806 18807 /* 1st arg to a function */ 18808 regs[BPF_REG_1].type = PTR_TO_CTX; 18809 mark_reg_known_zero(env, regs, BPF_REG_1); 18810 } 18811 18812 /* Acquire references for struct_ops program arguments tagged with "__ref" */ 18813 if (!subprog && env->prog->type == BPF_PROG_TYPE_STRUCT_OPS) { 18814 for (i = 0; i < aux->ctx_arg_info_size; i++) 18815 aux->ctx_arg_info[i].ref_obj_id = aux->ctx_arg_info[i].refcounted ? 18816 acquire_reference(env, 0) : 0; 18817 } 18818 18819 ret = do_check(env); 18820 out: 18821 if (!ret && pop_log) 18822 bpf_vlog_reset(&env->log, 0); 18823 free_states(env); 18824 return ret; 18825 } 18826 18827 /* Lazily verify all global functions based on their BTF, if they are called 18828 * from main BPF program or any of subprograms transitively. 18829 * BPF global subprogs called from dead code are not validated. 18830 * All callable global functions must pass verification. 18831 * Otherwise the whole program is rejected. 18832 * Consider: 18833 * int bar(int); 18834 * int foo(int f) 18835 * { 18836 * return bar(f); 18837 * } 18838 * int bar(int b) 18839 * { 18840 * ... 18841 * } 18842 * foo() will be verified first for R1=any_scalar_value. During verification it 18843 * will be assumed that bar() already verified successfully and call to bar() 18844 * from foo() will be checked for type match only. Later bar() will be verified 18845 * independently to check that it's safe for R1=any_scalar_value. 18846 */ 18847 static int do_check_subprogs(struct bpf_verifier_env *env) 18848 { 18849 struct bpf_prog_aux *aux = env->prog->aux; 18850 struct bpf_func_info_aux *sub_aux; 18851 int i, ret, new_cnt; 18852 18853 if (!aux->func_info) 18854 return 0; 18855 18856 /* exception callback is presumed to be always called */ 18857 if (env->exception_callback_subprog) 18858 subprog_aux(env, env->exception_callback_subprog)->called = true; 18859 18860 again: 18861 new_cnt = 0; 18862 for (i = 1; i < env->subprog_cnt; i++) { 18863 if (!bpf_subprog_is_global(env, i)) 18864 continue; 18865 18866 sub_aux = subprog_aux(env, i); 18867 if (!sub_aux->called || sub_aux->verified) 18868 continue; 18869 18870 env->insn_idx = env->subprog_info[i].start; 18871 WARN_ON_ONCE(env->insn_idx == 0); 18872 ret = do_check_common(env, i); 18873 if (ret) { 18874 return ret; 18875 } else if (env->log.level & BPF_LOG_LEVEL) { 18876 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 18877 i, subprog_name(env, i)); 18878 } 18879 18880 /* We verified new global subprog, it might have called some 18881 * more global subprogs that we haven't verified yet, so we 18882 * need to do another pass over subprogs to verify those. 18883 */ 18884 sub_aux->verified = true; 18885 new_cnt++; 18886 } 18887 18888 /* We can't loop forever as we verify at least one global subprog on 18889 * each pass. 18890 */ 18891 if (new_cnt) 18892 goto again; 18893 18894 return 0; 18895 } 18896 18897 static int do_check_main(struct bpf_verifier_env *env) 18898 { 18899 int ret; 18900 18901 env->insn_idx = 0; 18902 ret = do_check_common(env, 0); 18903 if (!ret) 18904 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18905 return ret; 18906 } 18907 18908 18909 static void print_verification_stats(struct bpf_verifier_env *env) 18910 { 18911 int i; 18912 18913 if (env->log.level & BPF_LOG_STATS) { 18914 verbose(env, "verification time %lld usec\n", 18915 div_u64(env->verification_time, 1000)); 18916 verbose(env, "stack depth "); 18917 for (i = 0; i < env->subprog_cnt; i++) { 18918 u32 depth = env->subprog_info[i].stack_depth; 18919 18920 verbose(env, "%d", depth); 18921 if (i + 1 < env->subprog_cnt) 18922 verbose(env, "+"); 18923 } 18924 verbose(env, "\n"); 18925 } 18926 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 18927 "total_states %d peak_states %d mark_read %d\n", 18928 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 18929 env->max_states_per_insn, env->total_states, 18930 env->peak_states, env->longest_mark_read_walk); 18931 } 18932 18933 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog, 18934 const struct bpf_ctx_arg_aux *info, u32 cnt) 18935 { 18936 prog->aux->ctx_arg_info = kmemdup_array(info, cnt, sizeof(*info), GFP_KERNEL_ACCOUNT); 18937 prog->aux->ctx_arg_info_size = cnt; 18938 18939 return prog->aux->ctx_arg_info ? 0 : -ENOMEM; 18940 } 18941 18942 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 18943 { 18944 const struct btf_type *t, *func_proto; 18945 const struct bpf_struct_ops_desc *st_ops_desc; 18946 const struct bpf_struct_ops *st_ops; 18947 const struct btf_member *member; 18948 struct bpf_prog *prog = env->prog; 18949 bool has_refcounted_arg = false; 18950 u32 btf_id, member_idx, member_off; 18951 struct btf *btf; 18952 const char *mname; 18953 int i, err; 18954 18955 if (!prog->gpl_compatible) { 18956 verbose(env, "struct ops programs must have a GPL compatible license\n"); 18957 return -EINVAL; 18958 } 18959 18960 if (!prog->aux->attach_btf_id) 18961 return -ENOTSUPP; 18962 18963 btf = prog->aux->attach_btf; 18964 if (btf_is_module(btf)) { 18965 /* Make sure st_ops is valid through the lifetime of env */ 18966 env->attach_btf_mod = btf_try_get_module(btf); 18967 if (!env->attach_btf_mod) { 18968 verbose(env, "struct_ops module %s is not found\n", 18969 btf_get_name(btf)); 18970 return -ENOTSUPP; 18971 } 18972 } 18973 18974 btf_id = prog->aux->attach_btf_id; 18975 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 18976 if (!st_ops_desc) { 18977 verbose(env, "attach_btf_id %u is not a supported struct\n", 18978 btf_id); 18979 return -ENOTSUPP; 18980 } 18981 st_ops = st_ops_desc->st_ops; 18982 18983 t = st_ops_desc->type; 18984 member_idx = prog->expected_attach_type; 18985 if (member_idx >= btf_type_vlen(t)) { 18986 verbose(env, "attach to invalid member idx %u of struct %s\n", 18987 member_idx, st_ops->name); 18988 return -EINVAL; 18989 } 18990 18991 member = &btf_type_member(t)[member_idx]; 18992 mname = btf_name_by_offset(btf, member->name_off); 18993 func_proto = btf_type_resolve_func_ptr(btf, member->type, 18994 NULL); 18995 if (!func_proto) { 18996 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 18997 mname, member_idx, st_ops->name); 18998 return -EINVAL; 18999 } 19000 19001 member_off = __btf_member_bit_offset(t, member) / 8; 19002 err = bpf_struct_ops_supported(st_ops, member_off); 19003 if (err) { 19004 verbose(env, "attach to unsupported member %s of struct %s\n", 19005 mname, st_ops->name); 19006 return err; 19007 } 19008 19009 if (st_ops->check_member) { 19010 err = st_ops->check_member(t, member, prog); 19011 19012 if (err) { 19013 verbose(env, "attach to unsupported member %s of struct %s\n", 19014 mname, st_ops->name); 19015 return err; 19016 } 19017 } 19018 19019 if (prog->aux->priv_stack_requested && !bpf_jit_supports_private_stack()) { 19020 verbose(env, "Private stack not supported by jit\n"); 19021 return -EACCES; 19022 } 19023 19024 for (i = 0; i < st_ops_desc->arg_info[member_idx].cnt; i++) { 19025 if (st_ops_desc->arg_info[member_idx].info[i].refcounted) { 19026 has_refcounted_arg = true; 19027 break; 19028 } 19029 } 19030 19031 /* Tail call is not allowed for programs with refcounted arguments since we 19032 * cannot guarantee that valid refcounted kptrs will be passed to the callee. 19033 */ 19034 for (i = 0; i < env->subprog_cnt; i++) { 19035 if (has_refcounted_arg && env->subprog_info[i].has_tail_call) { 19036 verbose(env, "program with __ref argument cannot tail call\n"); 19037 return -EINVAL; 19038 } 19039 } 19040 19041 prog->aux->st_ops = st_ops; 19042 prog->aux->attach_st_ops_member_off = member_off; 19043 19044 prog->aux->attach_func_proto = func_proto; 19045 prog->aux->attach_func_name = mname; 19046 env->ops = st_ops->verifier_ops; 19047 19048 return bpf_prog_ctx_arg_info_init(prog, st_ops_desc->arg_info[member_idx].info, 19049 st_ops_desc->arg_info[member_idx].cnt); 19050 } 19051 #define SECURITY_PREFIX "security_" 19052 19053 #ifdef CONFIG_FUNCTION_ERROR_INJECTION 19054 19055 /* list of non-sleepable functions that are otherwise on 19056 * ALLOW_ERROR_INJECTION list 19057 */ 19058 BTF_SET_START(btf_non_sleepable_error_inject) 19059 /* Three functions below can be called from sleepable and non-sleepable context. 19060 * Assume non-sleepable from bpf safety point of view. 19061 */ 19062 BTF_ID(func, __filemap_add_folio) 19063 #ifdef CONFIG_FAIL_PAGE_ALLOC 19064 BTF_ID(func, should_fail_alloc_page) 19065 #endif 19066 #ifdef CONFIG_FAILSLAB 19067 BTF_ID(func, should_failslab) 19068 #endif 19069 BTF_SET_END(btf_non_sleepable_error_inject) 19070 19071 static int check_non_sleepable_error_inject(u32 btf_id) 19072 { 19073 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 19074 } 19075 19076 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 19077 { 19078 /* fentry/fexit/fmod_ret progs can be sleepable if they are 19079 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 19080 */ 19081 if (!check_non_sleepable_error_inject(btf_id) && 19082 within_error_injection_list(addr)) 19083 return 0; 19084 19085 return -EINVAL; 19086 } 19087 19088 static int check_attach_modify_return(unsigned long addr, const char *func_name) 19089 { 19090 if (within_error_injection_list(addr) || 19091 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 19092 return 0; 19093 19094 return -EINVAL; 19095 } 19096 19097 #else 19098 19099 /* Unfortunately, the arch-specific prefixes are hard-coded in arch syscall code 19100 * so we need to hard-code them, too. Ftrace has arch_syscall_match_sym_name() 19101 * but that just compares two concrete function names. 19102 */ 19103 static bool has_arch_syscall_prefix(const char *func_name) 19104 { 19105 #if defined(__x86_64__) 19106 return !strncmp(func_name, "__x64_", 6); 19107 #elif defined(__i386__) 19108 return !strncmp(func_name, "__ia32_", 7); 19109 #elif defined(__s390x__) 19110 return !strncmp(func_name, "__s390x_", 8); 19111 #elif defined(__aarch64__) 19112 return !strncmp(func_name, "__arm64_", 8); 19113 #elif defined(__riscv) 19114 return !strncmp(func_name, "__riscv_", 8); 19115 #elif defined(__powerpc__) || defined(__powerpc64__) 19116 return !strncmp(func_name, "sys_", 4); 19117 #elif defined(__loongarch__) 19118 return !strncmp(func_name, "sys_", 4); 19119 #else 19120 return false; 19121 #endif 19122 } 19123 19124 /* Without error injection, allow sleepable and fmod_ret progs on syscalls. */ 19125 19126 static int check_attach_sleepable(u32 btf_id, unsigned long addr, const char *func_name) 19127 { 19128 if (has_arch_syscall_prefix(func_name)) 19129 return 0; 19130 19131 return -EINVAL; 19132 } 19133 19134 static int check_attach_modify_return(unsigned long addr, const char *func_name) 19135 { 19136 if (has_arch_syscall_prefix(func_name) || 19137 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 19138 return 0; 19139 19140 return -EINVAL; 19141 } 19142 19143 #endif /* CONFIG_FUNCTION_ERROR_INJECTION */ 19144 19145 int bpf_check_attach_target(struct bpf_verifier_log *log, 19146 const struct bpf_prog *prog, 19147 const struct bpf_prog *tgt_prog, 19148 u32 btf_id, 19149 struct bpf_attach_target_info *tgt_info) 19150 { 19151 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 19152 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 19153 char trace_symbol[KSYM_SYMBOL_LEN]; 19154 const char prefix[] = "btf_trace_"; 19155 struct bpf_raw_event_map *btp; 19156 int ret = 0, subprog = -1, i; 19157 const struct btf_type *t; 19158 bool conservative = true; 19159 const char *tname, *fname; 19160 struct btf *btf; 19161 long addr = 0; 19162 struct module *mod = NULL; 19163 19164 if (!btf_id) { 19165 bpf_log(log, "Tracing programs must provide btf_id\n"); 19166 return -EINVAL; 19167 } 19168 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 19169 if (!btf) { 19170 bpf_log(log, 19171 "Tracing program can only be attached to another program annotated with BTF\n"); 19172 return -EINVAL; 19173 } 19174 t = btf_type_by_id(btf, btf_id); 19175 if (!t) { 19176 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 19177 return -EINVAL; 19178 } 19179 tname = btf_name_by_offset(btf, t->name_off); 19180 if (!tname) { 19181 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 19182 return -EINVAL; 19183 } 19184 if (tgt_prog) { 19185 struct bpf_prog_aux *aux = tgt_prog->aux; 19186 bool tgt_changes_pkt_data; 19187 bool tgt_might_sleep; 19188 19189 if (bpf_prog_is_dev_bound(prog->aux) && 19190 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 19191 bpf_log(log, "Target program bound device mismatch"); 19192 return -EINVAL; 19193 } 19194 19195 for (i = 0; i < aux->func_info_cnt; i++) 19196 if (aux->func_info[i].type_id == btf_id) { 19197 subprog = i; 19198 break; 19199 } 19200 if (subprog == -1) { 19201 bpf_log(log, "Subprog %s doesn't exist\n", tname); 19202 return -EINVAL; 19203 } 19204 if (aux->func && aux->func[subprog]->aux->exception_cb) { 19205 bpf_log(log, 19206 "%s programs cannot attach to exception callback\n", 19207 prog_extension ? "Extension" : "Tracing"); 19208 return -EINVAL; 19209 } 19210 conservative = aux->func_info_aux[subprog].unreliable; 19211 if (prog_extension) { 19212 if (conservative) { 19213 bpf_log(log, 19214 "Cannot replace static functions\n"); 19215 return -EINVAL; 19216 } 19217 if (!prog->jit_requested) { 19218 bpf_log(log, 19219 "Extension programs should be JITed\n"); 19220 return -EINVAL; 19221 } 19222 tgt_changes_pkt_data = aux->func 19223 ? aux->func[subprog]->aux->changes_pkt_data 19224 : aux->changes_pkt_data; 19225 if (prog->aux->changes_pkt_data && !tgt_changes_pkt_data) { 19226 bpf_log(log, 19227 "Extension program changes packet data, while original does not\n"); 19228 return -EINVAL; 19229 } 19230 19231 tgt_might_sleep = aux->func 19232 ? aux->func[subprog]->aux->might_sleep 19233 : aux->might_sleep; 19234 if (prog->aux->might_sleep && !tgt_might_sleep) { 19235 bpf_log(log, 19236 "Extension program may sleep, while original does not\n"); 19237 return -EINVAL; 19238 } 19239 } 19240 if (!tgt_prog->jited) { 19241 bpf_log(log, "Can attach to only JITed progs\n"); 19242 return -EINVAL; 19243 } 19244 if (prog_tracing) { 19245 if (aux->attach_tracing_prog) { 19246 /* 19247 * Target program is an fentry/fexit which is already attached 19248 * to another tracing program. More levels of nesting 19249 * attachment are not allowed. 19250 */ 19251 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 19252 return -EINVAL; 19253 } 19254 } else if (tgt_prog->type == prog->type) { 19255 /* 19256 * To avoid potential call chain cycles, prevent attaching of a 19257 * program extension to another extension. It's ok to attach 19258 * fentry/fexit to extension program. 19259 */ 19260 bpf_log(log, "Cannot recursively attach\n"); 19261 return -EINVAL; 19262 } 19263 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 19264 prog_extension && 19265 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 19266 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT || 19267 tgt_prog->expected_attach_type == BPF_TRACE_FSESSION)) { 19268 /* Program extensions can extend all program types 19269 * except fentry/fexit. The reason is the following. 19270 * The fentry/fexit programs are used for performance 19271 * analysis, stats and can be attached to any program 19272 * type. When extension program is replacing XDP function 19273 * it is necessary to allow performance analysis of all 19274 * functions. Both original XDP program and its program 19275 * extension. Hence attaching fentry/fexit to 19276 * BPF_PROG_TYPE_EXT is allowed. If extending of 19277 * fentry/fexit was allowed it would be possible to create 19278 * long call chain fentry->extension->fentry->extension 19279 * beyond reasonable stack size. Hence extending fentry 19280 * is not allowed. 19281 */ 19282 bpf_log(log, "Cannot extend fentry/fexit/fsession\n"); 19283 return -EINVAL; 19284 } 19285 } else { 19286 if (prog_extension) { 19287 bpf_log(log, "Cannot replace kernel functions\n"); 19288 return -EINVAL; 19289 } 19290 } 19291 19292 switch (prog->expected_attach_type) { 19293 case BPF_TRACE_RAW_TP: 19294 if (tgt_prog) { 19295 bpf_log(log, 19296 "Only FENTRY/FEXIT/FSESSION progs are attachable to another BPF prog\n"); 19297 return -EINVAL; 19298 } 19299 if (!btf_type_is_typedef(t)) { 19300 bpf_log(log, "attach_btf_id %u is not a typedef\n", 19301 btf_id); 19302 return -EINVAL; 19303 } 19304 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 19305 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 19306 btf_id, tname); 19307 return -EINVAL; 19308 } 19309 tname += sizeof(prefix) - 1; 19310 19311 /* The func_proto of "btf_trace_##tname" is generated from typedef without argument 19312 * names. Thus using bpf_raw_event_map to get argument names. 19313 */ 19314 btp = bpf_get_raw_tracepoint(tname); 19315 if (!btp) 19316 return -EINVAL; 19317 fname = kallsyms_lookup((unsigned long)btp->bpf_func, NULL, NULL, NULL, 19318 trace_symbol); 19319 bpf_put_raw_tracepoint(btp); 19320 19321 if (fname) 19322 ret = btf_find_by_name_kind(btf, fname, BTF_KIND_FUNC); 19323 19324 if (!fname || ret < 0) { 19325 bpf_log(log, "Cannot find btf of tracepoint template, fall back to %s%s.\n", 19326 prefix, tname); 19327 t = btf_type_by_id(btf, t->type); 19328 if (!btf_type_is_ptr(t)) 19329 /* should never happen in valid vmlinux build */ 19330 return -EINVAL; 19331 } else { 19332 t = btf_type_by_id(btf, ret); 19333 if (!btf_type_is_func(t)) 19334 /* should never happen in valid vmlinux build */ 19335 return -EINVAL; 19336 } 19337 19338 t = btf_type_by_id(btf, t->type); 19339 if (!btf_type_is_func_proto(t)) 19340 /* should never happen in valid vmlinux build */ 19341 return -EINVAL; 19342 19343 break; 19344 case BPF_TRACE_ITER: 19345 if (!btf_type_is_func(t)) { 19346 bpf_log(log, "attach_btf_id %u is not a function\n", 19347 btf_id); 19348 return -EINVAL; 19349 } 19350 t = btf_type_by_id(btf, t->type); 19351 if (!btf_type_is_func_proto(t)) 19352 return -EINVAL; 19353 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19354 if (ret) 19355 return ret; 19356 break; 19357 default: 19358 if (!prog_extension) 19359 return -EINVAL; 19360 fallthrough; 19361 case BPF_MODIFY_RETURN: 19362 case BPF_LSM_MAC: 19363 case BPF_LSM_CGROUP: 19364 case BPF_TRACE_FENTRY: 19365 case BPF_TRACE_FEXIT: 19366 case BPF_TRACE_FSESSION: 19367 if (prog->expected_attach_type == BPF_TRACE_FSESSION && 19368 !bpf_jit_supports_fsession()) { 19369 bpf_log(log, "JIT does not support fsession\n"); 19370 return -EOPNOTSUPP; 19371 } 19372 if (!btf_type_is_func(t)) { 19373 bpf_log(log, "attach_btf_id %u is not a function\n", 19374 btf_id); 19375 return -EINVAL; 19376 } 19377 if (prog_extension && 19378 btf_check_type_match(log, prog, btf, t)) 19379 return -EINVAL; 19380 t = btf_type_by_id(btf, t->type); 19381 if (!btf_type_is_func_proto(t)) 19382 return -EINVAL; 19383 19384 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 19385 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 19386 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 19387 return -EINVAL; 19388 19389 if (tgt_prog && conservative) 19390 t = NULL; 19391 19392 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 19393 if (ret < 0) 19394 return ret; 19395 19396 if (tgt_prog) { 19397 if (subprog == 0) 19398 addr = (long) tgt_prog->bpf_func; 19399 else 19400 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 19401 } else { 19402 if (btf_is_module(btf)) { 19403 mod = btf_try_get_module(btf); 19404 if (mod) 19405 addr = find_kallsyms_symbol_value(mod, tname); 19406 else 19407 addr = 0; 19408 } else { 19409 addr = kallsyms_lookup_name(tname); 19410 } 19411 if (!addr) { 19412 module_put(mod); 19413 bpf_log(log, 19414 "The address of function %s cannot be found\n", 19415 tname); 19416 return -ENOENT; 19417 } 19418 } 19419 19420 if (prog->sleepable) { 19421 ret = -EINVAL; 19422 switch (prog->type) { 19423 case BPF_PROG_TYPE_TRACING: 19424 if (!check_attach_sleepable(btf_id, addr, tname)) 19425 ret = 0; 19426 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 19427 * in the fmodret id set with the KF_SLEEPABLE flag. 19428 */ 19429 else { 19430 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 19431 prog); 19432 19433 if (flags && (*flags & KF_SLEEPABLE)) 19434 ret = 0; 19435 } 19436 break; 19437 case BPF_PROG_TYPE_LSM: 19438 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 19439 * Only some of them are sleepable. 19440 */ 19441 if (bpf_lsm_is_sleepable_hook(btf_id)) 19442 ret = 0; 19443 break; 19444 default: 19445 break; 19446 } 19447 if (ret) { 19448 module_put(mod); 19449 bpf_log(log, "%s is not sleepable\n", tname); 19450 return ret; 19451 } 19452 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 19453 if (tgt_prog) { 19454 module_put(mod); 19455 bpf_log(log, "can't modify return codes of BPF programs\n"); 19456 return -EINVAL; 19457 } 19458 ret = -EINVAL; 19459 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 19460 !check_attach_modify_return(addr, tname)) 19461 ret = 0; 19462 if (ret) { 19463 module_put(mod); 19464 bpf_log(log, "%s() is not modifiable\n", tname); 19465 return ret; 19466 } 19467 } 19468 19469 break; 19470 } 19471 tgt_info->tgt_addr = addr; 19472 tgt_info->tgt_name = tname; 19473 tgt_info->tgt_type = t; 19474 tgt_info->tgt_mod = mod; 19475 return 0; 19476 } 19477 19478 BTF_SET_START(btf_id_deny) 19479 BTF_ID_UNUSED 19480 #ifdef CONFIG_SMP 19481 BTF_ID(func, ___migrate_enable) 19482 BTF_ID(func, migrate_disable) 19483 BTF_ID(func, migrate_enable) 19484 #endif 19485 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 19486 BTF_ID(func, rcu_read_unlock_strict) 19487 #endif 19488 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 19489 BTF_ID(func, preempt_count_add) 19490 BTF_ID(func, preempt_count_sub) 19491 #endif 19492 #ifdef CONFIG_PREEMPT_RCU 19493 BTF_ID(func, __rcu_read_lock) 19494 BTF_ID(func, __rcu_read_unlock) 19495 #endif 19496 BTF_SET_END(btf_id_deny) 19497 19498 /* fexit and fmod_ret can't be used to attach to __noreturn functions. 19499 * Currently, we must manually list all __noreturn functions here. Once a more 19500 * robust solution is implemented, this workaround can be removed. 19501 */ 19502 BTF_SET_START(noreturn_deny) 19503 #ifdef CONFIG_IA32_EMULATION 19504 BTF_ID(func, __ia32_sys_exit) 19505 BTF_ID(func, __ia32_sys_exit_group) 19506 #endif 19507 #ifdef CONFIG_KUNIT 19508 BTF_ID(func, __kunit_abort) 19509 BTF_ID(func, kunit_try_catch_throw) 19510 #endif 19511 #ifdef CONFIG_MODULES 19512 BTF_ID(func, __module_put_and_kthread_exit) 19513 #endif 19514 #ifdef CONFIG_X86_64 19515 BTF_ID(func, __x64_sys_exit) 19516 BTF_ID(func, __x64_sys_exit_group) 19517 #endif 19518 BTF_ID(func, do_exit) 19519 BTF_ID(func, do_group_exit) 19520 BTF_ID(func, kthread_complete_and_exit) 19521 BTF_ID(func, make_task_dead) 19522 BTF_SET_END(noreturn_deny) 19523 19524 static bool can_be_sleepable(struct bpf_prog *prog) 19525 { 19526 if (prog->type == BPF_PROG_TYPE_TRACING) { 19527 switch (prog->expected_attach_type) { 19528 case BPF_TRACE_FENTRY: 19529 case BPF_TRACE_FEXIT: 19530 case BPF_MODIFY_RETURN: 19531 case BPF_TRACE_ITER: 19532 case BPF_TRACE_FSESSION: 19533 return true; 19534 default: 19535 return false; 19536 } 19537 } 19538 return prog->type == BPF_PROG_TYPE_LSM || 19539 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 19540 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 19541 } 19542 19543 static int check_attach_btf_id(struct bpf_verifier_env *env) 19544 { 19545 struct bpf_prog *prog = env->prog; 19546 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 19547 struct bpf_attach_target_info tgt_info = {}; 19548 u32 btf_id = prog->aux->attach_btf_id; 19549 struct bpf_trampoline *tr; 19550 int ret; 19551 u64 key; 19552 19553 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 19554 if (prog->sleepable) 19555 /* attach_btf_id checked to be zero already */ 19556 return 0; 19557 verbose(env, "Syscall programs can only be sleepable\n"); 19558 return -EINVAL; 19559 } 19560 19561 if (prog->sleepable && !can_be_sleepable(prog)) { 19562 verbose(env, "Only fentry/fexit/fsession/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 19563 return -EINVAL; 19564 } 19565 19566 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 19567 return check_struct_ops_btf_id(env); 19568 19569 if (prog->type != BPF_PROG_TYPE_TRACING && 19570 prog->type != BPF_PROG_TYPE_LSM && 19571 prog->type != BPF_PROG_TYPE_EXT) 19572 return 0; 19573 19574 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 19575 if (ret) 19576 return ret; 19577 19578 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 19579 /* to make freplace equivalent to their targets, they need to 19580 * inherit env->ops and expected_attach_type for the rest of the 19581 * verification 19582 */ 19583 env->ops = bpf_verifier_ops[tgt_prog->type]; 19584 prog->expected_attach_type = tgt_prog->expected_attach_type; 19585 } 19586 19587 /* store info about the attachment target that will be used later */ 19588 prog->aux->attach_func_proto = tgt_info.tgt_type; 19589 prog->aux->attach_func_name = tgt_info.tgt_name; 19590 prog->aux->mod = tgt_info.tgt_mod; 19591 19592 if (tgt_prog) { 19593 prog->aux->saved_dst_prog_type = tgt_prog->type; 19594 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 19595 } 19596 19597 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 19598 prog->aux->attach_btf_trace = true; 19599 return 0; 19600 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 19601 return bpf_iter_prog_supported(prog); 19602 } 19603 19604 if (prog->type == BPF_PROG_TYPE_LSM) { 19605 ret = bpf_lsm_verify_prog(&env->log, prog); 19606 if (ret < 0) 19607 return ret; 19608 } else if (prog->type == BPF_PROG_TYPE_TRACING && 19609 btf_id_set_contains(&btf_id_deny, btf_id)) { 19610 verbose(env, "Attaching tracing programs to function '%s' is rejected.\n", 19611 tgt_info.tgt_name); 19612 return -EINVAL; 19613 } else if ((prog->expected_attach_type == BPF_TRACE_FEXIT || 19614 prog->expected_attach_type == BPF_TRACE_FSESSION || 19615 prog->expected_attach_type == BPF_MODIFY_RETURN) && 19616 btf_id_set_contains(&noreturn_deny, btf_id)) { 19617 verbose(env, "Attaching fexit/fsession/fmod_ret to __noreturn function '%s' is rejected.\n", 19618 tgt_info.tgt_name); 19619 return -EINVAL; 19620 } 19621 19622 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 19623 tr = bpf_trampoline_get(key, &tgt_info); 19624 if (!tr) 19625 return -ENOMEM; 19626 19627 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 19628 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 19629 19630 prog->aux->dst_trampoline = tr; 19631 return 0; 19632 } 19633 19634 struct btf *bpf_get_btf_vmlinux(void) 19635 { 19636 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 19637 mutex_lock(&bpf_verifier_lock); 19638 if (!btf_vmlinux) 19639 btf_vmlinux = btf_parse_vmlinux(); 19640 mutex_unlock(&bpf_verifier_lock); 19641 } 19642 return btf_vmlinux; 19643 } 19644 19645 /* 19646 * The add_fd_from_fd_array() is executed only if fd_array_cnt is non-zero. In 19647 * this case expect that every file descriptor in the array is either a map or 19648 * a BTF. Everything else is considered to be trash. 19649 */ 19650 static int add_fd_from_fd_array(struct bpf_verifier_env *env, int fd) 19651 { 19652 struct bpf_map *map; 19653 struct btf *btf; 19654 CLASS(fd, f)(fd); 19655 int err; 19656 19657 map = __bpf_map_get(f); 19658 if (!IS_ERR(map)) { 19659 err = __add_used_map(env, map); 19660 if (err < 0) 19661 return err; 19662 return 0; 19663 } 19664 19665 btf = __btf_get_by_fd(f); 19666 if (!IS_ERR(btf)) { 19667 btf_get(btf); 19668 return __add_used_btf(env, btf); 19669 } 19670 19671 verbose(env, "fd %d is not pointing to valid bpf_map or btf\n", fd); 19672 return PTR_ERR(map); 19673 } 19674 19675 static int process_fd_array(struct bpf_verifier_env *env, union bpf_attr *attr, bpfptr_t uattr) 19676 { 19677 size_t size = sizeof(int); 19678 int ret; 19679 int fd; 19680 u32 i; 19681 19682 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 19683 19684 /* 19685 * The only difference between old (no fd_array_cnt is given) and new 19686 * APIs is that in the latter case the fd_array is expected to be 19687 * continuous and is scanned for map fds right away 19688 */ 19689 if (!attr->fd_array_cnt) 19690 return 0; 19691 19692 /* Check for integer overflow */ 19693 if (attr->fd_array_cnt >= (U32_MAX / size)) { 19694 verbose(env, "fd_array_cnt is too big (%u)\n", attr->fd_array_cnt); 19695 return -EINVAL; 19696 } 19697 19698 for (i = 0; i < attr->fd_array_cnt; i++) { 19699 if (copy_from_bpfptr_offset(&fd, env->fd_array, i * size, size)) 19700 return -EFAULT; 19701 19702 ret = add_fd_from_fd_array(env, fd); 19703 if (ret) 19704 return ret; 19705 } 19706 19707 return 0; 19708 } 19709 19710 /* replace a generic kfunc with a specialized version if necessary */ 19711 static int specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc, int insn_idx) 19712 { 19713 struct bpf_prog *prog = env->prog; 19714 bool seen_direct_write; 19715 void *xdp_kfunc; 19716 bool is_rdonly; 19717 u32 func_id = desc->func_id; 19718 u16 offset = desc->offset; 19719 unsigned long addr = desc->addr; 19720 19721 if (offset) /* return if module BTF is used */ 19722 return 0; 19723 19724 if (bpf_dev_bound_kfunc_id(func_id)) { 19725 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19726 if (xdp_kfunc) 19727 addr = (unsigned long)xdp_kfunc; 19728 /* fallback to default kfunc when not supported by netdev */ 19729 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19730 seen_direct_write = env->seen_direct_write; 19731 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19732 19733 if (is_rdonly) 19734 addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19735 19736 /* restore env->seen_direct_write to its original value, since 19737 * may_access_direct_pkt_data mutates it 19738 */ 19739 env->seen_direct_write = seen_direct_write; 19740 } else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) { 19741 if (bpf_lsm_has_d_inode_locked(prog)) 19742 addr = (unsigned long)bpf_set_dentry_xattr_locked; 19743 } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) { 19744 if (bpf_lsm_has_d_inode_locked(prog)) 19745 addr = (unsigned long)bpf_remove_dentry_xattr_locked; 19746 } else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) { 19747 if (!env->insn_aux_data[insn_idx].non_sleepable) 19748 addr = (unsigned long)bpf_dynptr_from_file_sleepable; 19749 } else if (func_id == special_kfunc_list[KF_bpf_arena_alloc_pages]) { 19750 if (env->insn_aux_data[insn_idx].non_sleepable) 19751 addr = (unsigned long)bpf_arena_alloc_pages_non_sleepable; 19752 } else if (func_id == special_kfunc_list[KF_bpf_arena_free_pages]) { 19753 if (env->insn_aux_data[insn_idx].non_sleepable) 19754 addr = (unsigned long)bpf_arena_free_pages_non_sleepable; 19755 } 19756 desc->addr = addr; 19757 return 0; 19758 } 19759 19760 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19761 u16 struct_meta_reg, 19762 u16 node_offset_reg, 19763 struct bpf_insn *insn, 19764 struct bpf_insn *insn_buf, 19765 int *cnt) 19766 { 19767 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19768 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19769 19770 insn_buf[0] = addr[0]; 19771 insn_buf[1] = addr[1]; 19772 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19773 insn_buf[3] = *insn; 19774 *cnt = 4; 19775 } 19776 19777 int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19778 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19779 { 19780 struct bpf_kfunc_desc *desc; 19781 int err; 19782 19783 if (!insn->imm) { 19784 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19785 return -EINVAL; 19786 } 19787 19788 *cnt = 0; 19789 19790 /* insn->imm has the btf func_id. Replace it with an offset relative to 19791 * __bpf_call_base, unless the JIT needs to call functions that are 19792 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19793 */ 19794 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19795 if (!desc) { 19796 verifier_bug(env, "kernel function descriptor not found for func_id %u", 19797 insn->imm); 19798 return -EFAULT; 19799 } 19800 19801 err = specialize_kfunc(env, desc, insn_idx); 19802 if (err) 19803 return err; 19804 19805 if (!bpf_jit_supports_far_kfunc_call()) 19806 insn->imm = BPF_CALL_IMM(desc->addr); 19807 19808 if (is_bpf_obj_new_kfunc(desc->func_id) || is_bpf_percpu_obj_new_kfunc(desc->func_id)) { 19809 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19810 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19811 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19812 19813 if (is_bpf_percpu_obj_new_kfunc(desc->func_id) && kptr_struct_meta) { 19814 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19815 insn_idx); 19816 return -EFAULT; 19817 } 19818 19819 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19820 insn_buf[1] = addr[0]; 19821 insn_buf[2] = addr[1]; 19822 insn_buf[3] = *insn; 19823 *cnt = 4; 19824 } else if (is_bpf_obj_drop_kfunc(desc->func_id) || 19825 is_bpf_percpu_obj_drop_kfunc(desc->func_id) || 19826 is_bpf_refcount_acquire_kfunc(desc->func_id)) { 19827 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19828 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19829 19830 if (is_bpf_percpu_obj_drop_kfunc(desc->func_id) && kptr_struct_meta) { 19831 verifier_bug(env, "NULL kptr_struct_meta expected at insn_idx %d", 19832 insn_idx); 19833 return -EFAULT; 19834 } 19835 19836 if (is_bpf_refcount_acquire_kfunc(desc->func_id) && !kptr_struct_meta) { 19837 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19838 insn_idx); 19839 return -EFAULT; 19840 } 19841 19842 insn_buf[0] = addr[0]; 19843 insn_buf[1] = addr[1]; 19844 insn_buf[2] = *insn; 19845 *cnt = 3; 19846 } else if (is_bpf_list_push_kfunc(desc->func_id) || 19847 is_bpf_rbtree_add_kfunc(desc->func_id)) { 19848 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19849 int struct_meta_reg = BPF_REG_3; 19850 int node_offset_reg = BPF_REG_4; 19851 19852 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19853 if (is_bpf_rbtree_add_kfunc(desc->func_id)) { 19854 struct_meta_reg = BPF_REG_4; 19855 node_offset_reg = BPF_REG_5; 19856 } 19857 19858 if (!kptr_struct_meta) { 19859 verifier_bug(env, "kptr_struct_meta expected at insn_idx %d", 19860 insn_idx); 19861 return -EFAULT; 19862 } 19863 19864 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19865 node_offset_reg, insn, insn_buf, cnt); 19866 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19867 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19868 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19869 *cnt = 1; 19870 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_is_return] && 19871 env->prog->expected_attach_type == BPF_TRACE_FSESSION) { 19872 /* 19873 * inline the bpf_session_is_return() for fsession: 19874 * bool bpf_session_is_return(void *ctx) 19875 * { 19876 * return (((u64 *)ctx)[-1] >> BPF_TRAMP_IS_RETURN_SHIFT) & 1; 19877 * } 19878 */ 19879 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19880 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_IS_RETURN_SHIFT); 19881 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 1); 19882 *cnt = 3; 19883 } else if (desc->func_id == special_kfunc_list[KF_bpf_session_cookie] && 19884 env->prog->expected_attach_type == BPF_TRACE_FSESSION) { 19885 /* 19886 * inline bpf_session_cookie() for fsession: 19887 * __u64 *bpf_session_cookie(void *ctx) 19888 * { 19889 * u64 off = (((u64 *)ctx)[-1] >> BPF_TRAMP_COOKIE_INDEX_SHIFT) & 0xFF; 19890 * return &((u64 *)ctx)[-off]; 19891 * } 19892 */ 19893 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 19894 insn_buf[1] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_0, BPF_TRAMP_COOKIE_INDEX_SHIFT); 19895 insn_buf[2] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF); 19896 insn_buf[3] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 19897 insn_buf[4] = BPF_ALU64_REG(BPF_SUB, BPF_REG_0, BPF_REG_1); 19898 insn_buf[5] = BPF_ALU64_IMM(BPF_NEG, BPF_REG_0, 0); 19899 *cnt = 6; 19900 } 19901 19902 if (env->insn_aux_data[insn_idx].arg_prog) { 19903 u32 regno = env->insn_aux_data[insn_idx].arg_prog; 19904 struct bpf_insn ld_addrs[2] = { BPF_LD_IMM64(regno, (long)env->prog->aux) }; 19905 int idx = *cnt; 19906 19907 insn_buf[idx++] = ld_addrs[0]; 19908 insn_buf[idx++] = ld_addrs[1]; 19909 insn_buf[idx++] = *insn; 19910 *cnt = idx; 19911 } 19912 return 0; 19913 } 19914 19915 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 19916 { 19917 u64 start_time = ktime_get_ns(); 19918 struct bpf_verifier_env *env; 19919 int i, len, ret = -EINVAL, err; 19920 u32 log_true_size; 19921 bool is_priv; 19922 19923 BTF_TYPE_EMIT(enum bpf_features); 19924 19925 /* no program is valid */ 19926 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 19927 return -EINVAL; 19928 19929 /* 'struct bpf_verifier_env' can be global, but since it's not small, 19930 * allocate/free it every time bpf_check() is called 19931 */ 19932 env = kvzalloc_obj(struct bpf_verifier_env, GFP_KERNEL_ACCOUNT); 19933 if (!env) 19934 return -ENOMEM; 19935 19936 env->bt.env = env; 19937 19938 len = (*prog)->len; 19939 env->insn_aux_data = 19940 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 19941 ret = -ENOMEM; 19942 if (!env->insn_aux_data) 19943 goto err_free_env; 19944 for (i = 0; i < len; i++) 19945 env->insn_aux_data[i].orig_idx = i; 19946 env->succ = bpf_iarray_realloc(NULL, 2); 19947 if (!env->succ) 19948 goto err_free_env; 19949 env->prog = *prog; 19950 env->ops = bpf_verifier_ops[env->prog->type]; 19951 19952 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 19953 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 19954 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 19955 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 19956 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 19957 19958 bpf_get_btf_vmlinux(); 19959 19960 /* grab the mutex to protect few globals used by verifier */ 19961 if (!is_priv) 19962 mutex_lock(&bpf_verifier_lock); 19963 19964 /* user could have requested verbose verifier output 19965 * and supplied buffer to store the verification trace 19966 */ 19967 ret = bpf_vlog_init(&env->log, attr->log_level, 19968 (char __user *) (unsigned long) attr->log_buf, 19969 attr->log_size); 19970 if (ret) 19971 goto err_unlock; 19972 19973 ret = process_fd_array(env, attr, uattr); 19974 if (ret) 19975 goto skip_full_check; 19976 19977 mark_verifier_state_clean(env); 19978 19979 if (IS_ERR(btf_vmlinux)) { 19980 /* Either gcc or pahole or kernel are broken. */ 19981 verbose(env, "in-kernel BTF is malformed\n"); 19982 ret = PTR_ERR(btf_vmlinux); 19983 goto skip_full_check; 19984 } 19985 19986 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 19987 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 19988 env->strict_alignment = true; 19989 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 19990 env->strict_alignment = false; 19991 19992 if (is_priv) 19993 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 19994 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 19995 19996 env->explored_states = kvzalloc_objs(struct list_head, 19997 state_htab_size(env), 19998 GFP_KERNEL_ACCOUNT); 19999 ret = -ENOMEM; 20000 if (!env->explored_states) 20001 goto skip_full_check; 20002 20003 for (i = 0; i < state_htab_size(env); i++) 20004 INIT_LIST_HEAD(&env->explored_states[i]); 20005 INIT_LIST_HEAD(&env->free_list); 20006 20007 ret = bpf_check_btf_info_early(env, attr, uattr); 20008 if (ret < 0) 20009 goto skip_full_check; 20010 20011 ret = add_subprog_and_kfunc(env); 20012 if (ret < 0) 20013 goto skip_full_check; 20014 20015 ret = check_subprogs(env); 20016 if (ret < 0) 20017 goto skip_full_check; 20018 20019 ret = bpf_check_btf_info(env, attr, uattr); 20020 if (ret < 0) 20021 goto skip_full_check; 20022 20023 ret = check_and_resolve_insns(env); 20024 if (ret < 0) 20025 goto skip_full_check; 20026 20027 if (bpf_prog_is_offloaded(env->prog->aux)) { 20028 ret = bpf_prog_offload_verifier_prep(env->prog); 20029 if (ret) 20030 goto skip_full_check; 20031 } 20032 20033 ret = bpf_check_cfg(env); 20034 if (ret < 0) 20035 goto skip_full_check; 20036 20037 ret = bpf_compute_postorder(env); 20038 if (ret < 0) 20039 goto skip_full_check; 20040 20041 ret = bpf_stack_liveness_init(env); 20042 if (ret) 20043 goto skip_full_check; 20044 20045 ret = check_attach_btf_id(env); 20046 if (ret) 20047 goto skip_full_check; 20048 20049 ret = bpf_compute_const_regs(env); 20050 if (ret < 0) 20051 goto skip_full_check; 20052 20053 ret = bpf_prune_dead_branches(env); 20054 if (ret < 0) 20055 goto skip_full_check; 20056 20057 ret = sort_subprogs_topo(env); 20058 if (ret < 0) 20059 goto skip_full_check; 20060 20061 ret = bpf_compute_scc(env); 20062 if (ret < 0) 20063 goto skip_full_check; 20064 20065 ret = bpf_compute_live_registers(env); 20066 if (ret < 0) 20067 goto skip_full_check; 20068 20069 ret = mark_fastcall_patterns(env); 20070 if (ret < 0) 20071 goto skip_full_check; 20072 20073 ret = do_check_main(env); 20074 ret = ret ?: do_check_subprogs(env); 20075 20076 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 20077 ret = bpf_prog_offload_finalize(env); 20078 20079 skip_full_check: 20080 kvfree(env->explored_states); 20081 20082 /* might decrease stack depth, keep it before passes that 20083 * allocate additional slots. 20084 */ 20085 if (ret == 0) 20086 ret = bpf_remove_fastcall_spills_fills(env); 20087 20088 if (ret == 0) 20089 ret = check_max_stack_depth(env); 20090 20091 /* instruction rewrites happen after this point */ 20092 if (ret == 0) 20093 ret = bpf_optimize_bpf_loop(env); 20094 20095 if (is_priv) { 20096 if (ret == 0) 20097 bpf_opt_hard_wire_dead_code_branches(env); 20098 if (ret == 0) 20099 ret = bpf_opt_remove_dead_code(env); 20100 if (ret == 0) 20101 ret = bpf_opt_remove_nops(env); 20102 } else { 20103 if (ret == 0) 20104 sanitize_dead_code(env); 20105 } 20106 20107 if (ret == 0) 20108 /* program is valid, convert *(u32*)(ctx + off) accesses */ 20109 ret = bpf_convert_ctx_accesses(env); 20110 20111 if (ret == 0) 20112 ret = bpf_do_misc_fixups(env); 20113 20114 /* do 32-bit optimization after insn patching has done so those patched 20115 * insns could be handled correctly. 20116 */ 20117 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 20118 ret = bpf_opt_subreg_zext_lo32_rnd_hi32(env, attr); 20119 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 20120 : false; 20121 } 20122 20123 if (ret == 0) 20124 ret = bpf_fixup_call_args(env); 20125 20126 env->verification_time = ktime_get_ns() - start_time; 20127 print_verification_stats(env); 20128 env->prog->aux->verified_insns = env->insn_processed; 20129 20130 /* preserve original error even if log finalization is successful */ 20131 err = bpf_vlog_finalize(&env->log, &log_true_size); 20132 if (err) 20133 ret = err; 20134 20135 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 20136 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 20137 &log_true_size, sizeof(log_true_size))) { 20138 ret = -EFAULT; 20139 goto err_release_maps; 20140 } 20141 20142 if (ret) 20143 goto err_release_maps; 20144 20145 if (env->used_map_cnt) { 20146 /* if program passed verifier, update used_maps in bpf_prog_info */ 20147 env->prog->aux->used_maps = kmalloc_objs(env->used_maps[0], 20148 env->used_map_cnt, 20149 GFP_KERNEL_ACCOUNT); 20150 20151 if (!env->prog->aux->used_maps) { 20152 ret = -ENOMEM; 20153 goto err_release_maps; 20154 } 20155 20156 memcpy(env->prog->aux->used_maps, env->used_maps, 20157 sizeof(env->used_maps[0]) * env->used_map_cnt); 20158 env->prog->aux->used_map_cnt = env->used_map_cnt; 20159 } 20160 if (env->used_btf_cnt) { 20161 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 20162 env->prog->aux->used_btfs = kmalloc_objs(env->used_btfs[0], 20163 env->used_btf_cnt, 20164 GFP_KERNEL_ACCOUNT); 20165 if (!env->prog->aux->used_btfs) { 20166 ret = -ENOMEM; 20167 goto err_release_maps; 20168 } 20169 20170 memcpy(env->prog->aux->used_btfs, env->used_btfs, 20171 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 20172 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 20173 } 20174 if (env->used_map_cnt || env->used_btf_cnt) { 20175 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 20176 * bpf_ld_imm64 instructions 20177 */ 20178 convert_pseudo_ld_imm64(env); 20179 } 20180 20181 adjust_btf_func(env); 20182 20183 /* extension progs temporarily inherit the attach_type of their targets 20184 for verification purposes, so set it back to zero before returning 20185 */ 20186 if (env->prog->type == BPF_PROG_TYPE_EXT) 20187 env->prog->expected_attach_type = 0; 20188 20189 env->prog = __bpf_prog_select_runtime(env, env->prog, &ret); 20190 20191 err_release_maps: 20192 if (ret) 20193 release_insn_arrays(env); 20194 if (!env->prog->aux->used_maps) 20195 /* if we didn't copy map pointers into bpf_prog_info, release 20196 * them now. Otherwise free_used_maps() will release them. 20197 */ 20198 release_maps(env); 20199 if (!env->prog->aux->used_btfs) 20200 release_btfs(env); 20201 20202 *prog = env->prog; 20203 20204 module_put(env->attach_btf_mod); 20205 err_unlock: 20206 if (!is_priv) 20207 mutex_unlock(&bpf_verifier_lock); 20208 bpf_clear_insn_aux_data(env, 0, env->prog->len); 20209 vfree(env->insn_aux_data); 20210 err_free_env: 20211 bpf_stack_liveness_free(env); 20212 kvfree(env->cfg.insn_postorder); 20213 kvfree(env->scc_info); 20214 kvfree(env->succ); 20215 kvfree(env->gotox_tmp_buf); 20216 kvfree(env); 20217 return ret; 20218 } 20219